insertAssignments method

Future<TRow> insertAssignments(
  1. MssqlWriteAssignments values
)

Inserts values and returns the stored row, including defaults.

The query-layer create(OrderCreate) is the usual call. This is the assignment form the generated method compiles into.

Implementation

Future<TRow> insertAssignments(MssqlWriteAssignments values) async {
  _checkDecimalAgreement();
  final stamped = _stampInsert(values);
  final engine = await _engine();
  final readback = engine.insertReadback;
  final outcome = await engine.insertRow(stamped);
  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) {
        throw MssqlReadbackUnavailableException(
          table: binding.qualifiedName,
          operation: 'insert',
          reason: 'SCOPE_IDENTITY() returned no value',
        );
      }
      final identity = binding.column(binding.identityColumn!)!;
      final id = outcome.rows.first.at(0);
      final found = await session.queryTypedRows(
        'SELECT * FROM ${binding.quoted} WHERE '
        '${MssqlSql.quoteIdentifier(identity.name)} = @id',
        parameters: <String, Object?>{'id': identity.bind(id)},
      );
      if (found.isEmpty) {
        throw StateError(
          'INSERT into ${binding.qualifiedName} inserted identity $id '
          'but could not read the stored row back.',
        );
      }
      return binding.fromRow(found.first);
    case MssqlWriteReadback.none:
      throw MssqlReadbackUnavailableException(
        table: binding.qualifiedName,
        operation: 'insert',
        reason:
            'the table has no identity readback, so a Create cannot be '
            'turned into a stored row. Insert a full row, or add a key.',
      );
  }
}