Sub topic 12
Evolving the schema with migrations
This chapter assumes you have a working drift database with a TodoItems table and an AppDatabase class, and that you can run build_runner. It also assumes you know basic SQL (ALTER TABLE, CREATE TABLE). A migration is the code that moves an existing database from one schema version to the next.
Why migrations exist
Your schema will change after release. A user who installed version 1 of your app has a SQLite file on their device with the old tables. If you edit the Dart table classes and ship, that file does not change by itself. Queries then reference columns that don't exist, and the app fails at runtime.
Drift handles this with a schema version number. SQLite stores an integer called user_version in the database file header. Drift compares it with the schemaVersion getter in your database class each time the database opens, and runs the code you supply when they differ.
The migration strategy
You describe the behavior by overriding migration in AppDatabase. Its type is MigrationStrategy, with three callbacks:
onCreateruns for a fresh install. It must build the whole current schema.onUpgradereceives aMigrator, the old version (from) and the new version (to). It runs on existing installs.beforeOpenruns every time the database opens, after any create or upgrade. It is the place for pragmas and seed data.
If you don't override migration, drift's default creates all tables on a fresh install and does nothing on upgrade. That default is fine for version 1 and unsafe afterward.
Worked example: adding a column
Suppose version 2 adds an optional note to each to-do. First change the table class:
class TodoItems extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get title => text().withLength(min: 1, max: 100)();
BoolColumn get isDone => boolean().withDefault(const Constant(false))();
DateTimeColumn get createdAt => dateTime().withDefault(currentDateAndTime)();
TextColumn get note => text().nullable()();
}Then raise schemaVersion and add an upgrade step inside AppDatabase:
@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(todoItems, todoItems.note);
}
},
);Re-run dart run build_runner build so the generated row class gains the note field. Existing installs run addColumn. Fresh installs run createAll, which already includes note.
Each step is guarded by if (from < N), not if (from == N - 1). A user who skips an app release may jump from version 1 to version 3. With from < N checks, every missing step runs in order. Keep the checks in ascending order and never delete old ones.
Adding a table in a later version
Version 3 introduces a Categories table. Define the class, add it to @DriftDatabase(tables: [...]), bump schemaVersion to 3, and extend onUpgrade:
class Categories extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get name => text().withLength(min: 1, max: 50)();
}
// Inside AppDatabase, with tables: [TodoItems, Categories]
@override
int get schemaVersion => 3;
@override
MigrationStrategy get migration => MigrationStrategy(
onCreate: (m) => m.createAll(),
onUpgrade: (m, from, to) async {
if (from < 2) {
await m.addColumn(todoItems, todoItems.note);
}
if (from < 3) {
await m.createTable(categories);
await m.addColumn(todoItems, todoItems.categoryId);
}
},
);This assumes TodoItems also gained IntColumn get categoryId => integer().nullable().references(Categories, #id)();. A nullable column is deliberate, as the next section explains.
Rules that SQLite imposes
ALTER TABLE ... ADD COLUMN in SQLite is limited, and most migration bugs come from those limits.
| Change | Works with `addColumn`? | What to do |
|---|---|---|
| Add a nullable column | Yes | Call `m.addColumn` |
| Add a non-null column with a default | Yes | Give the column `withDefault` and call `m.addColumn` |
| Add a non-null column without a default | No, existing rows have no value | Add a default, or make it nullable |
| Rename a column | Yes, in recent SQLite | `m.renameColumn(table, 'old_name', table.newColumn)` |
| Change a column type or constraint | No | Rebuild the table with `m.alterTable(TableMigration(...))` |
| Drop a table | Yes | `m.deleteTable('name')` |
For type or constraint changes, alterTable creates a new table, copies the rows across, drops the old table, and renames the new one. You can pass columnTransformer to compute new column values from old ones, and newColumns for columns that didn't exist before.
// Version 4: make 'title' longer and backfill nothing else
if (from < 4) {
await m.alterTable(TableMigration(todoItems));
}Use this only when addColumn can't express the change. The table is copied in full, so it costs time on large tables.
Running code before the database opens
beforeOpen is the right place to enable foreign key enforcement. SQLite turns it off by default for each connection.
@override
MigrationStrategy get migration => MigrationStrategy(
onCreate: (m) => m.createAll(),
onUpgrade: (m, from, to) async {
if (from < 2) {
await m.addColumn(todoItems, todoItems.note);
}
},
beforeOpen: (details) async {
await customStatement('PRAGMA foreign_keys = ON');
if (details.wasCreated) {
await into(todoItems)
.insert(TodoItemsCompanion.insert(title: 'Welcome'));
}
},
);details.wasCreated is true only on the run that created the file. details.hadUpgrade is true when onUpgrade ran, and details.versionBefore holds the previous version.
Data migrations
Sometimes the schema stays the same shape but the data must change, such as splitting a column or filling in a new one. Run SQL inside the upgrade step after the structural change:
if (from < 5) {
await m.addColumn(todoItems, todoItems.priority);
await customStatement('UPDATE todo_items SET priority = 1 WHERE is_done = 0');
}Drift converts Dart names to snake case for SQL, so TodoItems becomes todo_items and isDone becomes is_done. Check generated names in database.g.dart if unsure. Drift runs the whole migration inside a transaction, so a thrown exception rolls it back and leaves the file at the old version.
Verifying migrations
Manual testing doesn't scale past two versions. Drift ships tooling in drift_dev for this:
- Run
dart run drift_dev schema dump lib/database.dart drift_schemas/after each release to save a JSON snapshot of that version. - Run
dart run drift_dev schema generate drift_schemas/ test/generated_migrations/to produce helpers that open a database at an old version. - In a test, use the generated
SchemaVerifierto create a database at version N, upgrade it, and callvalidateDatabaseSchema(). This fails if your migration produced a different schema from the one in your table classes.
Commit the snapshots with the release. They are the only record of what each shipped version looked like.
Common mistakes
- Changing a table class but forgetting to raise
schemaVersion. The upgrade never runs. - Raising
schemaVersionbut not runningbuild_runner. The generated code still has the old row class. - Adding a non-null column with no default. The
ALTER TABLEfails on any install that has rows. - Using
from == N - 1instead offrom < N, which breaks users who skipped a release. - Shipping a downgrade. Drift does not support moving to a lower version, so never ship a lower
schemaVersionthan a previous release.
Exercise
Your app has shipped versions 1 and 2. In version 3 you want to add IntColumn get priority => integer()(); (non-null, no default) to TodoItems. What goes wrong with m.addColumn, and how do you fix it so users on version 1 and version 2 both upgrade cleanly?
Show answer
SQLite cannot add a non-null column with no default to a table that already has rows, because the existing rows have no value for it, so addColumn fails and the migration rolls back. Declare the column with a default, for example integer().withDefault(const Constant(0))(), or make it nullable(). Raise schemaVersion to 3 and add if (from < 3) { await m.addColumn(todoItems, todoItems.priority); } after the existing if (from < 2) step. Because both checks use from <, a version 1 user runs both steps and a version 2 user runs only the new one.