transaction<T> method
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 {
late T result;
await _pool.withConnection((conn) async {
await conn.execute('START TRANSACTION');
try {
result = await callback(_MySqlTxDB(conn));
await conn.execute('COMMIT');
} catch (e) {
await conn.execute('ROLLBACK');
rethrow;
}
});
return result;
}