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 {
    // SQLite isolation levels are handled differently (DEFERRED, IMMEDIATE, EXCLUSIVE)
    // We can map standard levels or just use BEGIN
    if (isolationLevel != null) {
      // SQLite doesn't support SET TRANSACTION ISOLATION LEVEL standard syntax easily
      // We'll ignore for now or map 'SERIALIZABLE' to 'BEGIN EXCLUSIVE' etc.
    }

    await beginTransaction();
    final result = await callback();
    await commit();

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

    return result;
  } catch (e) {
    try {
      await rollBack();
    } catch (_) {
      // Ignore rollback errors
    }

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