migrate method
Update database structure with latest migrations. Note that this will run
the migrations
in the order provided.
Implementation
Future<void> migrate(List<Migration> migrations) async {
final db = await getDb();
// Ensure foreign keys are enabled
await db.execute('PRAGMA foreign_keys = ON');
final latestMigrationVersion = MigrationManager.latestMigrationVersion(migrations);
final latestSqliteMigrationVersion = await lastMigrationVersion();
// Guard if migration has already been committed.
if (latestSqliteMigrationVersion == latestMigrationVersion) {
_logger.info('Already at latest migration version ($latestMigrationVersion)');
return;
}
for (var migration in migrations) {
for (var command in migration.up) {
_logger.finer(
'Running migration (${migration.version}): ${command.statement ?? command.forGenerator}');
final alterCommand = AlterColumnHelper(command);
await _lock.synchronized(() async {
if (alterCommand.requiresSchema) {
await alterCommand.execute(db);
} else if (command.statement != null) {
await db.execute(command.statement!);
}
});
}
await db.rawInsert(
'INSERT INTO $_migrationVersionsTableName(version) VALUES(?)',
[migration.version],
);
}
}