Sub topic 9
Changing the schema with versions and migrations
Apps outlive their first database design. A later release needs a pinned flag, a timestamp, or an index. Users who installed an earlier version already have a notes.db file on their device with the old schema. This chapter covers how sqflite lets you upgrade that file in place without losing data.
This chapter assumes you can open a database with openDatabase, run basic CRUD with sqflite, and read simple SQL (CREATE TABLE, ALTER TABLE, INSERT ... SELECT). It continues the notes table from the previous chapters.
Why a schema version exists
A SQLite file carries an integer in its header called user_version. sqflite exposes it through the version argument of openDatabase. When you open the database, sqflite compares the number stored in the file with the number your code asks for, then calls one of your callbacks.
| Stored version | Requested version | Callback called |
|---|---|---|
| File does not exist | 2 | `onCreate` |
| 1 | 2 | `onUpgrade(db, 1, 2)` |
| 2 | 2 | none (`onOpen` still runs) |
| 3 | 2 | `onDowngrade(db, 3, 2)` |
After the callback finishes successfully, sqflite stores the new version number. Each callback runs inside a transaction, so if it throws, the changes roll back and the stored version stays the same.
Two paths to the same schema
Every release has to produce the same final schema by two routes:
- New installs run
onCreateonce and must end with the latest schema. - Existing installs run
onUpgradeand must end with an identical schema.
Here is the version 2 example from earlier. onCreate builds the full v2 table, and onUpgrade patches a v1 table.
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
Future<Database> openNotesDatabaseV2() async {
final path = join(await getDatabasesPath(), 'notes.db');
return openDatabase(
path,
version: 2,
onCreate: (db, version) async {
await db.execute(
'CREATE TABLE notes('
'id INTEGER PRIMARY KEY AUTOINCREMENT, '
'title TEXT NOT NULL, '
'body TEXT, '
'pinned INTEGER NOT NULL DEFAULT 0)',
);
},
onUpgrade: (db, oldVersion, newVersion) async {
if (oldVersion < 2) {
await db.execute(
'ALTER TABLE notes ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0',
);
}
},
);
}The check is oldVersion < 2, not oldVersion == 1. A user who skipped several releases may jump from version 1 straight to version 4, and every step in between must still run.
Migrating in ordered steps
With three or four versions, a chain of if blocks gets hard to read. A common pattern is a map from target version to the statements that reach it. onUpgrade then replays every step between the old and new version.
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
const int notesDbVersion = 3;
const String _createNotesV3 = 'CREATE TABLE notes('
'id INTEGER PRIMARY KEY AUTOINCREMENT, '
'title TEXT NOT NULL, '
'body TEXT, '
'pinned INTEGER NOT NULL DEFAULT 0, '
'updated_at INTEGER)';
const String _createTitleIndex =
'CREATE INDEX idx_notes_title ON notes(title)';
// Each key is the version the statements upgrade the database TO.
const Map<int, List<String>> _migrations = {
2: [
'ALTER TABLE notes ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0',
],
3: [
'ALTER TABLE notes ADD COLUMN updated_at INTEGER',
'UPDATE notes SET updated_at = 0 WHERE updated_at IS NULL',
_createTitleIndex,
],
};
Future<Database> openNotesDatabaseV3() async {
final path = join(await getDatabasesPath(), 'notes.db');
return openDatabase(
path,
version: notesDbVersion,
onCreate: (db, version) async {
await db.execute(_createNotesV3);
await db.execute(_createTitleIndex);
},
onUpgrade: (db, oldVersion, newVersion) async {
for (var v = oldVersion + 1; v <= newVersion; v++) {
final steps = _migrations[v];
if (steps == null) {
throw StateError('Missing migration to version $v');
}
for (final sql in steps) {
await db.execute(sql);
}
}
},
);
}Version 3 does three things. It adds a nullable column, backfills existing rows so old data has a defined value, and creates an index. Throwing on a missing step is deliberate. If you bump notesDbVersion and forget the migration, the failure shows up in development and not as a silently wrong schema in production.
Rules for every migration
- Never edit a migration that has shipped. Add a new one.
- Keep each migration self-contained. It must not call code that reads your current
Notemodel, because that model changes later. - Update
onCreateand add a migration in the same commit. - Treat a version bump as a release decision. Two feature branches that both bump to version 3 will conflict.
What ALTER TABLE can and cannot do
SQLite supports far fewer schema changes than server databases.
| Change | Supported by `ALTER TABLE` |
|---|---|
| Add a column | Yes, with limits (below) |
| Rename a table | Yes |
| Rename a column | Only on SQLite 3.25 and later |
| Drop a column | Only on SQLite 3.35 and later |
| Change a column type or constraint | No |
| Add a `PRIMARY KEY` or `UNIQUE` column | No |
Limits on adding a column:
- A
NOT NULLcolumn needs a non-nullDEFAULT, which is whypinnedhasDEFAULT 0. - The default must be a constant, not an expression such as
CURRENT_TIMESTAMP.
The SQLite version depends on the OS. On Android it is whatever the device's system library provides, so a rename or drop that works on your new test phone can fail on an older one. Unless you set a minimum OS version that guarantees the feature, use the rebuild technique below instead.
Rebuilding a table
To change something ALTER TABLE cannot, create a new table, copy the data, drop the old table, and rename the new one. For example, version 4 makes title unique and drops nothing else:
const List<String> migrationToV4 = [
'CREATE TABLE notes_new('
'id INTEGER PRIMARY KEY AUTOINCREMENT, '
'title TEXT NOT NULL UNIQUE, '
'body TEXT, '
'pinned INTEGER NOT NULL DEFAULT 0, '
'updated_at INTEGER)',
'INSERT OR IGNORE INTO notes_new(id, title, body, pinned, updated_at) '
'SELECT id, title, body, pinned, updated_at FROM notes',
'DROP TABLE notes',
'ALTER TABLE notes_new RENAME TO notes',
'CREATE INDEX idx_notes_title ON notes(title)',
];Two details matter here. Dropping a table also drops its indexes, so recreate them at the end. INSERT OR IGNORE silently discards rows whose title duplicates an earlier row, which loses data. A real migration should decide how to handle duplicates first, for instance by renaming them in an earlier statement.
Transactions and atomicity
sqflite wraps onCreate, onUpgrade and onDowngrade in one transaction, so a failed step rolls back all earlier steps in that upgrade. The database stays at its old version and the same migration runs again on the next launch.
Do not call db.transaction inside these callbacks. The db object you receive is already inside the transaction, and opening another one can deadlock. Use db.batch() if you want to group statements for speed.
Configuration, downgrade and open hooks
Three other callbacks complete the picture.
onConfigureruns first, before create, upgrade or downgrade. Use it for settings such as foreign keys, which SQLite leaves off by default.onDowngraderuns when the stored version is higher than the requested one. That happens when a user installs an older build over a newer one. Without a handler,openDatabasethrows.onDatabaseDowngradeDeletedeletes the database and recreates it. That is safe for a cache and destructive for user notes.onOpenruns on every successful open, after migrations.
Future<Database> openWithForeignKeys(String path) {
return openDatabase(
path,
version: 1,
onConfigure: (db) async {
await db.execute('PRAGMA foreign_keys = ON');
},
onCreate: (db, version) async {
await db.execute('CREATE TABLE tags(id INTEGER PRIMARY KEY, name TEXT)');
},
);
}Common errors
- Forgetting
onCreate. New installs end up on the old schema while upgraded installs have the new one. Bugs then appear only for one group of users. - Bumping
versionwithout a migration. The app opens but a query fails withno such column. - Testing only fresh installs. Run the upgrade path from every released version on a populated database.
- Using
==for version checks. Users who skip versions miss steps. - Changing data types in app code. If a
Notefield changes, the stored columns still need a migration.
Summary
The version number tells sqflite which callback to run. onCreate and onUpgrade must produce the same schema. Migrations are ordered, never edited after release, and run inside one transaction. When ALTER TABLE cannot do the job, rebuild the table and preserve its indexes and data.
Exercise
A user has a database at version 1. Your current code requests version 3, with migrations registered for 2 and 3. Which callbacks run, in what order, and what happens if the step for version 3 throws an error?
Show answer
Only onUpgrade runs, once, with oldVersion 1 and newVersion 3. The loop applies the version 2 steps and then the version 3 steps. If version 3 throws, the whole upgrade transaction rolls back, including the version 2 steps. The stored version stays 1, and the upgrade is attempted again the next time the app opens the database.
Exercise
You want to add a created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP column to notes in version 4 using ALTER TABLE ADD COLUMN. Why does it fail, and how would you achieve the result?
Show answer
SQLite requires the default of an added column to be a constant, and CURRENT_TIMESTAMP is not allowed for ADD COLUMN. Either add the column as nullable (or with a constant default such as an empty string) and backfill it with an UPDATE statement, or rebuild the table with the new column definition and copy the data across, then recreate the indexes.