prepareReplace method

void prepareReplace(
  1. Insertable<Row> entity
)

Update this statement to generate the SQL for a replace call.

This is used internally when replace cannot be used because it also runs the statement, e.g. to build batches.

Implementation

void prepareReplace(Insertable<Row> entity) {
  // We don't turn nulls to absent values here (as opposed to a regular
  // update, where only non-null fields will be written).
  _applyColumns(entity, false);
  assert(
    whereClause == null,
    'When using replace on an update statement, you may not use where(...)'
    'as well. The where clause will be determined automatically',
  );

  whereSamePrimaryKey(entity);

  final primaryKeys = resultSet.resolvedPrimaryKey.map((c) => c.name);

  // entityToSql doesn't include absent values, so we might have to apply the
  // default value here
  for (final column in resultSet.columns) {
    // if a default value exists and no value is set, apply the default
    if (updatedColumns.containsKey(column.name)) {
      continue;
    }

    final defaultValue = column.constraints
        .whereType<ColumnDefaultConstraint>()
        .firstOrNull
        ?.defaultExpression;

    if (defaultValue != null && !updatedColumns.containsKey(column.name)) {
      updatedColumns[column.name] = defaultValue;
    }
  }

  // Don't update the primary key
  updatedColumns.removeWhere((key, _) => primaryKeys.contains(key));
}