diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index ec1eba555..fa02bce43 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -267,6 +267,10 @@ extension Database { schemaCache.set(canonicalTableName: canonicalTableName, forTable: tableName) return canonicalTableName } + + func schema() throws -> SchemaInfo { + return try SchemaInfo(self) + } } extension Database { @@ -558,3 +562,24 @@ public struct ForeignKeyInfo { return mapping.map { $0.destination } } } + +struct SchemaInfo: Equatable { + var objects: [SchemaKey: String?] + + init(_ db: Database) throws { + objects = try Dictionary(uniqueKeysWithValues: Row + .fetchAll(db, "SELECT type, name, tbl_name, sql FROM sqlite_master") + .map { row in (SchemaKey(row: row), row["sql"]) }) + } + + struct SchemaKey: Codable, Hashable, FetchableRecord { + var type: String + var name: String + var tbl_name: String? + + // TODO: remove when Hashable conformance is synthesized + var hashValue: Int { + return type.hashValue ^ name.hashValue ^ (tbl_name?.hashValue ?? 0) + } + } +} diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 00f0100ab..2b7838b95 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -42,7 +42,33 @@ /// /// try migrator.migrate(dbQueue) public struct DatabaseMigrator { - + /// When the `eraseDatabaseOnSchemaChange` flag is true, the migrator will + /// automatically wipe out the full database content, and recreate the whole + /// database from scratch, if it detects that a migration has changed its + /// definition. + /// + /// This flag can destroy your precious users' data! + /// + /// But it may be useful in two situations: + /// + /// 1. During application development, as you are still designing + /// migrations, and the schema changes often. + /// + /// In this case, it is recommended that you make sure this flag does + /// not ship in the distributed application, in order to avoid undesired + /// data loss: + /// + /// var migrator = DatabaseMigrator() + /// #if DEBUG + /// // Speed up development by nuking the database when migrations change + /// migrator.eraseDatabaseOnSchemaChange = true + /// #endif + /// + /// 2. When the database content can easily be recreated, such as a cache + /// for some downloaded data. + public var eraseDatabaseOnSchemaChange = false + private var migrations: [Migration] = [] + /// A new migrator. public init() { } @@ -128,10 +154,10 @@ public struct DatabaseMigrator { /// migrations should apply. /// - throws: An eventual error thrown by the registered migration blocks. public func migrate(_ writer: DatabaseWriter) throws { - try writer.writeWithoutTransaction { db in - try setupMigrations(db) - try runMigrations(db) + guard let lastMigration = migrations.last else { + return } + try migrate(writer, upTo: lastMigration.identifier) } /// Iterate migrations in the same order as they were registered, up to the @@ -143,9 +169,57 @@ public struct DatabaseMigrator { /// - targetIdentifier: The identifier of a registered migration. /// - throws: An eventual error thrown by the registered migration blocks. public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws { - try writer.writeWithoutTransaction { db in - try setupMigrations(db) - try runMigrations(db, upTo: targetIdentifier) + if eraseDatabaseOnSchemaChange { + let witness = try DatabaseQueue(path: "") + + let (currentIdentifier, currentSchema) = try writer.writeWithoutTransaction { db -> (String?, SchemaInfo) in + try setupMigrations(db) + let identifiers = try appliedIdentifiers(db) + let currentIdentifier = try migrations + .reversed() + .first { identifiers.contains($0.identifier) }? + .identifier + return try (currentIdentifier, db.schema()) + } + if let currentIdentifier = currentIdentifier { + let witnessSchema: SchemaInfo = try witness.writeWithoutTransaction { db in + try setupMigrations(db) + try runMigrations(db, upTo: currentIdentifier) + return try db.schema() + } + + if currentSchema != witnessSchema { + try writer.erase() + try writer.writeWithoutTransaction { db in + try setupMigrations(db) + try runMigrations(db, upTo: currentIdentifier) + } + } + } + + let schema: SchemaInfo = try writer.writeWithoutTransaction { db in + try runMigrations(db, upTo: targetIdentifier) + return try db.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) + } } } @@ -157,8 +231,6 @@ public struct DatabaseMigrator { // MARK: - Non public - private var migrations: [Migration] = [] - private mutating func registerMigration(_ migration: Migration) { GRDBPrecondition(!migrations.map({ $0.identifier }).contains(migration.identifier), "already registered migration: \(String(reflecting: migration.identifier))") migrations.append(migration) @@ -172,13 +244,6 @@ public struct DatabaseMigrator { return try Set(String.fetchAll(db, "SELECT identifier FROM grdb_migrations")) } - private func runMigrations(_ db: Database) throws { - let appliedIdentifiers = try self.appliedIdentifiers(db) - for migration in migrations where !appliedIdentifiers.contains(migration.identifier) { - try migration.run(db) - } - } - private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws { var prefixMigrations: [Migration] = [] for migration in migrations { diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 69edf1f38..ff6ba59ac 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -238,4 +238,77 @@ class DatabaseMigratorTests : GRDBTestCase { } } } + + func testEraseDatabaseOnSchemaChange() throws { + // 1st version of the migrator + var migrator1 = DatabaseMigrator() + migrator1.registerMigration("1") { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + } + } + + // 2nd version of the migrator + var migrator2 = DatabaseMigrator() + migrator2.registerMigration("1") { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + t.column("score", .integer) // <- schema change, because reasons (development) + } + } + migrator2.registerMigration("2") { db in + try db.execute("INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)") + } + + // Apply 1st migrator + let dbQueue = try makeDatabaseQueue() + try migrator1.migrate(dbQueue) + + // Test than 2nd migrator can't run... + do { + try migrator2.migrate(dbQueue) + XCTFail("Expected DatabaseError") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssertEqual(error.message, "table player has no column named score") + } + try XCTAssertEqual(migrator2.appliedMigrations(in: dbQueue), ["1"]) + + // ... unless databaase gets erased + migrator2.eraseDatabaseOnSchemaChange = true + try migrator2.migrate(dbQueue) + try XCTAssertEqual(migrator2.appliedMigrations(in: dbQueue), ["1", "2"]) + } + + func testEraseDatabaseOnSchemaChangeDoesNotEraseDatabaseOnAddedMigration() throws { + var migrator = DatabaseMigrator() + migrator.eraseDatabaseOnSchemaChange = true + + var witness = 1 + migrator.registerMigration("1") { db in + try db.execute(""" + CREATE TABLE t1(id INTEGER PRIMARY KEY); + INSERT INTO t1(id) VALUES (?) + """, arguments: [witness]) + witness += 1 + } + + let dbQueue = try makeDatabaseQueue() + + // 1st migration + try migrator.migrate(dbQueue) + try XCTAssertEqual(dbQueue.read { try Int.fetchOne($0, "SELECT id FROM t1") }, 1) + + // 2nd migration does not erase database + migrator.registerMigration("2") { db in + try db.execute(""" + CREATE TABLE t2(id INTEGER PRIMARY KEY); + """) + } + try migrator.migrate(dbQueue) + try XCTAssertEqual(dbQueue.read { try Int.fetchOne($0, "SELECT id FROM t1") }, 1) + try XCTAssertTrue(dbQueue.read { try $0.tableExists("t2") }) + } }