transaction<R> method

Future<R> transaction<R>(
  1. Future<R> action()
)

Runs action in a transaction: everything or nothing. The DataAccess methods called inside action take part in it; a transaction started inside a transaction joins it. Inside a transaction a failing method throws instead of returning false (even outside strict mode), so that every change is rolled back; the error is rethrown.

Implementation

Future<R> transaction<R>(Future<R> Function() action) async {
  if (_scope != null) return action();
  final SqlExecutor executor = (await _open()).executor;
  _TxScope? scope;
  try {
    final R result = await executor.transaction((SqlExecutor tx) {
      scope = _TxScope(tx);
      return runZoned(
        () => action(),
        zoneValues: <Object, Object>{_txKey: scope!},
      );
    });
    _knownTables.addAll(scope!.createdTables);
    return result;
  } finally {
    scope?.active = false;
  }
}