From d5ba231fcca4dde24d4950d9c09375d60057996e Mon Sep 17 00:00:00 2001 From: unknown <55nknown@pm.me> Date: Sat, 18 Sep 2021 16:30:17 +0200 Subject: [PATCH] fix database migration --- filcnaplo/lib/database/init.dart | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/filcnaplo/lib/database/init.dart b/filcnaplo/lib/database/init.dart index 3d27729..3590cf1 100644 --- a/filcnaplo/lib/database/init.dart +++ b/filcnaplo/lib/database/init.dart @@ -57,7 +57,7 @@ Future migrateDB( Map defaultValues, Future Function(Database) create, ) async { - var originalRows = (await db.query(table)); + var originalRows = await db.query(table); if (originalRows.length == 0) { await db.execute("drop table $table"); @@ -65,6 +65,8 @@ Future migrateDB( return; } + List> migrated = []; + await Future.forEach>(originalRows, (original) async { bool migrationRequired = keys.any((key) => !original.containsKey(key) || original[key] == null); @@ -72,9 +74,6 @@ Future migrateDB( print("INFO: Migrating $table"); var copy = Map.from(original); - // Delete table - await db.execute("drop table $table"); - // Fill missing columns keys.forEach((key) { if (!keys.contains(key)) { @@ -88,11 +87,20 @@ Future migrateDB( } }); - // Recreate table - await create(db); - await db.insert(table, copy); - - print("INFO: Database migrated"); + migrated.add(copy); } }); + + if (migrated.length > 0) { + // Delete table + await db.execute("drop table $table"); + + // Recreate table + await create(db); + await Future.forEach(migrated, (Map copy) async { + await db.insert(table, copy); + }); + + print("INFO: Database migrated"); + } }