resolveIndexOfVariables static method

void resolveIndexOfVariables(
  1. List<Variable> variables
)

Implementation

static void resolveIndexOfVariables(List<Variable> variables) {
  // sort variables by the order in which they appear inside the statement.
  variables.sort((a, b) {
    return a.firstPosition.compareTo(b.firstPosition);
  });
  // Assigning rules are explained at https://www.sqlite.org/lang_expr.html#varparam
  var largestAssigned = 0;
  final resolvedNames = <String, int>{};

  for (final variable in variables) {
    if (variable is NumberedVariable) {
      // if the variable has an explicit index (e.g ?123), then 123 is the
      // resolved index and the next variable will have index 124. Otherwise,
      // just assigned the current largest assigned index plus one.
      if (variable.explicitIndex != null) {
        final index = variable.resolvedIndex = variable.explicitIndex!;
        largestAssigned = max(largestAssigned, index);
      } else {
        variable.resolvedIndex = largestAssigned + 1;
        largestAssigned++;
      }
    } else if (variable is ColonNamedVariable) {
      // named variables behave just like numbered vars without an explicit
      // index, but of course two variables with the same name must have the
      // same index.
      final index = resolvedNames.putIfAbsent(variable.name, () {
        return ++largestAssigned;
      });
      variable.resolvedIndex = index;
    }
  }
}