Dart
Transaction
Learn atomic operations with Transaction.
Transaction
A transaction runs multiple database operations as a single atomic unit. Either all succeed or none. On error the whole operation is rolled back; on success it commits.
In sqflite you start a transaction with await db.transaction((txn) async { ... }). Inside the block you use txn.insert, txn.query and similar. Example: a money transfer — deduct from one account, add to another; if one fails both are rolled back.
An atomic transfer example
Consider a bank transfer: deduct 100 lira from account A, add 100 lira to account B. These two operations are one unit; if one fails the other must roll back. Otherwise money vanishes or duplicates.
db.transaction((txn) async { await txn.insert('accounts', {'id': 1, 'amount': 100}); await txn.insert('accounts', {'id': 2, 'amount': 50}); print('commit'); }). If both inserts succeed, 'commit' is printed. If one throws, none commits. In this lesson we apply this pattern.
Exercise An atomic transfer
The code below has main open a bank.db. Define transferDemo(Database db): inside a db.transaction((txn) async { ... }) block add two txn.insert('accounts', ...) calls (id 1 amount 100 and id 2 amount 50) and at the end of the block call print('commit'). main already has print('Transaction: atomic transfer'); add the transferDemo(db) call.
Show example solution
import 'package:sqflite/sqflite.dart';
Future<void> transferDemo(Database db) async {
await db.transaction((txn) async {
await txn.insert('accounts', {'id': 1, 'amount': 100});
await txn.insert('accounts', {'id': 2, 'amount': 50});
print('commit');
});
}
void main() async {
print('Transaction: atomic transfer');
final db = await openDatabase('bank.db');
await transferDemo(db);
await db.close();
}
Test yourself
-
What does a transaction provide?
- Faster queries
- Atomicity
- Less memory
- Auto backup
Show answer
Atomicity — a transaction provides atomicity — all or nothing.
-
Match the transaction parts
- db.transaction
- Atomic block
- txn.insert
- In-block insert
- commit
- Successful end
- rollback
- Rolls back
-
The db.transaction connector
await db.____((txn) async {
await txn.insert('accounts', {'id': 1, 'amount': 100});
await txn.insert('accounts', {'id': 2, 'amount': 50});
print('commit');
});
Show answer
await db.transaction((txn) async {
await txn.insert('accounts', {'id': 1, 'amount': 100});
await txn.insert('accounts', {'id': 2, 'amount': 50});
print('commit');
});
Next lesson: ORM