insert method

Future<TRow> insert(
  1. TRow row
)

Inserts row and applies the table's configured readback strategy.

Rows with only server-generated columns use DEFAULT VALUES.

Implementation

Future<TRow> insert(TRow row) async {
  _checkDecimalAgreement();
  final values = _stampInsert(_writableValues(row));
  final engine = await _engine();
  final readback = engine.insertReadback;
  final outcome = await engine.insertRow(values);

  switch (readback) {
    case MssqlWriteReadback.storedRow:
    case MssqlWriteReadback.keyCapture:
      if (outcome.rows.isEmpty) {
        throw StateError(
          'INSERT into ${binding.qualifiedName} stored a row but reported '
          'none back. A trigger or an updatable view that discards the row '
          'is the usual cause; declare a readback strategy that matches it.',
        );
      }
      return binding.fromRow(outcome.rows.first);

    case MssqlWriteReadback.identityOnly:
      if (outcome.rows.isEmpty) return row;
      final apply = binding.applyIdentity;
      if (apply == null) {
        throw StateError(
          '${binding.qualifiedName} reads its key back through '
          'SCOPE_IDENTITY() but its binding carries no applyIdentity, so '
          'the generated key cannot be put back into the row. Regenerate '
          'the table.',
        );
      }
      return apply(row, outcome.rows.first.at(0));

    case MssqlWriteReadback.none:
      return row;
  }
}