fix database migration

This commit is contained in:
unknown 2021-09-18 16:30:17 +02:00
parent 68d92c4462
commit d5ba231fcc
No known key found for this signature in database
GPG Key ID: 1D070E0B09CFB257

View File

@ -57,7 +57,7 @@ Future<void> migrateDB(
Map<String, Object?> defaultValues, Map<String, Object?> defaultValues,
Future<DatabaseStruct> Function(Database) create, Future<DatabaseStruct> Function(Database) create,
) async { ) async {
var originalRows = (await db.query(table)); var originalRows = await db.query(table);
if (originalRows.length == 0) { if (originalRows.length == 0) {
await db.execute("drop table $table"); await db.execute("drop table $table");
@ -65,6 +65,8 @@ Future<void> migrateDB(
return; return;
} }
List<Map<String, dynamic>> migrated = [];
await Future.forEach<Map<String, Object?>>(originalRows, (original) async { await Future.forEach<Map<String, Object?>>(originalRows, (original) async {
bool migrationRequired = keys.any((key) => !original.containsKey(key) || original[key] == null); bool migrationRequired = keys.any((key) => !original.containsKey(key) || original[key] == null);
@ -72,9 +74,6 @@ Future<void> migrateDB(
print("INFO: Migrating $table"); print("INFO: Migrating $table");
var copy = Map<String, dynamic>.from(original); var copy = Map<String, dynamic>.from(original);
// Delete table
await db.execute("drop table $table");
// Fill missing columns // Fill missing columns
keys.forEach((key) { keys.forEach((key) {
if (!keys.contains(key)) { if (!keys.contains(key)) {
@ -88,11 +87,20 @@ Future<void> migrateDB(
} }
}); });
// Recreate table migrated.add(copy);
await create(db);
await db.insert(table, copy);
print("INFO: Database migrated");
} }
}); });
if (migrated.length > 0) {
// Delete table
await db.execute("drop table $table");
// Recreate table
await create(db);
await Future.forEach(migrated, (Map<String, dynamic> copy) async {
await db.insert(table, copy);
});
print("INFO: Database migrated");
}
} }