diff --git a/CHANGELOG.md b/CHANGELOG.md index 060f83c92..0e9da65c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,17 @@ 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 Released June 17, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v3.0.0...v3.1.0) 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/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..9e17ef96b 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -169,41 +169,8 @@ 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 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 d60a88c93..3ffde08bc 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,61 @@ 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 { + #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 + 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 + } + + // 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 + try DatabaseQueue().backup(to: self) + #endif + } + + // 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 diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 00f0100ab..c993fe241 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: "") + + // 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 = 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() + } + } + + // 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) + } } } @@ -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/README.md b/README.md index 3c3e18842..a74664286 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: + + ```swift + 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 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 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") }) + } } diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index ee3188fc8..ea085368a 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -50,4 +50,44 @@ 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 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; + 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.tableExists("ft")) + 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")) + } + } }