I just wondering how we write migration strategy when schema version is getting bigger. Can anyone give me an example how to handle that situation?
@MuhammadDicky This is what I do. It has been working great for me.
onUpgrade: (Migrator m, int from, int to) async {
print("UPGRADING $from $to");
if (to < from) {
print("Trying to downgrade from $from to $to");
throw Exception("Can't downgrade database");
}
await customStatement('PRAGMA foreign_keys = OFF');
await transaction(
() async {
for (var i = from; i < to; i++) {
await migrationsMap[i](m, this);
}
},
);
await customStatement('PRAGMA foreign_keys = ON');
},
typedef MigrateFunction = Future<void> Function(Migrator, AppDatabase);
final Map<int, MigrateFunction> migrationsMap = {
1: migrate1,
2: migrate2,
3: migrate3,
4: migrate4,
...
};
Future<void> migrate1(Migrator m, AppDatabase db) async {
print("Migration 1 to 2");
...
}
Future<void> migrate2(Migrator m, AppDatabase db) async {
print("Migration 2 to 3");
...
}
@davidmartos96 That great, thanks for the input.
@MuhammadDicky Anytime!
What if someone going from 1 to 3?
version 1.0 of the app have a schema version 1
version 2.0 of the app have a schema version 2
version 3.0 of the app have a schema version 3
and someone has version 1.0 of the app and then he doesn't update the app until version 3.0 of the app comes
now he is updating from version 1.0 to 3.0 it means schema from 1 to 3.
please explain
@muhammadfaheem-pycom This is covered by the snippet David posted:
for (var i = from; i < to; i++) {
await migrationsMap[i](m, this);
}
You can just apply the migration for 1 -> 2 and 2 -> 3 in sequence.
Most helpful comment
@MuhammadDicky This is what I do. It has been working great for me.