SqlBuilder.insert constructor

SqlBuilder.insert(
  1. String table,
  2. Map<String, Object?> values, {
  3. String? nullColumnHack,
  4. ConflictAlgorithm? conflictAlgorithm,
})

Convenience method for inserting a row into the database. Parameters: @table the table to insert the row into @nullColumnHack optional; may be null. SQL doesn't allow inserting a completely empty row without naming at least one column name. If your provided values is empty, no column names are known and an empty row can't be inserted. If not set to null, the nullColumnHack parameter provides the name of nullable column name to explicitly insert a NULL into in the case where your values is empty. @values this map contains the initial column values for the row. The keys should be the column names and the values the column values

Implementation

SqlBuilder.insert(String table, Map<String, Object?> values,
    {String? nullColumnHack, ConflictAlgorithm? conflictAlgorithm}) {
  final insert = StringBuffer();
  insert.write('INSERT');
  if (conflictAlgorithm != null) {
    insert.write(' ${_conflictValues[conflictAlgorithm.index]}');
  }
  insert.write(' INTO ');
  insert.write(_escapeName(table));
  insert.write(' (');

  List<Object?>? bindArgs;
  final size = values.length;

  if (size > 0) {
    final sbValues = StringBuffer(') VALUES (');

    bindArgs = <Object?>[];
    var i = 0;
    values.forEach((String colName, Object? value) {
      if (i++ > 0) {
        insert.write(', ');
        sbValues.write(', ');
      }

      /// This should be just a column name
      insert.write(_escapeName(colName));
      if (value == null) {
        sbValues.write('NULL');
      } else {
        checkNonNullValue(value);
        bindArgs!.add(value);
        sbValues.write('?');
      }
    });
    insert.write(sbValues);
  } else {
    if (nullColumnHack == null) {
      throw ArgumentError('nullColumnHack required when inserting no data');
    }
    insert.write('$nullColumnHack) VALUES (NULL');
  }
  insert.write(')');

  sql = insert.toString();
  arguments = bindArgs;
}