Sub topic 9
Changing the Schema with Versions and Migrations
This chapter assumes you know Dart classes, Future, async and await, and the basic sqflite operations for opening a database and running SQL.
A database schema is the structure of a database. It defines tables, columns, data types, and indexes. As your app changes, the schema may need to change too. For example, a notes app might add a pinned column after version 1 has already been released.
A migration is code that changes an existing database from one schema version to another. Without a migration, users who update the app may still have the old database structure.
How database versions work
When you call openDatabase, provide a version number:
- A new installation runs
onCreate. - An existing database with a lower version runs
onUpgrade. - An existing database with the same version runs neither callback.
- The version number should increase when the schema changes.
onCreate must create the complete schema for a new installation. onUpgrade must apply only the changes needed by an older installation.
Writing migrations with sqflite
Suppose version 1 has id, title, and body. Version 2 adds pinned, and version 3 adds an index for faster title searches.
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
Future<Database> openNotesDatabase() async {
final path = join(await getDatabasesPath(), 'notes.db');
return openDatabase(
path,
version: 3,
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)',
);
await db.execute(
'CREATE INDEX notes_title_index ON notes(title)',
);
},
onUpgrade: (db, oldVersion, newVersion) async {
if (oldVersion < 2) {
await db.execute(
'ALTER TABLE notes '
'ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0',
);
}
if (oldVersion < 3) {
await db.execute(
'CREATE INDEX notes_title_index ON notes(title)',
);
}
},
);
}The oldVersion < 2 condition handles upgrades from version 1 to version 2. It also handles a direct upgrade from version 1 to version 3. In that case, both migration blocks run in order.
The onCreate callback creates the final version 3 schema directly. A new user should not need to run old migrations that were designed for earlier releases.
Common migration errors
A migration can fail when SQL assumes a column or table already exists. Test upgrades from each supported old version, not only fresh installations.
Avoid lowering the version number. sqflite is designed for forward upgrades, not automatic downgrades. If a downgrade is required during development, uninstall the app or use a deliberate migration strategy.
Migrations can also lose data. Replacing a table, changing a column type, or removing a column may require copying rows into a temporary table. Back up important data before destructive changes, and make such operations explicit.
Use the database transaction supplied by sqflite's upgrade process. If one migration statement fails, the upgrade should not leave the database halfway between two schemas.
Exercise
A user has a version 1 database, and the current app version is 3. Which migration conditions should run?
Show answer
Both if (oldVersion < 2) and if (oldVersion < 3) should run, in that order. The onCreate callback does not run because the database already exists.