Sub topic 11
Keeping Related Writes Together with Transactions
Prerequisites and the transaction model
This chapter assumes you know basic Dart, Flutter, async and await, and drift table definitions. You should also know how to insert rows with into(table).insert(...).
A transaction groups several database operations into one unit. SQLite commits the whole unit only when every operation succeeds. If one operation throws an error, SQLite rolls back the earlier operations in that transaction. A rollback restores the database to its state before the transaction started.
This matters when rows depend on one another. For example, creating an order and its order lines should not leave an order without its lines if the second insert fails.
Writing a transaction in drift
The generated database class provides transaction. Pass it an asynchronous callback. Every database operation that belongs together must be awaited inside that callback.
Suppose the database has todoLists and todoItems tables. Each item stores the ID of its list.
// Inside AppDatabase
Future<int> createListWithItems(
String name,
List<String> titles,
) {
return transaction(() async {
final listId = await into(todoLists).insert(
TodoListsCompanion.insert(name: name),
);
for (final title in titles) {
await into(todoItems).insert(
TodoItemsCompanion.insert(
listId: listId,
title: title,
),
);
}
return listId;
});
}The list insert and all item inserts are committed together. If an item violates a constraint, such as a required column or a unique index, the transaction throws and the list insert is rolled back too.
A transaction can return a value. In this example, the returned value is the generated list ID. The return value does not change the commit behavior.
| Result | Database effect |
|---|---|
| The callback completes normally | All writes are committed |
| The callback throws an exception | All writes are rolled back |
Common errors
Do not start independent asynchronous writes without awaiting them. The transaction callback could finish before those writes complete, so they might not be part of the intended unit.
// Correct
await into(todoItems).insert(companion);
// Risky: the transaction may finish before this operation completes
into(todoItems).insert(companion);Do not catch an error inside the transaction and then return normally unless partial success is intentional. Returning normally tells drift that the transaction succeeded. If you need to log the error, rethrow it afterward.
Future<void> saveData() {
return transaction(() async {
try {
await writeParentAndChildren();
} catch (error) {
logError(error);
rethrow;
}
});
}Keep transactions short. Avoid network requests, long computations, or waiting for user input inside them. A transaction should contain the related database work only. Fetch remote data first, then open a transaction to save the result.
Exercise
If the child insert fails after the parent insert succeeds, what remains in the database?
Show answer
Nothing from that transaction remains. The exception causes SQLite to roll back both the parent and child inserts.