transaction<T> method
Future<T>
transaction<T>(
- Future<
T> callback(), { - Duration retryDelay = const Duration(milliseconds: 100),
- Future<
void> onSuccess(- T result
- Future<
void> onFailure(- dynamic error
- Future<
void> onFinally()?, - String? isolationLevel,
override
Executes a transactional block with retry, success/failure hooks.
callbackis the block of code to run inside a transaction.retryDelaysets the delay between retries.
Hooks:
onSuccesscalled when the transaction commits successfully.onFailurecalled if the transaction throws an error.onFinallyalways 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();
}
}