transaction<T> method

  1. @override
Future<T> transaction<T>(
  1. Future<T> callback(), {
  2. Duration retryDelay = const Duration(milliseconds: 100),
  3. Future<void> onSuccess(
    1. T result
    )?,
  4. Future<void> onFailure(
    1. dynamic error
    )?,
  5. Future<void> onFinally()?,
  6. String? isolationLevel,
})
override

Executes a transactional block with retry, success/failure hooks.

  • callback is the block of code to run inside a transaction.
  • retryDelay sets the delay between retries.

Hooks:

  • onSuccess called when the transaction commits successfully.
  • onFailure called if the transaction throws an error.
  • onFinally always called after transaction completes.

Implementation

@override
Future<T> transaction<T>(
  Future<T> Function() callback, {
  Duration retryDelay = const Duration(milliseconds: 100),
  Future<void> Function(T result)? onSuccess,
  Future<void> Function(dynamic error)? onFailure,
  Future<void> Function()? onFinally,
  String? isolationLevel,
}) async {
  if (!isConnected) {
    await connect();
  }

  try {
    if (isolationLevel != null) {
      await execute('SET TRANSACTION ISOLATION LEVEL $isolationLevel');
    }
    await execute('START TRANSACTION');
    final result = await callback();
    await execute('COMMIT');

    if (onSuccess != null) {
      await onSuccess(result);
    }

    return result;
  } catch (e) {
    try {
      await execute('ROLLBACK');
    } catch (_) {
      // Ignore rollback errors if connection is lost
    }

    if (onFailure != null) await onFailure(e);
    rethrow;
  } finally {
    if (onFinally != null) await onFinally();
  }
}