transaction<T> method

Future<T> transaction<T>(
  1. Future<T> body(), {
  2. String? connection,
  3. int attempts = 1,
  4. Duration? timeout,
})

Runs body in a transaction on connection (default when null). Nested calls create a savepoint that is released or rolled back with the nested callback. With attempts > 1, deadlocks and serialization failures retry the whole transaction, after a short random wait.

With a timeout, a body still running when it passes is given up: its transaction (or savepoint) rolls back, the connection goes back to the pool, the call throws TransactionTimeoutException (not retried), and any later query of that body throws it too instead of running. A query already waiting in the database (on a row lock, say) ends only when the database lets it go, so pair this with the database's own lock timeout.

Implementation

Future<T> transaction<T>(
  Future<T> Function() body, {
  String? connection,
  int attempts = 1,
  Duration? timeout,
}) async {
  if (timeout != null && timeout <= Duration.zero) {
    throw ArgumentError.value(timeout, 'timeout', 'must be positive');
  }
  if (_activeScope(connection) != null) {
    return _savepoint(body, timeout);
  }
  final connectionName = connection ?? config.defaultConnection;
  final driver = await this.connection(connection);
  var wait = retryBaseDelay;
  for (var attempt = 1; ; attempt++) {
    final callbacks = <FutureOr<void> Function()>[];
    final T result;
    final probe = PoolWaitProbe();
    final watch = Stopwatch();
    final watched = _transactionListeners.isNotEmpty;
    var begun = false;
    Future<T> run() => driver.transaction<T>((tx) {
      if (watched) {
        begun = true;
        _notifyTransaction(
          DbTransactionBeginning(connectionName, 1, poolWait: probe.waited),
        );
        watch.start();
      }
      final scope = _TransactionScope(tx, this, connectionName);
      return _bounded(
        runZoned<Future<T>>(
          _unlessCancelled(body),
          zoneValues: <Object?, Object?>{
            transactionKey: scope.executor,
            _scopeKey: scope,
            depthKey: 1,
            afterCommitKey: callbacks,
          },
        ),
        timeout,
        scope,
      ).whenComplete(scope.close);
    });
    try {
      result = await (watched ? probe.run(run) : run());
      if (watched) {
        _notifyTransaction(
          DbTransactionCommitted(connectionName, 1, watch.elapsed),
        );
      }
    } catch (error) {
      // No connection, no BEGIN: nothing to pair a rollback with.
      if (begun) {
        _notifyTransaction(
          DbTransactionRolledBack(connectionName, 1, watch.elapsed, error),
        );
      }
      if (attempt >= attempts || !_isRetryable(driver, error)) {
        rethrow;
      }
      _logger?.warning(
        'Transaction attempt $attempt failed with a retryable error; retrying.',
      );
      // Wall clock: a frozen test clock must not slow the retry, and a
      // delay needs no connection, so the others get theirs meanwhile.
      if (!Clock.isFaked) {
        wait = retryDelay(wait, _retryRandom);
        await Future<void>.delayed(wait);
      }
      continue;
    }
    // Committed. The callbacks run outside the retry above: one that
    // fails with a deadlock or busy error (a query of its own) must not
    // run the body, and its writes, a second time. As in Laravel, the
    // first callback to throw stops the rest and surfaces to the caller.
    for (final callback in callbacks) {
      await callback();
    }
    return result;
  }
}