Sub topic 11
Keeping related writes together with transactions
This chapter assumes you have the AppDatabase and TodoItems table from the earlier chapters, and that you are comfortable with async/await. It covers how to make several writes succeed or fail as a single unit.
Why a single write is not enough
Every statement drift runs, such as an insert or a delete, is atomic on its own. Many real operations need several statements, though. If the app crashes, a constraint fails, or an exception is thrown halfway through, the database can be left half-updated.
Examples of operations that need grouping:
- Adding a to-do and a matching log entry.
- Replacing a list of items: delete the old rows, then insert the new ones.
- Moving a row from one table to another.
A transaction groups statements so that either all of them take effect or none do. SQLite calls the two outcomes commit and rollback.
The transaction method
Your database class inherits a transaction method. You pass it an async callback. The callback's return value becomes the return value of transaction.
// Inside AppDatabase
Future<List<int>> addItemsAllOrNothing(List<String> titles) {
return transaction(() async {
final ids = <int>[];
for (final title in titles) {
if (title.trim().isEmpty) {
throw ArgumentError('Blank title');
}
ids.add(await addItem(title));
}
return ids;
});
}Calling addItemsAllOrNothing(['Buy milk', '', 'Call Sam']) inserts "Buy milk", then throws on the blank title. Drift rolls back, so "Buy milk" is not in the table afterwards. The ArgumentError still reaches your caller, so you can show a message.
Inside the callback you call the same methods you use everywhere else, such as addItem or select(todoItems). Drift routes them through the open transaction automatically. You do not pass a transaction object around.
Rules the callback must follow
Drift ties the transaction to the callback's async scope. That gives a few rules.
- Always
awaitevery database call. A statement you forget to await may run after the transaction has already committed, outside its protection. - Throw to roll back. Any exception that escapes the callback causes a rollback. Returning early from the callback without throwing commits whatever was done so far.
- Keep it short. While a transaction is open, other writes to the same database wait for it. Do not await a network request or a user dialog inside the callback.
- Use the database's own methods. Calls made through a different
AppDatabaseinstance do not join the transaction.
// Inside AppDatabase
// Avoid: holds the transaction open during a slow network call.
Future<void> badSync() => transaction(() async {
final response = await fetchRemoteTitles(); // slow, external
for (final title in response) {
await addItem(title);
}
});
// Better: fetch first, then write quickly.
Future<void> goodSync() async {
final titles = await fetchRemoteTitles();
await transaction(() async {
for (final title in titles) {
await addItem(title);
}
});
}fetchRemoteTitles here stands for any slow call you own, such as an HTTP request.
Reading and writing in one transaction
A transaction is also the right place for read-then-write logic. Reads inside it see the writes made earlier in the same transaction, and no other writer can slip in between your read and your write.
// Inside AppDatabase
/// Deletes finished items and returns how many were removed,
/// but only if at least [minimum] items are done.
Future<int> clearDoneIfAtLeast(int minimum) {
return transaction(() async {
final done = await (select(todoItems)
..where((t) => t.isDone.equals(true)))
.get();
if (done.length < minimum) return 0;
return deleteDone();
});
}Without the transaction, an item could become done or be removed between the select and the delete. The count you checked would no longer match what was deleted.
Nested transactions
You can call transaction from inside another transaction. Drift does not open a second independent one. It uses a SQLite savepoint, which is a named marker inside the outer transaction.
- If the inner block throws, only the work since its savepoint is undone.
- If you catch that exception in the outer block, the outer transaction can continue and still commit its own work.
- If the exception escapes the outer block too, everything rolls back.
// Inside AppDatabase
Future<void> importWithOptionalExtras(
List<String> required,
List<String> extras,
) {
return transaction(() async {
for (final title in required) {
await addItem(title);
}
try {
await addItemsAllOrNothing(extras); // nested: its own savepoint
} on ArgumentError {
// Extras are skipped as a group; the required items are kept.
}
});
}This makes it safe to build small transactional methods and compose them. A method like addItemsAllOrNothing works on its own and also inside a larger operation.
Transactions and watch streams
The watch() streams from the previous chapters are transaction-aware. Drift tells listening queries about changed tables when the transaction commits, so a StreamBuilder does not render a half-finished state. If the transaction rolls back, no update is emitted.
This is a good reason to wrap bulk changes in a transaction even when atomicity is not critical. A loop of 200 separate inserts can trigger many UI rebuilds. One transaction produces one update.
Transactions versus batches
Drift also has batch, which sends many statements to SQLite together. It is aimed at speed when you run many similar writes. A transaction is aimed at correctness when your logic has steps that depend on each other.
| Need | Use |
|---|---|
| Several dependent steps, reads mixed with writes, rollback on any error | `transaction` |
| Many inserts or updates with no logic between them | `batch` |
| Many writes that must also be all-or-nothing | `transaction` containing a `batch` |
// Inside AppDatabase
Future<void> insertMany(List<String> titles) {
return transaction(() async {
await batch((b) {
b.insertAll(todoItems, [
for (final t in titles) TodoItemsCompanion.insert(title: t),
]);
});
});
}Testing rollback
The in-memory database from the testing chapter makes rollback easy to verify. The test below checks that a failing transaction leaves no partial data behind.
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
late AppDatabase db;
setUp(() => db = AppDatabase(NativeDatabase.memory()));
tearDown(() => db.close());
test('a failing transaction leaves nothing behind', () async {
await expectLater(
db.addItemsAllOrNothing(['Buy milk', '', 'Call Sam']),
throwsArgumentError,
);
expect(await db.allItems(), isEmpty);
});
test('a successful transaction returns all ids', () async {
final ids = await db.addItemsAllOrNothing(['A', 'B']);
expect(ids, hasLength(2));
expect(await db.allItems(), hasLength(2));
});
}Common mistakes
- Catching the exception inside the callback and swallowing it. The transaction then commits, because nothing escaped. Rethrow, or let it propagate.
- Doing slow, unrelated work inside the callback, which blocks other writers.
- Forgetting
awaiton a statement inside the callback. - Assuming a nested transaction can commit independently. It cannot. Its changes are only saved if the outermost transaction commits.
Exercise
You write transaction(() async { await addItem('A'); try { await addItem(''); } catch (_) {} await addItem('B'); }), where addItem('') throws. After the call, which items are in the table, and why?
Show answer
Both "A" and "B" are saved. The exception is caught inside the callback, so nothing escapes and the transaction commits. Whether the failed insert changed anything depends on where it failed, but the transaction does not roll back. To roll everything back, rethrow the error or do not catch it.
Exercise
A method fetches data over HTTP and then inserts 50 rows. Where should the transaction call go relative to the HTTP request, and why?
Show answer
Make the request first, then open the transaction and insert the rows. This keeps the transaction short, so other writes are not blocked while waiting for the network. One transaction for the 50 inserts also means one stream update after the commit.