diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 70520ce1b..6ca684c8c 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -176,9 +176,11 @@ public struct DatabaseMigrator { /// - throws: An eventual error thrown by the registered migration blocks. public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws { if eraseDatabaseOnSchemaChange { + // Create a temporary witness database, on disk, just in case + // migrations would involve a lot of data. let witness = try DatabaseQueue(path: "") - // Erase database if we detect a change in the *current* schema. + // Erase database if we detect a change in the current schema. let (currentIdentifier, currentSchema) = try writer.writeWithoutTransaction { db -> (String?, SchemaInfo) in try setupMigrations(db) let identifiers = try appliedIdentifiers(db) @@ -188,6 +190,7 @@ public struct DatabaseMigrator { .identifier return try (currentIdentifier, db.schema()) } + if let currentIdentifier = currentIdentifier { let witnessSchema: SchemaInfo = try witness.writeWithoutTransaction { db in try setupMigrations(db) @@ -199,33 +202,12 @@ public struct DatabaseMigrator { try writer.erase() } } - - // Migrate to *target* schema - let schema: SchemaInfo = try writer.writeWithoutTransaction { db in - try setupMigrations(db) - try runMigrations(db, upTo: targetIdentifier) - return try db.schema() - } - - // Erase database if we detect a change in the *target* schema. - let witnessSchema: SchemaInfo = try witness.writeWithoutTransaction { db in - try setupMigrations(db) - try runMigrations(db, upTo: targetIdentifier) - return try db.schema() - } - - if schema != witnessSchema { - try writer.erase() - try writer.writeWithoutTransaction { db in - try setupMigrations(db) - try runMigrations(db, upTo: targetIdentifier) - } - } - } else { - try writer.writeWithoutTransaction { db in - try setupMigrations(db) - try runMigrations(db, upTo: targetIdentifier) - } + } + + // Migrate to target schema + try writer.writeWithoutTransaction { db in + try setupMigrations(db) + try runMigrations(db, upTo: targetIdentifier) } }