transaction<T> method

Future<T> transaction<T>(
  1. Future<T> delegate(
    1. DatabaseContext context
    )
)

Executes delegate inside of a database transaction.

If transaction is called from inside of another transaction's delegate, the parent transaction / database context will be forwarded so methods using transaction can be combined into larger transactions.

Implementation

Future<T> transaction<T>(
    Future<T> Function(DatabaseContext context) delegate) async {
  if (!_connection.isOpen) {
    _connection = await _adapter.openConnection();
  }
  try {
    return await _connection.runTransaction(delegate);
  } on SocketException catch (e, stack) {
    resolve<LogService?>()?.warn(
      'Socket exception in transaction. Retrying...',
      error: e,
      trace: stack,
    );

    try {
      await _connection.close();
    } catch (e, stack) {
      resolve<LogService?>()?.warn(
        'Could not close connection.',
        error: e,
        trace: stack,
      );
    }

    _connection = await _adapter.openConnection();
    return await _connection.runTransaction(delegate);
  }
}