From 86d93b11ddd4c18fa6873d6766d1cfd0a7d07b35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 6 Jul 2018 13:57:55 +0200 Subject: [PATCH 01/15] Easier database backup invocation --- GRDB/Core/Database.swift | 42 ++++++++++++++++++++++++++++++++++ GRDB/Core/DatabaseReader.swift | 35 +--------------------------- 2 files changed, 43 insertions(+), 34 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 56e708767..0fcb49f41 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -782,6 +782,48 @@ extension Database { } } +extension Database { + + // MARK: - Backup + + static func backup(from dbFrom: Database, to dbDest: Database, afterBackupInit: (() -> ())? = nil, afterBackupStep: (() -> ())? = nil) throws { + guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main") else { + throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage) + } + guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else { + throw DatabaseError(resultCode: .SQLITE_ERROR) + } + + afterBackupInit?() + + do { + backupLoop: while true { + switch sqlite3_backup_step(backup, -1) { + case SQLITE_DONE: + afterBackupStep?() + break backupLoop + case SQLITE_OK: + afterBackupStep?() + case let code: + throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage) + } + } + } catch { + sqlite3_backup_finish(backup) + throw error + } + + switch sqlite3_backup_finish(backup) { + case SQLITE_OK: + break + case let code: + throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage) + } + + dbDest.clearSchemaCache() + } +} + #if SQLITE_HAS_CODEC extension Database { diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index b3222c6f0..d1540cbfd 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -170,40 +170,7 @@ extension DatabaseReader { func backup(to writer: DatabaseWriter, afterBackupInit: (() -> ())?, afterBackupStep: (() -> ())?) throws { try read { dbFrom in try writer.write { dbDest in - guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main") else { - throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage) - } - guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else { - throw DatabaseError(resultCode: .SQLITE_ERROR) - } - - afterBackupInit?() - - do { - backupLoop: while true { - switch sqlite3_backup_step(backup, -1) { - case SQLITE_DONE: - afterBackupStep?() - break backupLoop - case SQLITE_OK: - afterBackupStep?() - case let code: - throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage) - } - } - } catch { - sqlite3_backup_finish(backup) - throw error - } - - switch sqlite3_backup_finish(backup) { - case SQLITE_OK: - break - case let code: - throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage) - } - - dbDest.clearSchemaCache() + try Database.backup(from: dbFrom, to: dbDest, afterBackupInit: afterBackupInit, afterBackupStep: afterBackupStep) } } } From a465f16ff7837d1640375c39e27163ca220abba8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 6 Jul 2018 13:58:55 +0200 Subject: [PATCH 02/15] databaseWriter.erase(), databaseWriter.vacuum() --- GRDB/Core/DatabaseWriter.swift | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index d60a88c93..5d18943ae 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -57,7 +57,7 @@ public protocol DatabaseWriter : DatabaseReader { /// This method is reentrant. It should be avoided because it fosters /// dangerous concurrency practices. func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T - + // MARK: - Reading from Database /// Synchronously or asynchronously executes a read-only block that takes a @@ -102,6 +102,26 @@ extension DatabaseWriter { public func remove(transactionObserver: TransactionObserver) { writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) } } + + // MARK: - Erasing the content of the database + + /// Erases the content of the database. + /// + /// - precondition: database is not accessed concurrently during the + /// execution of this method. + public func erase() throws { + try DatabaseQueue().backup(to: self) + } + + // MARK: - Claiming Disk Space + + /// Rebuilds the database file, repacking it into a minimal amount of + /// disk space. + /// + /// See https://www.sqlite.org/lang_vacuum.html for more information. + public func vacuum() throws { + try writeWithoutTransaction { try $0.execute("VACUUM") } + } } /// A type-erased DatabaseWriter From 0bc25f877337e82d0b0bd4da90c15a02b53c49c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 6 Jul 2018 14:03:44 +0200 Subject: [PATCH 03/15] Tests for DatabaseQueue and DatabasePool erase and vacuum --- Tests/GRDBTests/DatabasePoolBackupTests.swift | 26 +++++++++++++++++++ Tests/GRDBTests/DatabaseQueueTests.swift | 26 +++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/Tests/GRDBTests/DatabasePoolBackupTests.swift b/Tests/GRDBTests/DatabasePoolBackupTests.swift index 0bf37285f..2dc31b78d 100644 --- a/Tests/GRDBTests/DatabasePoolBackupTests.swift +++ b/Tests/GRDBTests/DatabasePoolBackupTests.swift @@ -81,4 +81,30 @@ class DatabasePoolBackupTests: GRDBTestCase { // XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1) // } // } + + func testEraseAndVacuum() throws { + let writer = try makeDatabasePool() + try writer.write { db in + try db.execute("CREATE TABLE t (a, b UNIQUE)") + try db.execute("CREATE INDEX i ON t(a)") + try db.execute("CREATE VIEW v AS SELECT a FROM t") + try db.execute("CREATE TRIGGER tr AFTER INSERT ON t BEGIN INSERT INTO t (a, b) VALUES (1, 2); END") + } + + try writer.read { db in + try XCTAssertTrue(db.tableExists("t")) + try XCTAssertTrue(db.viewExists("v")) + try XCTAssertTrue(db.triggerExists("tr")) + try XCTAssertEqual(db.indexes(on: "t").count, 2) + } + + try writer.erase() + try writer.vacuum() + + try writer.read { db in + try XCTAssertFalse(db.tableExists("t")) + try XCTAssertFalse(db.viewExists("i")) + try XCTAssertFalse(db.triggerExists("tr")) + } + } } diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index 2c3b84dbf..37bf3b12c 100644 --- a/Tests/GRDBTests/DatabaseQueueTests.swift +++ b/Tests/GRDBTests/DatabaseQueueTests.swift @@ -131,4 +131,30 @@ class DatabaseQueueTests: GRDBTestCase { XCTAssertEqual(label, "Toreador") } } + + func testEraseAndVacuum() throws { + let writer = try makeDatabaseQueue() + try writer.write { db in + try db.execute("CREATE TABLE t (a, b UNIQUE)") + try db.execute("CREATE INDEX i ON t(a)") + try db.execute("CREATE VIEW v AS SELECT a FROM t") + try db.execute("CREATE TRIGGER tr AFTER INSERT ON t BEGIN INSERT INTO t (a, b) VALUES (1, 2); END") + } + + try writer.read { db in + try XCTAssertTrue(db.tableExists("t")) + try XCTAssertTrue(db.viewExists("v")) + try XCTAssertTrue(db.triggerExists("tr")) + try XCTAssertEqual(db.indexes(on: "t").count, 2) + } + + try writer.erase() + try writer.vacuum() + + try writer.read { db in + try XCTAssertFalse(db.tableExists("t")) + try XCTAssertFalse(db.viewExists("i")) + try XCTAssertFalse(db.triggerExists("tr")) + } + } } From a73be9c010976aa058201f99193dde72fdbb1ef9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 7 Jul 2018 12:32:40 +0200 Subject: [PATCH 04/15] Fix databaseWriter.erase() with SQLCipher --- GRDB/Core/DatabaseReader.swift | 2 +- GRDB/Core/DatabaseWriter.swift | 27 +++++++++++++ Tests/GRDBTests/DatabasePoolBackupTests.swift | 26 ------------- Tests/GRDBTests/DatabaseQueueTests.swift | 26 ------------- Tests/GRDBTests/DatabaseWriterTests.swift | 38 +++++++++++++++++++ 5 files changed, 66 insertions(+), 53 deletions(-) diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index d1540cbfd..9e17ef96b 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -169,7 +169,7 @@ extension DatabaseReader { func backup(to writer: DatabaseWriter, afterBackupInit: (() -> ())?, afterBackupStep: (() -> ())?) throws { try read { dbFrom in - try writer.write { dbDest in + try writer.writeWithoutTransaction { dbDest in try Database.backup(from: dbFrom, to: dbDest, afterBackupInit: afterBackupInit, afterBackupStep: afterBackupStep) } } diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 5d18943ae..966a45815 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -110,7 +110,34 @@ extension DatabaseWriter { /// - precondition: database is not accessed concurrently during the /// execution of this method. public func erase() throws { + #if SQLITE_HAS_CODEC + // SQLCipher does not support the backup API: https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631 + // So we'll drop all database objects one after the other. + try writeWithoutTransaction { db in + // Prevent foreign keys from messing with drop table statements + let foreignKeysEnabled = try Bool.fetchOne(db, "PRAGMA foreign_keys")! + if foreignKeysEnabled { + try db.execute("PRAGMA foreign_keys = OFF") + } + + // Remove all database objects, one after the other + try db.inTransaction { + while let row = try Row.fetchOne(db, "SELECT type, name FROM sqlite_master") { + let type: String = row["type"] + let name: String = row["name"] + try db.execute("DROP \(type) \(name.quotedDatabaseIdentifier)") + } + return .commit + } + + // Restore foreign keys if needed + if foreignKeysEnabled { + try db.execute("PRAGMA foreign_keys = ON") + } + } + #else try DatabaseQueue().backup(to: self) + #endif } // MARK: - Claiming Disk Space diff --git a/Tests/GRDBTests/DatabasePoolBackupTests.swift b/Tests/GRDBTests/DatabasePoolBackupTests.swift index 2dc31b78d..0bf37285f 100644 --- a/Tests/GRDBTests/DatabasePoolBackupTests.swift +++ b/Tests/GRDBTests/DatabasePoolBackupTests.swift @@ -81,30 +81,4 @@ class DatabasePoolBackupTests: GRDBTestCase { // XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1) // } // } - - func testEraseAndVacuum() throws { - let writer = try makeDatabasePool() - try writer.write { db in - try db.execute("CREATE TABLE t (a, b UNIQUE)") - try db.execute("CREATE INDEX i ON t(a)") - try db.execute("CREATE VIEW v AS SELECT a FROM t") - try db.execute("CREATE TRIGGER tr AFTER INSERT ON t BEGIN INSERT INTO t (a, b) VALUES (1, 2); END") - } - - try writer.read { db in - try XCTAssertTrue(db.tableExists("t")) - try XCTAssertTrue(db.viewExists("v")) - try XCTAssertTrue(db.triggerExists("tr")) - try XCTAssertEqual(db.indexes(on: "t").count, 2) - } - - try writer.erase() - try writer.vacuum() - - try writer.read { db in - try XCTAssertFalse(db.tableExists("t")) - try XCTAssertFalse(db.viewExists("i")) - try XCTAssertFalse(db.triggerExists("tr")) - } - } } diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index 37bf3b12c..2c3b84dbf 100644 --- a/Tests/GRDBTests/DatabaseQueueTests.swift +++ b/Tests/GRDBTests/DatabaseQueueTests.swift @@ -131,30 +131,4 @@ class DatabaseQueueTests: GRDBTestCase { XCTAssertEqual(label, "Toreador") } } - - func testEraseAndVacuum() throws { - let writer = try makeDatabaseQueue() - try writer.write { db in - try db.execute("CREATE TABLE t (a, b UNIQUE)") - try db.execute("CREATE INDEX i ON t(a)") - try db.execute("CREATE VIEW v AS SELECT a FROM t") - try db.execute("CREATE TRIGGER tr AFTER INSERT ON t BEGIN INSERT INTO t (a, b) VALUES (1, 2); END") - } - - try writer.read { db in - try XCTAssertTrue(db.tableExists("t")) - try XCTAssertTrue(db.viewExists("v")) - try XCTAssertTrue(db.triggerExists("tr")) - try XCTAssertEqual(db.indexes(on: "t").count, 2) - } - - try writer.erase() - try writer.vacuum() - - try writer.read { db in - try XCTAssertFalse(db.tableExists("t")) - try XCTAssertFalse(db.viewExists("i")) - try XCTAssertFalse(db.triggerExists("tr")) - } - } } diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index ee3188fc8..8126ee744 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -50,4 +50,42 @@ class DatabaseWriterTests : GRDBTestCase { let writer: DatabaseWriter = DatabaseQueue() let _: DatabaseWriter = AnyDatabaseWriter(writer) } + + func testEraseAndVacuum() throws { + try testEraseAndVacuum(writer: makeDatabaseQueue()) + try testEraseAndVacuum(writer: makeDatabasePool()) + } + + private func testEraseAndVacuum(writer: DatabaseWriter) throws { + var migrator = DatabaseMigrator() + migrator.registerMigration("init") { db in + // Create a database with recursive constraints, so that we test + // that those don't prevent database erasure. + try db.execute(""" + CREATE TABLE t1 (id INTEGER PRIMARY KEY, b UNIQUE, c REFERENCES t2(id) ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED); + CREATE TABLE t2 (id INTEGER PRIMARY KEY, b UNIQUE, c REFERENCES t1(id) ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED); + CREATE INDEX i ON t1(c); + CREATE VIEW v AS SELECT id FROM t1; + CREATE TRIGGER tr AFTER INSERT ON t1 BEGIN INSERT INTO t2 (id, b, c) VALUES (NEW.c, NEW.b, NEW.id); END; + INSERT INTO t1 (id, b, c) VALUES (1, 1, 1) + """) + } + + try migrator.migrate(writer) + + try writer.read { db in + try XCTAssertTrue(db.tableExists("t1")) + try XCTAssertTrue(db.tableExists("t2")) + try XCTAssertTrue(db.viewExists("v")) + try XCTAssertTrue(db.triggerExists("tr")) + try XCTAssertEqual(db.indexes(on: "t1").count, 2) + } + + try writer.erase() + try writer.vacuum() + + try writer.read { db in + try XCTAssertNil(Row.fetchOne(db, "SELECT * FROM sqlite_master")) + } + } } From fee4486d1b7d680415f7ee7c1d04def9b93fa91f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 7 Jul 2018 14:23:50 +0200 Subject: [PATCH 05/15] DatabaseMigrator.eraseDatabaseOnSchemaChange --- GRDB/Core/Database+Schema.swift | 25 ++++++ GRDB/Migration/DatabaseMigrator.swift | 97 +++++++++++++++++---- Tests/GRDBTests/DatabaseMigratorTests.swift | 73 ++++++++++++++++ 3 files changed, 179 insertions(+), 16 deletions(-) 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") }) + } } From e84b539de2a73b252a9a5fcfdd896308581e6593 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 7 Jul 2018 14:42:18 +0200 Subject: [PATCH 06/15] DatabaseWriter.erase(): don't mess with internal SQLite objects --- GRDB/Core/DatabaseWriter.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 966a45815..4a714ce0c 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -122,7 +122,7 @@ extension DatabaseWriter { // Remove all database objects, one after the other try db.inTransaction { - while let row = try Row.fetchOne(db, "SELECT type, name FROM sqlite_master") { + while let row = try Row.fetchOne(db, "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'") { let type: String = row["type"] let name: String = row["name"] try db.execute("DROP \(type) \(name.quotedDatabaseIdentifier)") From 35938066855b367e47f4c8c0f369b0a65f34d9ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 7 Jul 2018 14:49:43 +0200 Subject: [PATCH 07/15] Cleanup --- GRDB/Migration/DatabaseMigrator.swift | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 2b7838b95..c993fe241 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -172,10 +172,11 @@ public struct DatabaseMigrator { if eraseDatabaseOnSchemaChange { let witness = try DatabaseQueue(path: "") + // 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) - let currentIdentifier = try migrations + let currentIdentifier = migrations .reversed() .first { identifiers.contains($0.identifier) }? .identifier @@ -190,18 +191,17 @@ public struct DatabaseMigrator { if currentSchema != witnessSchema { try writer.erase() - try writer.writeWithoutTransaction { db in - try setupMigrations(db) - try runMigrations(db, upTo: currentIdentifier) - } } } + // 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) From fc2d5419b3ec194fdcf025eae72c314564c4f945 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 7 Jul 2018 17:17:23 +0200 Subject: [PATCH 08/15] CHANGELOG --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 060f83c92..a77a1ce39 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ Release Notes ============= +## Next Version + +- [#381](https://github.com/groue/GRDB.swift/pull/381): Nuking db during development + + ## 3.1.0 Released June 17, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v3.0.0...v3.1.0) From d814249c5a7a85e3de17e73569ea722020b2ec96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 7 Jul 2018 17:34:44 +0200 Subject: [PATCH 09/15] eraseDatabaseOnSchemaChange documentation --- README.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/README.md b/README.md index 3c3e18842..a62384425 100644 --- a/README.md +++ b/README.md @@ -4344,6 +4344,35 @@ if appliedMigrations.contains("v2") { } ``` +### The `eraseDatabaseOnSchemaChange` Option + +A DatabaseMigrator can automatically wipe out the full database content, and recreate the whole database from scratch, if it detects that a migration has changed its definition: + +```swift +var migrator = DatabaseMigrator() +migrator.eraseDatabaseOnSchemaChange = true +``` + +Beware! This flag can destroy your precious users' data! + +Yet it may be useful in those two situations: + +1. During application development, as you are still designing migrations, and the schema changes often. + + In this case, it is recommended that this flag does not ship in the distributed application: + + ```swif + 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. + +The `eraseDatabaseOnSchemaChange` option triggers a recreation of the database if and only the migrator detects a *schema change*. A schema change is any difference in the `sqlite_master` table, which contains the SQL used to create database tables, indexes, triggers, and views. + ### Advanced Database Schema Changes From 91d0a453daea989e93746c6faf8f0b86365e119d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 7 Jul 2018 17:43:26 +0200 Subject: [PATCH 10/15] DatabaseWriter.erase(): more robust error handling --- GRDB/Core/DatabaseWriter.swift | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 4a714ce0c..3ffde08bc 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -121,18 +121,26 @@ extension DatabaseWriter { } // Remove all database objects, one after the other - try db.inTransaction { - while let row = try Row.fetchOne(db, "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'") { - let type: String = row["type"] - let name: String = row["name"] - try db.execute("DROP \(type) \(name.quotedDatabaseIdentifier)") + do { + try db.inTransaction { + while let row = try Row.fetchOne(db, "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'") { + let type: String = row["type"] + let name: String = row["name"] + try db.execute("DROP \(type) \(name.quotedDatabaseIdentifier)") + } + return .commit } - return .commit - } - - // Restore foreign keys if needed - if foreignKeysEnabled { - try db.execute("PRAGMA foreign_keys = ON") + + // Restore foreign keys if needed + if foreignKeysEnabled { + try db.execute("PRAGMA foreign_keys = ON") + } + } catch { + // Restore foreign keys if needed + if foreignKeysEnabled { + try? db.execute("PRAGMA foreign_keys = ON") + } + throw error } } #else From 3405585d60a820d057c3899ef7c9e39600e15267 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 7 Jul 2018 17:43:37 +0200 Subject: [PATCH 11/15] Typo fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a62384425..ce16da582 100644 --- a/README.md +++ b/README.md @@ -4361,7 +4361,7 @@ Yet it may be useful in those two situations: In this case, it is recommended that this flag does not ship in the distributed application: - ```swif + ```swift var migrator = DatabaseMigrator() #if DEBUG // Speed up development by nuking the database when migrations change From 22006e2251f16767abc4d4af52b733de21584c1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 7 Jul 2018 17:43:42 +0200 Subject: [PATCH 12/15] CHANGELOG --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a77a1ce39..0e9da65c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,8 +3,14 @@ Release Notes ## Next Version +### New + - [#381](https://github.com/groue/GRDB.swift/pull/381): Nuking db during development +### Documentation Diff + +- [The `eraseDatabaseOnSchemaChange` Option](README.md#the-erasedatabaseonschemachange-option): See how a DatabaseMigrator can automatically recreate the whole database when a migration has changed its definition. + ## 3.1.0 From 1a84a84bd173fbe8a0c84d3ba34b5bdb8638f3f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 7 Jul 2018 17:45:15 +0200 Subject: [PATCH 13/15] Typo fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ce16da582..a74664286 100644 --- a/README.md +++ b/README.md @@ -4371,7 +4371,7 @@ Yet it may be useful in those two situations: 2. When the database content can easily be recreated, such as a cache for some downloaded data. -The `eraseDatabaseOnSchemaChange` option triggers a recreation of the database if and only the migrator detects a *schema change*. A schema change is any difference in the `sqlite_master` table, which contains the SQL used to create database tables, indexes, triggers, and views. +The `eraseDatabaseOnSchemaChange` option triggers a recreation of the database if the migrator detects a *schema change*. A schema change is any difference in the `sqlite_master` table, which contains the SQL used to create database tables, indexes, triggers, and views. ### Advanced Database Schema Changes From fdef88d1503835acd6ef7f4c94c950c46bcdd8c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 7 Jul 2018 17:51:55 +0200 Subject: [PATCH 14/15] DatabaseWriterTests.testEraseAndVacuum: add a virtual table --- Tests/GRDBTests/DatabaseWriterTests.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index 8126ee744..adaae08af 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -64,6 +64,7 @@ class DatabaseWriterTests : GRDBTestCase { try db.execute(""" CREATE TABLE t1 (id INTEGER PRIMARY KEY, b UNIQUE, c REFERENCES t2(id) ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED); CREATE TABLE t2 (id INTEGER PRIMARY KEY, b UNIQUE, c REFERENCES t1(id) ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED); + CREATE VIRTUAL TABLE ft USING fts4(content); CREATE INDEX i ON t1(c); CREATE VIEW v AS SELECT id FROM t1; CREATE TRIGGER tr AFTER INSERT ON t1 BEGIN INSERT INTO t2 (id, b, c) VALUES (NEW.c, NEW.b, NEW.id); END; @@ -76,6 +77,7 @@ class DatabaseWriterTests : GRDBTestCase { try writer.read { db in try XCTAssertTrue(db.tableExists("t1")) try XCTAssertTrue(db.tableExists("t2")) + try XCTAssertTrue(db.tableExists("ft")) try XCTAssertTrue(db.viewExists("v")) try XCTAssertTrue(db.triggerExists("tr")) try XCTAssertEqual(db.indexes(on: "t1").count, 2) From fc2c2658b74b5c270e644c55dd30ca5c7fe3b965 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 7 Jul 2018 17:53:36 +0200 Subject: [PATCH 15/15] DatabaseWriterTests.testEraseAndVacuum: use auto increment so we can test database erasure with internal SQLite objects --- Tests/GRDBTests/DatabaseWriterTests.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index adaae08af..ea085368a 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -62,8 +62,8 @@ class DatabaseWriterTests : GRDBTestCase { // Create a database with recursive constraints, so that we test // that those don't prevent database erasure. try db.execute(""" - CREATE TABLE t1 (id INTEGER PRIMARY KEY, b UNIQUE, c REFERENCES t2(id) ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED); - CREATE TABLE t2 (id INTEGER PRIMARY KEY, b UNIQUE, c REFERENCES t1(id) ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED); + CREATE TABLE t1 (id INTEGER PRIMARY KEY AUTOINCREMENT, b UNIQUE, c REFERENCES t2(id) ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED); + CREATE TABLE t2 (id INTEGER PRIMARY KEY AUTOINCREMENT, b UNIQUE, c REFERENCES t1(id) ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED); CREATE VIRTUAL TABLE ft USING fts4(content); CREATE INDEX i ON t1(c); CREATE VIEW v AS SELECT id FROM t1;