transaction<T> method

  1. @override
Future<T> transaction<T>(
  1. Future<T> callback(
    1. DbTransaction tx
    )
)
override

Runs callback inside a database transaction.

If callback throws, the transaction is rolled back automatically. Returns whatever callback returns on success.

final orderId = await db.transaction((tx) async {
  final order = await tx.insert('orders', {'total': 99.99});
  await tx.insert('order_items', {'order_id': order.first!['id'], 'sku': 'ABC'});
  return order.first!['id'];
});

Implementation

@override
Future<T> transaction<T>(
  Future<T> Function(DbTransaction tx) callback,
) async {
  _db.execute('BEGIN');
  try {
    final result = await callback(_SqliteTxDB(_db));
    _db.execute('COMMIT');
    return result;
  } catch (e) {
    _db.execute('ROLLBACK');
    rethrow;
  }
}