Sub topic 12
Evolving the Schema with drift Migrations
Prerequisites
Assume you know basic Dart, Flutter, async and await, and drift table definitions. This chapter also assumes an existing AppDatabase with a TodoItems table and a generated database.g.dart file.
A schema is the structure of a database: its tables, columns, indexes, and relationships. A migration is code that changes an existing database from one schema version to another while preserving user data.
Fresh installations can create the latest schema immediately. Existing installations need each change applied in order.
Schema versions and migration paths
The schemaVersion getter identifies the newest schema understood by your application. When the app opens the database, drift compares this value with the version stored in SQLite.
onCreateruns for a new database.onUpgraderuns for an existing database with an older version.- The
fromvalue tells you the version that the installed database currently uses. - The
tovalue tells you the target version.
The migration path should be incremental. If version 1 becomes version 3, the code must still apply the version 2 change before the version 3 change.
Adding a column safely
Suppose version 1 contains title and completion status. Version 2 adds an optional note. The column is nullable, so old rows remain valid without a value.
import 'package:drift/drift.dart';
import 'package:drift_flutter/drift_flutter.dart';
part 'database.g.dart';
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()();
}
@DriftDatabase(tables: [TodoItems])
class AppDatabase extends _$AppDatabase {
AppDatabase([QueryExecutor? executor])
: super(executor ?? driftDatabase(name: 'app'));
@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);
}
},
);
}Run code generation after changing the table:
dart run build_runner buildFor a required column, plan a value for existing rows. You might first add it as nullable, fill it in with an update, and then make it required in a later migration. Adding a non-nullable column without a default value can fail because old rows have no value for it.
Testing migrations
Migration code can pass fresh-install tests while failing for users upgrading from an older release. Keep a test database at each important old version, apply the migration, and verify both the new schema and existing rows.
Test these cases:
- A fresh database creates the newest schema.
- A version 1 database upgrades to version 2.
- Existing values remain unchanged.
- New columns contain the intended default or null value.
- Multiple migrations run in order.
Exercise
Why should an upgrade check use if (from < 2) instead of only if (from == 1)?
Show answer
A database may skip several app releases. Checking from < 2 applies the version 2 change to every older database, including one upgrading from version 0 or another earlier version.