transaction<T> method

  1. @override
Future<T> transaction<T>(
  1. FutureOr<T> f(
    1. Database
    )
)

Enters a database transaction, performing the actions within, and returning the results of f.

If f fails, the transaction will be rolled back, and the responsible exception will be re-thrown.

Whether nested transactions are supported depends on the underlying driver.

Implementation

@override
Future<T> transaction<T>(FutureOr<T> Function(Database) f) async {
  if (_connection is! PostgreSQLConnection) {
    return await f(this);
  }

  var conn = _connection as PostgreSQLConnection;
  T? returnValue;

  var txResult = await conn.transaction((ctx) async {
    try {
      logger.config('Entering transaction');
      var tx = PostgreSqlDatabase(ctx, logger: logger);
      returnValue = await f(tx);

      return returnValue;
    } catch (e) {
      ctx.cancelTransaction(reason: e.toString());
      rethrow;
    } finally {
      logger.config('Exiting transaction');
    }
  });

  if (txResult is PostgreSQLRollback) {
    //if (txResult.reason == null) {
    //  throw StateError('The transaction was cancelled.');
    //} else {
    throw StateError(
        'The transaction was cancelled with reason "${txResult.reason}".');
    //}
  } else {
    return returnValue!;
  }
}