Sub topic 10
Type-safe databases with drift
This chapter assumes you have finished the sqflite chapters. You should be comfortable with onCreate, onUpgrade, whereArgs and Future/Stream, and you should know how to add packages and run commands from the project root.
What drift adds to SQLite
With sqflite you write SQL as strings and convert rows with toMap and fromMap. The compiler cannot check any of it. A typo in a column name, a wrong cast in fromMap, or a missing migration step only shows up at runtime.
drift is a persistence library built on SQLite. You describe tables in Dart, and a code generator produces row classes, typed query builders and the schema SQL. A wrong column name or type then becomes a compile error.
| Concern | sqflite | drift |
|---|---|---|
| Schema | SQL string in `onCreate` | Dart `Table` classes |
| Row type | Hand-written model | Generated data class |
| Queries | SQL strings with `whereArgs` | Dart expressions, always parameterized |
| Reactive results | You write it | `watch()` returns a `Stream` |
| Migrations | Raw SQL by hand | Helpers such as `addColumn`, plus generated schema dumps for tests |
| Build step | None | `build_runner` |
The costs are a code-generation step, generated files in your project, and a library you have to learn on top of SQL. For a one-table app with two queries, sqflite is often enough. drift pays off as the schema grows, as queries get joins, or when the UI should update whenever data changes.
Setting up
Add the runtime packages and the generator:
flutter pub add drift drift_flutter
flutter pub add --dev drift_dev build_runnerdrift_flutter supplies driftDatabase(), which opens the database in the right location on each platform. drift_dev and build_runner produce the generated code.
Declaring a table and a database
Each table is a class that extends Table. Each column is a getter built with a fluent chain that ends in a second (). The second pair of parentheses is easy to forget.
import 'package:drift/drift.dart';
import 'package:drift_flutter/drift_flutter.dart';
part 'app_database.g.dart';
@DataClassName('NoteRow')
class Notes extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get title => text().withLength(min: 1, max: 200)();
TextColumn get body => text().nullable()();
BoolColumn get pinned => boolean().withDefault(const Constant(false))();
}
@DriftDatabase(tables: [Notes])
class AppDatabase extends _$AppDatabase {
AppDatabase([QueryExecutor? executor])
: super(executor ?? driftDatabase(name: 'notes'));
@override
int get schemaVersion => 2;
@override
MigrationStrategy get migration => MigrationStrategy(
onCreate: (m) => m.createAll(),
onUpgrade: (m, from, to) async {
if (from < 2) {
await m.addColumn(notes, notes.pinned);
}
},
);
}Several details in this file matter:
- By default, a table named
Notesgenerates a data class namedNote. That would clash with theNotemodel from the earlier chapters, so@DataClassName('NoteRow')renames the generated class. - The
partline points at the file the generator writes. It must match the file name, soapp_database.dartneedsapp_database.g.dart. - Columns are non-null unless you call
.nullable(). Thebodycolumn isString?in the generated class, matching the nullablebodyin the earlierNotemodel. AppDatabasetakes an optionalQueryExecutor. Production code passes nothing and gets the real database. Tests pass an in-memory one, as shown at the end of this chapter.
Run the generator:
dart run build_runner buildWhile you are editing, dart run build_runner watch regenerates on every save. Fix any error in the table definitions first. The generator cannot produce _$AppDatabase until they compile.
What the generator produces
You work with three generated pieces:
NoteRowis an immutable class with typed fields:int id,String title,String? body,bool pinned. It is what queries return.NotesCompanionis a class for writing. Each field is wrapped inValue<T>, which has three states: a value,Value.absent()(leave it out of the statement), orValue(null)for an explicit SQLNULL. This is how drift tells "do not touch this column" apart from "set this column to null".NotesCompanion.insert(...)takes the required columns as plain arguments and the optional or defaulted ones asValues. That is why the insert below passestitledirectly but wrapsbody.
Insert, query, update and delete
Add these methods inside AppDatabase. Every query goes through Dart expressions, so values are always sent as bound parameters and you do not interpolate strings yourself.
Future<int> addNote(String title, String? body) {
return into(notes).insert(
NotesCompanion.insert(title: title, body: Value(body)),
);
}
Future<List<NoteRow>> notesByTitle(String title) {
return (select(notes)..where((t) => t.title.equals(title))).get();
}
Future<int> setPinned(int id, bool pinned) {
return (update(notes)..where((t) => t.id.equals(id)))
.write(NotesCompanion(pinned: Value(pinned)));
}
Future<int> removeNote(int id) {
return (delete(notes)..where((t) => t.id.equals(id))).go();
}The (select(notes)..where(...)) form uses Dart's cascade operator. ..where(...) modifies the statement and returns the statement itself, so .get() runs the modified one. The return values mirror sqflite: insert gives the new row id, and write and go give the number of affected rows.
Because setPinned writes a companion with only pinned set, the other columns are Value.absent() and stay unchanged.
Watching queries
The feature that most changes how a UI is written is watch(). It returns a Stream that emits a fresh result whenever a table the query reads is changed through the same database object.
Stream<List<NoteRow>> watchNotes() {
return (select(notes)
..orderBy([
(t) => OrderingTerm.desc(t.pinned),
(t) => OrderingTerm.asc(t.title),
]))
.watch();
}A StreamBuilder can show this directly:
StreamBuilder<List<NoteRow>>(
stream: db.watchNotes(),
builder: (context, snapshot) {
final rows = snapshot.data ?? const <NoteRow>[];
return ListView(
children: [for (final n in rows) ListTile(title: Text(n.title))],
);
},
)After addNote or setPinned completes, the list rebuilds without any manual refresh call. With sqflite you would re-run the query yourself after every write.
Migrations
You use two mechanisms to change the schema. First, raise schemaVersion. Second, handle old versions in onUpgrade. The example above moved from version 1 (no pinned) to version 2 (with pinned):
- A new install runs
onCreate, andm.createAll()builds the current schema from the table classes. You do not write theCREATE TABLESQL, so it cannot drift out of step with the class. - An existing install at version 1 runs
onUpgradewithfrom: 1, to: 2, andm.addColumnadds the one new column.
Use if (from < N) blocks, not else if, so a user jumping from version 1 to version 4 runs every step in order.
drift can also export a snapshot of the schema at each version (dart run drift_dev schema dump) and generate test helpers that check your onUpgrade against real older schemas. Consider this once the app has real users and more than a couple of versions.
Common errors
_$AppDatabasenot found. The generator has not run, or it failed. Rundart run build_runner buildand read the first error.- "Part file doesn't match" or a missing
.g.dart. Thepartdirective does not match the file name. - Forgetting the trailing
()in a column definition, such asinteger().autoIncrement()instead ofinteger().autoIncrement()(). The analyzer reports a type mismatch. - Changing a table without bumping
schemaVersion. Existing installs keep the old schema, and queries fail at runtime with "no such column". Always bump the version and add anonUpgradestep. - Committing stale generated code. Whether you check in
.g.dartfiles or generate them in CI, be consistent across the team.
Testing a drift database
Because the constructor accepts a QueryExecutor, tests can use an in-memory database. No device or file is involved.
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'app_database.dart';
void main() {
late AppDatabase db;
setUp(() => db = AppDatabase(NativeDatabase.memory()));
tearDown(() => db.close());
test('pinning a note updates the stored row', () async {
final id = await db.addNote('Groceries', null);
await db.setPinned(id, true);
final rows = await db.notesByTitle('Groceries');
expect(rows.single.pinned, isTrue);
});
}This runs against real SQLite, so it checks your actual queries, not a fake. It needs the sqlite3 native library on the machine running the tests, which most desktop development setups already have.
Exercise
Your app ships with schema version 2. You now add a nullable color text column to Notes and want existing users to keep their data. List the three changes you make in app_database.dart, and say which one needs a re-run of the generator.
Show answer
(1) Add TextColumn get color => text().nullable()(); to the Notes class. (2) Raise schemaVersion from 2 to 3. (3) Add if (from < 3) { await m.addColumn(notes, notes.color); } to onUpgrade, after the existing from < 2 block. The generator must be re-run after change (1), because that is what updates NoteRow and NotesCompanion. New installs get the column from createAll(), and upgraded installs get it from addColumn. The column is nullable, so no default is needed.