runWithBegin<T> static method
Runs action inside a fresh transaction obtained from beginFn.
On normal completion the transaction is committed. On an error, rollback is attempted only while the handle remains active; a concurrent native operation can keep it busy, so cleanup is not guaranteed. The original error is rethrown even if that rollback attempt fails.
beginFn is whatever piece of API returns a TransactionHandle? (e.g.
NativeOdbcConnection.beginTransactionHandle).
Implementation
static Future<T> runWithBegin<T>(
TransactionHandle? Function() beginFn,
Future<T> Function(TransactionHandle txn) action,
) async {
final txn = beginFn();
if (txn == null) {
throw StateError('beginTransactionHandle returned null');
}
try {
final result = await action(txn);
if (!txn.commit()) {
throw StateError('Failed to commit transaction ${txn.txnId}');
}
return result;
} on Object {
if (txn.isActive) {
txn.rollback();
}
rethrow;
}
}