From 51c15e9db61d2e91303b1b5a6f026c4785438cc3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 3 Nov 2021 13:26:24 +0100 Subject: [PATCH 01/11] Precise handling of foreign key checks in migrations --- GRDB/Migration/DatabaseMigrator.swift | 95 +++++++++++- GRDB/Migration/Migration.swift | 35 ++++- Tests/GRDBTests/DatabaseMigratorTests.swift | 162 ++++++++++++++++++++ 3 files changed, 287 insertions(+), 5 deletions(-) diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 1aa0e960d..6c967e4c7 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -47,6 +47,27 @@ import Foundation /// /// try migrator.migrate(dbQueue) public struct DatabaseMigrator { + /// Controls how migrations handle foreign keys constraints. + public enum ForeignKeyChecks { + /// The migration runs with disabled foreign keys, until foreign keys + /// are checked right before changes are committed on disk. + /// + /// These deferred checks are not executed if the migrator comes + /// from `unsafeWithoutDeferredForeignKeyChecks()`. + /// + /// Deferred foreign key checks are necessary for migrations that + /// perform schema changes as described in + /// + case deferred + + /// The migration runs for foreign keys on. + /// + /// Immediate foreign key checks are not compatible with migrations that + /// perform schema changes as described in + /// + case immediate + } + /// 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 @@ -72,12 +93,50 @@ public struct DatabaseMigrator { /// 2. When the database content can easily be recreated, such as a cache /// for some downloaded data. public var eraseDatabaseOnSchemaChange = false + private var defersForeignKeyChecks = true private var _migrations: [Migration] = [] /// A new migrator. public init() { } + // MARK: - Disabling Foreign Key Checks + + /// Returns a migrator that will not perform deferred foreign key checks in + /// all newly registered migrations. + /// + /// The returned migrator is _unsafe_, because it no longer guarantees the + /// integrity of the database. It is your responsibility to register + /// migrations that do not break foreign key constraints. + /// + /// Running migrations without foreign key checks can improve migration + /// performance on huge databases. + /// + /// Example: + /// + /// var migrator = DatabaseMigrator() + /// migrator.registerMigration("A") { db in + /// // Runs with deferred foreign key checks + /// } + /// migrator.registerMigration("B", foreignKeyChecks: .immediate) { db in + /// // Runs with immediate foreign key checks + /// } + /// + /// migrator = migrator.unsafeWithoutDeferredForeignKeyChecks() + /// migrator.registerMigration("C") { db in + /// // Runs with disabled foreign key checks + /// } + /// migrator.registerMigration("D", foreignKeyChecks: .immediate) { db in + /// // Runs with immediate foreign key checks + /// } + /// + /// - warning: Before using this unsafe method, try to run your migrations with + /// `.immediate` foreign key checks, if possible. This may enhance migration + /// performances, while preserving the database integrity guarantee. + public func unsafeWithoutDeferredForeignKeyChecks() -> DatabaseMigrator { + with { $0.defersForeignKeyChecks = false } + } + // MARK: - Registering Migrations /// Registers a migration. @@ -92,10 +151,40 @@ public struct DatabaseMigrator { /// /// - parameters: /// - identifier: The migration identifier. + /// - foreignKeyChecks: This parameter is ignored if the database has + /// not enabled foreign keys. + /// + /// The default `.deferred` checks have the migration run with + /// disabled foreign keys, until foreign keys are checked right before + /// changes are committed on disk. These deferred checks are not + /// executed if the migrator comes + /// from `unsafeWithoutDeferredForeignKeyChecks()`. + /// + /// The `.immediate` checks have the migration run with foreign + /// keys enabled. + /// + /// Only use `.immediate` if you are sure that the migration does not + /// perform schema changes described in + /// /// - block: The migration block that performs SQL statements. /// - precondition: No migration with the same same as already been registered. - public mutating func registerMigration(_ identifier: String, migrate: @escaping (Database) throws -> Void) { - registerMigration(Migration(identifier: identifier, migrate: migrate)) + public mutating func registerMigration( + _ identifier: String, + foreignKeyChecks: ForeignKeyChecks = .deferred, + migrate: @escaping (Database) throws -> Void) + { + let migrationChecks: Migration.ForeignKeyChecks + switch foreignKeyChecks { + case .deferred: + if defersForeignKeyChecks { + migrationChecks = .deferred + } else { + migrationChecks = .disabled + } + case .immediate: + migrationChecks = .immediate + } + registerMigration(Migration(identifier: identifier, foreignKeyChecks: migrationChecks, migrate: migrate)) } // MARK: - Applying Migrations @@ -347,6 +436,8 @@ public struct DatabaseMigrator { } } +extension DatabaseMigrator: Refinable { } + #if canImport(Combine) extension DatabaseMigrator { // MARK: - Publishing Migrations diff --git a/GRDB/Migration/Migration.swift b/GRDB/Migration/Migration.swift index 7550cf407..e6069f446 100644 --- a/GRDB/Migration/Migration.swift +++ b/GRDB/Migration/Migration.swift @@ -1,17 +1,31 @@ /// An internal struct that defines a migration. struct Migration { + public enum ForeignKeyChecks { + case deferred + case immediate + case disabled + } + let identifier: String + var foreignKeyChecks: ForeignKeyChecks let migrate: (Database) throws -> Void func run(_ db: Database) throws { if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false { - try runWithDeferredForeignKeysChecks(db) + switch foreignKeyChecks { + case .deferred: + try runWithDeferredForeignKeysChecks(db) + case .immediate: + try runWithImmediateForeignKeysChecks(db) + case .disabled: + try runWithDisabledForeignKeysChecks(db) + } } else { - try runWithoutDisabledForeignKeys(db) + try runWithImmediateForeignKeysChecks(db) } } - private func runWithoutDisabledForeignKeys(_ db: Database) throws { + private func runWithImmediateForeignKeysChecks(_ db: Database) throws { try db.inTransaction(.immediate) { try migrate(db) try insertAppliedIdentifier(db) @@ -19,6 +33,21 @@ struct Migration { } } + private func runWithDisabledForeignKeysChecks(_ db: Database) throws { + try db.execute(sql: "PRAGMA foreign_keys = OFF") + try throwingFirstError( + execute: { + try db.inTransaction(.immediate) { + try migrate(db) + try insertAppliedIdentifier(db) + return .commit + } + }, + finally: { + try db.execute(sql: "PRAGMA foreign_keys = ON") + }) + } + private func runWithDeferredForeignKeysChecks(_ db: Database) throws { // Support for database alterations described at // https://www.sqlite.org/lang_altertable.html#otheralter diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 4b396dd3d..919e463d7 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -848,4 +848,166 @@ class DatabaseMigratorTests : GRDBTestCase { XCTAssertEqual(migrator.migrations, ["foo", "bar"]) } } + + func testMigrationForeignKeyChecks() throws { + let foreignKeyViolation = """ + CREATE TABLE parent(id INTEGER NOT NULL PRIMARY KEY); + CREATE TABLE child(parentId INTEGER REFERENCES parent(id)); + INSERT INTO child (parentId) VALUES (1); + """ + let transientForeignKeyViolation = """ + CREATE TABLE parent(id INTEGER NOT NULL PRIMARY KEY); + CREATE TABLE child(parentId INTEGER REFERENCES parent(id)); + INSERT INTO child (parentId) VALUES (1); + DELETE FROM child; + """ + + // Foreign key violation + do { + var migrator = DatabaseMigrator() + migrator.registerMigration("A") { db in + try db.execute(sql: foreignKeyViolation) + } + let dbQueue = try makeDatabaseQueue() + do { + try migrator.migrate(dbQueue) + XCTFail("Expected error") + } catch DatabaseError.SQLITE_CONSTRAINT { } + try dbQueue.read { db in + try XCTAssertTrue(Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty()) + } + } + do { + var migrator = DatabaseMigrator() + migrator.registerMigration("A", foreignKeyChecks: .immediate) { db in + try db.execute(sql: foreignKeyViolation) + } + let dbQueue = try makeDatabaseQueue() + do { + try migrator.migrate(dbQueue) + XCTFail("Expected error") + } catch DatabaseError.SQLITE_CONSTRAINT { } + try dbQueue.read { db in + try XCTAssertTrue(Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty()) + } + } + + // Transient foreign key violation + do { + var migrator = DatabaseMigrator() + migrator.registerMigration("A") { db in + try db.execute(sql: transientForeignKeyViolation) + } + let dbQueue = try makeDatabaseQueue() + try migrator.migrate(dbQueue) + try dbQueue.read { db in + try XCTAssertTrue(Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty()) + } + } + do { + var migrator = DatabaseMigrator() + migrator.registerMigration("A", foreignKeyChecks: .immediate) { db in + try db.execute(sql: transientForeignKeyViolation) + } + let dbQueue = try makeDatabaseQueue() + do { + try migrator.migrate(dbQueue) + XCTFail("Expected error") + } catch DatabaseError.SQLITE_CONSTRAINT { } + try dbQueue.read { db in + try XCTAssertTrue(Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty()) + } + } + } + + func testUnsafeWithoutDeferredForeignKeyChecks() throws { + let foreignKeyViolation = """ + CREATE TABLE parent(id INTEGER NOT NULL PRIMARY KEY); + CREATE TABLE child(parentId INTEGER REFERENCES parent(id)); + INSERT INTO child (parentId) VALUES (1); + """ + let transientForeignKeyViolation = """ + CREATE TABLE parent(id INTEGER NOT NULL PRIMARY KEY); + CREATE TABLE child(parentId INTEGER REFERENCES parent(id)); + INSERT INTO child (parentId) VALUES (1); + DELETE FROM child; + """ + + // Foreign key violation + do { + var migrator = DatabaseMigrator().unsafeWithoutDeferredForeignKeyChecks() + migrator.registerMigration("A") { db in + try db.execute(sql: foreignKeyViolation) + } + let dbQueue = try makeDatabaseQueue() + try migrator.migrate(dbQueue) + try dbQueue.read { db in + // The unique opportunity for corrupt data + try XCTAssertFalse(Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty()) + } + } + do { + var migrator = DatabaseMigrator().unsafeWithoutDeferredForeignKeyChecks() + migrator.registerMigration("A", foreignKeyChecks: .immediate) { db in + try db.execute(sql: foreignKeyViolation) + } + let dbQueue = try makeDatabaseQueue() + do { + try migrator.migrate(dbQueue) + XCTFail("Expected error") + } catch DatabaseError.SQLITE_CONSTRAINT { } + try dbQueue.read { db in + try XCTAssertTrue(Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty()) + } + } + + // Transient foreign key violation + do { + var migrator = DatabaseMigrator().unsafeWithoutDeferredForeignKeyChecks() + migrator.registerMigration("A") { db in + try db.execute(sql: transientForeignKeyViolation) + } + let dbQueue = try makeDatabaseQueue() + try migrator.migrate(dbQueue) + try dbQueue.read { db in + try XCTAssertTrue(Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty()) + } + } + do { + var migrator = DatabaseMigrator().unsafeWithoutDeferredForeignKeyChecks() + migrator.registerMigration("A", foreignKeyChecks: .immediate) { db in + try db.execute(sql: transientForeignKeyViolation) + } + let dbQueue = try makeDatabaseQueue() + do { + try migrator.migrate(dbQueue) + XCTFail("Expected error") + } catch DatabaseError.SQLITE_CONSTRAINT { } + try dbQueue.read { db in + try XCTAssertTrue(Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty()) + } + } + } + + func testUnsafeWithoutDeferredForeignKeyChecks_applies_to_newly_registered_migrations() throws { + let foreignKeyViolation = """ + CREATE TABLE parent(id INTEGER NOT NULL PRIMARY KEY); + CREATE TABLE child(parentId INTEGER REFERENCES parent(id)); + INSERT INTO child (parentId) VALUES (1); + """ + + var migrator = DatabaseMigrator() + migrator.registerMigration("A") { db in + try db.execute(sql: foreignKeyViolation) + } + migrator = migrator.unsafeWithoutDeferredForeignKeyChecks() + migrator.registerMigration("B") { db in + XCTFail("Should not run") + } + let dbQueue = try makeDatabaseQueue() + do { + try migrator.migrate(dbQueue) + XCTFail("Expected error") + } catch DatabaseError.SQLITE_CONSTRAINT { } + } } From b66b907fbc145fc0ef9e070220d709d5ffa08018 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 3 Nov 2021 13:58:11 +0100 Subject: [PATCH 02/11] Documentation --- Documentation/Migrations.md | 89 ++++++++++++++++++++++++++++++++++++- 1 file changed, 88 insertions(+), 1 deletion(-) diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index aca5bf756..094ad1d73 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -2,6 +2,15 @@ **Migrations** are a convenient way to alter your database schema over time in a consistent and easy way. +- [Migrations Overview] +- [The `eraseDatabaseOnSchemaChange` Option] +- [Advanced Database Schema Changes] +- [Foreign Key Checks] +- [Asynchronous Migrations] + + +## Migrations Overview + Migrations run in order, once and only once. When a user upgrades your application, only non-applied migrations are run. Inside each migration, you typically [define and update your database tables](../README.md#database-schema) according to your evolving application needs: @@ -31,7 +40,7 @@ migrator.registerMigration("v2") { db in **Each migration runs in a separate transaction.** Should one throw an error, its transaction is rollbacked, subsequent migrations do not run, and the error is eventually thrown by `migrator.migrate(dbQueue)`. -**Migrations run with deferred foreign key checks.** This means that eventual foreign key violations are only checked at the end of the migration (and they make the migration fail). +**Migrations run with deferred foreign key checks.** This means that eventual foreign key violations are only checked at the end of the migration (and they make the migration fail). See [Foreign Key Checks] below for more information. **The memory of applied migrations is stored in the database itself** (in a reserved table). @@ -119,6 +128,76 @@ migrator.registerMigration("AddNotNullCheckOnName") { db in } ``` +Please check [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes) in the SQLite documentation for further information. + + +## Foreign Key Checks + +You'll need to read this chapter if your migrations spend a lot of time performing foreign key checks, and you are looking for a mitigation. + +What are we talking about? SQLite has [limited support](https://www.sqlite.org/lang_altertable.html) for database schema change, and this unfortunately creates unwanted churn regarding foreign keys. In order to accept any kind of schema changes, GRDB migration runs, by default, with deferred foreign key checks. They precisely apply the technique described in [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes): + +1. Disable foreign keys +2. Start a transaction +3. Apply migration +4. Run [`PRAGMA foreign_key_check`](https://www.sqlite.org/pragma.html#pragma_foreign_key_check) to verify that the schema change did not break any foreign key constraints. +5. Commit +6. Reenable foreign keys + +The step 4 can take a long time. + +**Mitigation technique 1: immediate foreign key checks** + +If you register a migration with `.immediate` foreign key checks, the migration will not disable foreign keys, and avoid the slow `PRAGMA foreign_key_check`: + +```swift +migrator.registerMigration("slow", foreignKeyChecks: .immediate) { db in ... } +``` + +1. Start a transaction +2. Apply migration +3. Commit + +Such a migration still guarantees that no foreign key constraint is broken. But it can not run the kind of migrations covered by [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes). + +**Mitigation technique 2: unsafely disable deferred foreign key checks** + +You can ask the migrator to never run `PRAGMA foreign_key_check` for all newly registered migrations: + +```swift +migrator = migrator.unsafeWithoutDeferredForeignKeyChecks() +migrator.registerMigration("unchecked") { db in ... } +``` + +1. Disable foreign keys +2. Start a transaction +3. Apply migration +4. Commit +5. Reenable foreign keys + +You keep the ability to run any kind of migration. But the migrator can no longer guarantees that foreign key constraints are honored :warning: + +Individual migrations can still immediately check their foreign keys (as long as they do not require the technique described by [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes)): + +```swift +migrator = migrator.unsafeWithoutDeferredForeignKeyChecks() +migrator.registerMigration("unchecked") { db in ... } +migrator.registerMigration("checked", foreignKeyChecks: .immediate) { db in ... } +``` + +Since such a migrator does not guarantee that foreign key constraints are honored, you may want to check them at some point, with [`PRAGMA foreign_key_check`](https://www.sqlite.org/pragma.html#pragma_foreign_key_check): + +```swift +try migrator.migrate(dbQueue) +let foreignKeyViolationExists = try dbQueue.read { db + try Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty() == false +} +if foreignKeyViolationExists { + // Well, too bad +} +``` + + ## Asynchronous Migrations `DatabaseMigrator` provides two ways to migrate a database in an asynchronous way. @@ -142,3 +221,11 @@ let publisher = migrator.migratePublisher(dbQueue) ``` This publisher completes on the main queue, unless you provide a specific [scheduler](https://developer.apple.com/documentation/combine/scheduler) to the `receiveOn` argument. + + + +[Migrations Overview]: #migrations-overview +[The `eraseDatabaseOnSchemaChange` Option]: #the-erasedatabaseonschemachange-option +[Advanced Database Schema Changes]: #advanced-database-schema-changes +[Foreign Key Checks]: #foreign-key-checks +[Asynchronous Migrations]: #asynchronous-migrations From 6193c6aa00f6174ae9b0e404d5cbcf5059ea3c29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 4 Nov 2021 14:19:11 +0100 Subject: [PATCH 03/11] foreignKeyViolations() and checkForeignKeyViolations() --- GRDB/Core/Database+Schema.swift | 132 +++++++++++++++- GRDB/Migration/Migration.swift | 18 +-- Tests/GRDBTests/DatabaseMigratorTests.swift | 24 +-- Tests/GRDBTests/ForeignKeyInfoTests.swift | 166 +++++++++++++++++++- 4 files changed, 298 insertions(+), 42 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 97dbaa94a..55adb1589 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -175,7 +175,7 @@ extension Database { .contains { $0.lowercased() == name } } - /// The primary key for table named `tableName`, in the main or temp schema. + /// The primary key for table named `tableName`. /// /// All tables have a primary key, even when it is not explicit. When a /// table has no explicit primary key, the result is the hidden @@ -304,7 +304,7 @@ extension Database { } } - /// The indexes on table named `tableName`, in the main or temp schema. + /// The indexes on table named `tableName`. /// /// Only indexes on columns are returned. Indexes on expressions are /// not returned. @@ -385,7 +385,7 @@ extension Database { try columnsForUniqueKey(Array(columns), in: tableName) != nil } - /// The foreign keys defined on table named `tableName`, in the main or temp schema. + /// The foreign keys defined on table named `tableName`. /// /// - throws: A DatabaseError if table does not exist. public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] { @@ -404,6 +404,7 @@ extension Database { } var rawForeignKeys: [( + id: Int, destinationTable: String, mapping: [(origin: String, destination: String?, seq: Int)])] = [] var previousId: Int? = nil @@ -424,7 +425,7 @@ extension Database { .append((origin: origin, destination: destination, seq: seq)) } else { let mapping = [(origin: origin, destination: destination, seq: seq)] - rawForeignKeys.append((destinationTable: table, mapping: mapping)) + rawForeignKeys.append((id: id, destinationTable: table, mapping: mapping)) previousId = id } } @@ -438,7 +439,7 @@ extension Database { } } - let foreignKeys = try rawForeignKeys.map { (destinationTable, columnMapping) -> ForeignKeyInfo in + let foreignKeys = try rawForeignKeys.map { (id, destinationTable, columnMapping) -> ForeignKeyInfo in let orderedMapping = columnMapping .sorted { $0.seq < $1.seq } .map { (origin: $0.origin, destination: $0 .destination) } @@ -454,13 +455,59 @@ extension Database { (origin: origin, destination: destination!) } } - return ForeignKeyInfo(destinationTable: destinationTable, mapping: completeMapping) + return ForeignKeyInfo(id: id, destinationTable: destinationTable, mapping: completeMapping) } schemaCache[table.schemaID].set(foreignKeys: .value(foreignKeys), forTable: table.name) return foreignKeys } + /// Returns a cursor over foreign key violations in the database. + public func foreignKeyViolations() throws -> RecordCursor { + try ForeignKeyViolation.fetchCursor(self, sql: "PRAGMA foreign_key_check") + } + + /// Returns a cursor over foreign key violations in the table. + public func foreignKeyViolations(in tableName: String) throws -> RecordCursor { + for schemaIdentifier in try schemaIdentifiers() { + if try exists(type: .table, name: tableName, in: schemaIdentifier) { + return try foreignKeyViolations(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) + } + } + throw DatabaseError.noSuchTable(tableName) + } + + /// Throws a DatabaseError of extended code `SQLITE_CONSTRAINT_FOREIGNKEY` + /// if there exists a foreign key violation in the database. + public func checkForeignKeyViolations() throws { + try checkForeignKeyViolations(from: foreignKeyViolations()) + } + + /// Throws a DatabaseError of extended code `SQLITE_CONSTRAINT_FOREIGNKEY` + /// if there exists a foreign key violation in the table. + public func checkForeignKeyViolations(in tableName: String) throws { + try checkForeignKeyViolations(from: foreignKeyViolations(in: tableName)) + } + + private func foreignKeyViolations(in table: TableIdentifier) throws -> RecordCursor { + try ForeignKeyViolation.fetchCursor(self, sql: """ + PRAGMA \(table.schemaID.sql).foreign_key_check(\(table.name.quotedDatabaseIdentifier)) + """) + } + + private func checkForeignKeyViolations(from violations: RecordCursor) throws { + guard let violation = try violations.next() else { + return + } + + // Grab detailed information, if possible, for better error message. + // If detailed information is not available, fallback to plain description. + let message = (try? violation.failureDescription(self)) ?? String(describing: violation) + throw DatabaseError( + resultCode: .SQLITE_CONSTRAINT_FOREIGNKEY, + message: message) + } + /// Returns the actual name of the database table, in the main or temp /// schema, or nil if the table does not exist. /// @@ -486,7 +533,7 @@ extension Database { extension Database { - /// The columns in the table named `tableName`, in the main or temp schema. + /// The columns in the table named `tableName`. /// /// - throws: A DatabaseError if table does not exist. public func columns(in tableName: String) throws -> [ColumnInfo] { @@ -725,6 +772,74 @@ public struct IndexInfo { } } +/// A foreign key violation produced by PRAGMA foreign_key_check +/// +/// See +public struct ForeignKeyViolation: FetchableRecord, CustomStringConvertible { + /// The name of the table that contains the `REFERENCES` clause + var originTable: String + + /// The rowid of the row that contains the invalid `REFERENCES` clause, or + /// nil if the origin table is a `WITHOUT ROWID` table. + var originRowID: Int64? + + /// The name of the table that is referred to. + var destinationTable: String + + /// The id of the specific foreign key constraint that failed. This id + /// matches `ForeignKeyInfo.id`. See `Database.foreignKeys(on:)` for more + /// information. + var foreignKeyId: Int + + public init(row: Row) { + originTable = row[0] + originRowID = row[1] + destinationTable = row[2] + foreignKeyId = row[3] + } + + public var description: String { + if let originRowID = originRowID { + return "Foreign key violation from \(originTable) to \(destinationTable), in rowid \(originRowID)" + } else { + return "Foreign key violation from \(originTable) to \(destinationTable)" + } + } + + /// Returns a precise description of the foreign key violation. + /// + /// For example: 'foreign key constraint failed from player(teamId) to team(id), + /// in [id:1 teamId:2 name:"O'Brien" score: 1000]' + public func failureDescription(_ db: Database) throws -> String { + // Grab detailed information, if possible, for better error message + let originRow = try originRowID.flatMap { rowid in + try Row.fetchOne(db, sql: "SELECT * FROM \(originTable) WHERE rowid = \(rowid)") + } + let foreignKey = try db.foreignKeys(on: originTable).first(where: { foreignKey in + foreignKey.id == foreignKeyId + }) + + var description: String + if let foreignKey = foreignKey { + description = """ + foreign key constraint failed \ + from \(originTable)(\(foreignKey.originColumns.joined(separator: ", "))) \ + to \(destinationTable)(\(foreignKey.destinationColumns.joined(separator: ", "))) + """ + } else { + description = "foreign key constraint failed from \(originTable) to \(destinationTable)" + } + + if let originRow = originRow { + description += ", in \(String(describing: originRow))" + } else if let originRowID = originRowID { + description += ", in rowid \(originRowID)" + } + + return description + } +} + /// Primary keys are returned from the Database.primaryKey(_:) method. /// /// When the table's primary key is the rowid: @@ -861,6 +976,9 @@ public struct PrimaryKeyInfo { /// You get foreign keys from table names, with the /// `foreignKeys(on:)` method. public struct ForeignKeyInfo { + /// The first column in the output of the `foreign_key_list` pragma + public var id: Int + /// The name of the destination table public let destinationTable: String diff --git a/GRDB/Migration/Migration.swift b/GRDB/Migration/Migration.swift index e6069f446..789da9c46 100644 --- a/GRDB/Migration/Migration.swift +++ b/GRDB/Migration/Migration.swift @@ -67,23 +67,7 @@ struct Migration { // > then run PRAGMA foreign_key_check to verify that the // > schema change did not break any foreign // > key constraints. - if try db - .makeStatement(sql: "PRAGMA foreign_key_check") - .makeCursor() - .isEmpty() == false - { - // https://www.sqlite.org/pragma.html#pragma_foreign_key_check - // - // PRAGMA foreign_key_check does not return an error, - // but the list of violated foreign key constraints. - // - // Let's turn any violation into an - // SQLITE_CONSTRAINT_FOREIGNKEY error, and rollback - // the transaction. - throw DatabaseError( - resultCode: .SQLITE_CONSTRAINT_FOREIGNKEY, - message: "FOREIGN KEY constraint failed") - } + try db.checkForeignKeyViolations() // > 11. Commit the transaction started in step 2. return .commit diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 919e463d7..7e9befa09 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -398,9 +398,9 @@ class DatabaseMigratorTests : GRDBTestCase { // The first migration should be committed. // The second migration should be rollbacked. - XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) - XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version + XCTAssertEqual(error.message, #"foreign key constraint failed from pets(masterId) to persons(id), in [masterId:123 name:"Bobby"]"#) let names = try dbQueue.inDatabase { db in try String.fetchAll(db, sql: "SELECT name FROM persons") @@ -418,9 +418,9 @@ class DatabaseMigratorTests : GRDBTestCase { // The second migration should be rollbacked. let error = error as! DatabaseError - XCTAssert(error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) - XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version + XCTAssertEqual(error.message, #"foreign key constraint failed from pets(masterId) to persons(id), in [masterId:123 name:"Bobby"]"#) let names = try! String.fetchAll(db, sql: "SELECT name FROM persons") XCTAssertEqual(names, ["Arthur"]) @@ -461,9 +461,9 @@ class DatabaseMigratorTests : GRDBTestCase { // Migration 1 and 2 should be committed. // Migration 3 should not be committed. - XCTAssert((error.resultCode == error.extendedResultCode) || error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) - XCTAssertEqual(error.message!.lowercased(), "foreign key constraint failed") // lowercased: accept multiple SQLite version + XCTAssertEqual(error.message, #"foreign key constraint failed from pets(masterId) to persons(id), in [masterId:123 name:"Bobby"]"#) try dbQueue.inDatabase { db in // Arthur inserted (migration 1), Barbara (migration 3) not inserted. @@ -872,7 +872,7 @@ class DatabaseMigratorTests : GRDBTestCase { do { try migrator.migrate(dbQueue) XCTFail("Expected error") - } catch DatabaseError.SQLITE_CONSTRAINT { } + } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } try dbQueue.read { db in try XCTAssertTrue(Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty()) } @@ -886,7 +886,7 @@ class DatabaseMigratorTests : GRDBTestCase { do { try migrator.migrate(dbQueue) XCTFail("Expected error") - } catch DatabaseError.SQLITE_CONSTRAINT { } + } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } try dbQueue.read { db in try XCTAssertTrue(Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty()) } @@ -913,7 +913,7 @@ class DatabaseMigratorTests : GRDBTestCase { do { try migrator.migrate(dbQueue) XCTFail("Expected error") - } catch DatabaseError.SQLITE_CONSTRAINT { } + } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } try dbQueue.read { db in try XCTAssertTrue(Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty()) } @@ -955,7 +955,7 @@ class DatabaseMigratorTests : GRDBTestCase { do { try migrator.migrate(dbQueue) XCTFail("Expected error") - } catch DatabaseError.SQLITE_CONSTRAINT { } + } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } try dbQueue.read { db in try XCTAssertTrue(Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty()) } @@ -982,7 +982,7 @@ class DatabaseMigratorTests : GRDBTestCase { do { try migrator.migrate(dbQueue) XCTFail("Expected error") - } catch DatabaseError.SQLITE_CONSTRAINT { } + } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } try dbQueue.read { db in try XCTAssertTrue(Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty()) } @@ -1008,6 +1008,6 @@ class DatabaseMigratorTests : GRDBTestCase { do { try migrator.migrate(dbQueue) XCTFail("Expected error") - } catch DatabaseError.SQLITE_CONSTRAINT { } + } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } } } diff --git a/Tests/GRDBTests/ForeignKeyInfoTests.swift b/Tests/GRDBTests/ForeignKeyInfoTests.swift index 707cff6f3..dee225f6d 100644 --- a/Tests/GRDBTests/ForeignKeyInfoTests.swift +++ b/Tests/GRDBTests/ForeignKeyInfoTests.swift @@ -54,27 +54,181 @@ class ForeignKeyInfoTests: GRDBTestCase { do { let foreignKeys = try db.foreignKeys(on: "children1") XCTAssertEqual(foreignKeys.count, 1) - assertEqual(foreignKeys[0], ForeignKeyInfo(destinationTable: "parents1", mapping: [(origin: "parentId", destination: "id")])) + assertEqual(foreignKeys[0], ForeignKeyInfo(id: foreignKeys[0].id, destinationTable: "parents1", mapping: [(origin: "parentId", destination: "id")])) } do { let foreignKeys = try db.foreignKeys(on: "children2") XCTAssertEqual(foreignKeys.count, 2) - assertEqual(foreignKeys[0], ForeignKeyInfo(destinationTable: "parents1", mapping: [(origin: "parentId2", destination: "id")])) - assertEqual(foreignKeys[1], ForeignKeyInfo(destinationTable: "parents1", mapping: [(origin: "parentId1", destination: "id")])) + assertEqual(foreignKeys[0], ForeignKeyInfo(id: foreignKeys[0].id, destinationTable: "parents1", mapping: [(origin: "parentId2", destination: "id")])) + assertEqual(foreignKeys[1], ForeignKeyInfo(id: foreignKeys[1].id, destinationTable: "parents1", mapping: [(origin: "parentId1", destination: "id")])) } do { let foreignKeys = try db.foreignKeys(on: "children3") XCTAssertEqual(foreignKeys.count, 1) - assertEqual(foreignKeys[0], ForeignKeyInfo(destinationTable: "parents2", mapping: [(origin: "parentA", destination: "a"), (origin: "parentB", destination: "b")])) + assertEqual(foreignKeys[0], ForeignKeyInfo(id: foreignKeys[0].id, destinationTable: "parents2", mapping: [(origin: "parentA", destination: "a"), (origin: "parentB", destination: "b")])) } do { let foreignKeys = try db.foreignKeys(on: "children4") XCTAssertEqual(foreignKeys.count, 2) - assertEqual(foreignKeys[0], ForeignKeyInfo(destinationTable: "parents2", mapping: [(origin: "parentA2", destination: "b"), (origin: "parentB2", destination: "a")])) - assertEqual(foreignKeys[1], ForeignKeyInfo(destinationTable: "parents2", mapping: [(origin: "parentA1", destination: "a"), (origin: "parentB1", destination: "b")])) + assertEqual(foreignKeys[0], ForeignKeyInfo(id: foreignKeys[0].id, destinationTable: "parents2", mapping: [(origin: "parentA2", destination: "b"), (origin: "parentB2", destination: "a")])) + assertEqual(foreignKeys[1], ForeignKeyInfo(id: foreignKeys[1].id, destinationTable: "parents2", mapping: [(origin: "parentA1", destination: "a"), (origin: "parentB1", destination: "b")])) + } + } + } + + func testForeignKeyViolations() throws { + try makeDatabaseQueue().writeWithoutTransaction { db in + try db.execute(sql: """ + CREATE TABLE parent(id TEXT NOT NULL PRIMARY KEY); + CREATE TABLE child1(id INTEGER NOT NULL PRIMARY KEY, parentId TEXT REFERENCES parent(id)); + CREATE TABLE child2(id INTEGER NOT NULL PRIMARY KEY, parentId TEXT REFERENCES parent(id)); + PRAGMA foreign_keys = OFF; + INSERT INTO child1 (id, parentId) VALUES (13, '1'); + INSERT INTO child1 (id, parentId) VALUES (42, '2'); + INSERT INTO child2 (id, parentId) VALUES (17, '3'); + """) + + let violations = try Array(db.foreignKeyViolations()) + XCTAssertEqual(violations.count, 3) + + if let violation = violations.first(where: { $0.originTable == "child1" && $0.originRowID == 13 }) { + XCTAssertEqual(violation.destinationTable, "parent") + } else { + XCTFail("Missing violation") + } + + if let violation = violations.first(where: { $0.originTable == "child1" && $0.originRowID == 42 }) { + XCTAssertEqual(violation.destinationTable, "parent") + } else { + XCTFail("Missing violation") + } + + if let violation = violations.first(where: { $0.originTable == "child2" && $0.originRowID == 17 }) { + XCTAssertEqual(violation.destinationTable, "parent") + } else { + XCTFail("Missing violation") + } + } + } + + func testForeignKeyViolationsInTable() throws { + try makeDatabaseQueue().writeWithoutTransaction { db in + try db.execute(sql: """ + CREATE TABLE parent(id TEXT NOT NULL PRIMARY KEY); + CREATE TABLE child1(id INTEGER NOT NULL PRIMARY KEY, parentId TEXT REFERENCES parent(id)); + CREATE TABLE child2(id INTEGER NOT NULL PRIMARY KEY, parentId TEXT REFERENCES parent(id)); + PRAGMA foreign_keys = OFF; + INSERT INTO child1 (id, parentId) VALUES (13, '1'); + INSERT INTO child1 (id, parentId) VALUES (42, '2'); + INSERT INTO child2 (id, parentId) VALUES (17, '3'); + """) + + do { + let violations = try Array(db.foreignKeyViolations(in: "child1")) + XCTAssertEqual(violations.count, 2) + + if let violation = violations.first(where: { $0.originRowID == 13 }) { + XCTAssertEqual(violation.originTable, "child1") + XCTAssertEqual(violation.destinationTable, "parent") + } else { + XCTFail("Missing violation") + } + + if let violation = violations.first(where: { $0.originRowID == 42 }) { + XCTAssertEqual(violation.originTable, "child1") + XCTAssertEqual(violation.destinationTable, "parent") + } else { + XCTFail("Missing violation") + } + } + + do { + let violations = try Array(db.foreignKeyViolations(in: "child2")) + XCTAssertEqual(violations.count, 1) + + if let violation = violations.first(where: { $0.originRowID == 17 }) { + XCTAssertEqual(violation.originTable, "child2") + XCTAssertEqual(violation.destinationTable, "parent") + } else { + XCTFail("Missing violation") + } + } + + // Case insensitivity + do { + let violations = try Array(db.foreignKeyViolations(in: "cHiLd2")) + XCTAssertEqual(violations.count, 1) + + if let violation = violations.first(where: { $0.originRowID == 17 }) { + XCTAssertEqual(violation.originTable, "child2") + XCTAssertEqual(violation.destinationTable, "parent") + } else { + XCTFail("Missing violation") + } + } + + // Missing table + do { + _ = try db.foreignKeyViolations(in: "missing") + } catch DatabaseError.SQLITE_ERROR { } + } + } + + func testCheckForeignKeyViolations() throws { + try makeDatabaseQueue().writeWithoutTransaction { db in + try db.execute(sql: """ + CREATE TABLE parent(id TEXT NOT NULL PRIMARY KEY); + CREATE TABLE child(id INTEGER NOT NULL PRIMARY KEY, parentId TEXT REFERENCES parent(id)); + PRAGMA foreign_keys = OFF; + INSERT INTO child (id, parentId) VALUES (13, '1'); + """) + + do { + try db.checkForeignKeyViolations() + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) + XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssertEqual(error.message, #"foreign key constraint failed from child(parentId) to parent(id), in [id:13 parentId:"1"]"#) + XCTAssertEqual(error.description, #"SQLite error 19: foreign key constraint failed from child(parentId) to parent(id), in [id:13 parentId:"1"]"#) + } + } + + try makeDatabaseQueue().writeWithoutTransaction { db in + try db.execute(sql: """ + CREATE TABLE parent(a TEXT NOT NULL, b TEXT NOT NULL, PRIMARY KEY (a, b)); + CREATE TABLE child(id INTEGER NOT NULL PRIMARY KEY, parentA, parentB, FOREIGN KEY (parentA, parentB) REFERENCES parent(a, b)); + PRAGMA foreign_keys = OFF; + INSERT INTO child (id, parentA, parentB) VALUES (13, 'foo', 'bar'); + """) + + do { + try db.checkForeignKeyViolations() + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) + XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssertEqual(error.message, #"foreign key constraint failed from child(parentA, parentB) to parent(a, b), in [id:13 parentA:"foo" parentB:"bar"]"#) + XCTAssertEqual(error.description, #"SQLite error 19: foreign key constraint failed from child(parentA, parentB) to parent(a, b), in [id:13 parentA:"foo" parentB:"bar"]"#) + } + } + + try makeDatabaseQueue().writeWithoutTransaction { db in + try db.execute(sql: """ + CREATE TABLE parent(a TEXT NOT NULL, b TEXT NOT NULL, PRIMARY KEY (a, b)); + CREATE TABLE child(id INTEGER NOT NULL PRIMARY KEY, parentA, parentB, FOREIGN KEY (parentA, parentB) REFERENCES parent(a, b)) WITHOUT ROWID; + PRAGMA foreign_keys = OFF; + INSERT INTO child (id, parentA, parentB) VALUES (13, 'foo', 'bar'); + """) + + do { + try db.checkForeignKeyViolations() + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) + XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) + XCTAssertEqual(error.message, "foreign key constraint failed from child(parentA, parentB) to parent(a, b)") + XCTAssertEqual(error.description, "SQLite error 19: foreign key constraint failed from child(parentA, parentB) to parent(a, b)") } } } From d0997efbb683a291fd27906287be1f962f5a3e1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 4 Nov 2021 14:19:15 +0100 Subject: [PATCH 04/11] Documentation --- Documentation/Migrations.md | 177 ++++++++++++++++++++++++------------ 1 file changed, 117 insertions(+), 60 deletions(-) diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index 094ad1d73..f3ee41b39 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -111,9 +111,7 @@ The `eraseDatabaseOnSchemaChange` option triggers a recreation of the database i ## Advanced Database Schema Changes -SQLite does not support many schema changes, and won't let you drop a table column with "ALTER TABLE ... DROP COLUMN ...", for example. - -Yet any kind of schema change is still possible, by recreating tables: +If SQLite does not directly support all kinds of schema alterations, you can make arbitrary changes to the schema design of any table using a sequence of operations, as in the example below: ```swift migrator.registerMigration("AddNotNullCheckOnName") { db in @@ -128,75 +126,134 @@ migrator.registerMigration("AddNotNullCheckOnName") { db in } ``` -Please check [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes) in the SQLite documentation for further information. +This technique is described in SQLite documentation: [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes). + +The detailed sequence of operations is described below, some of them are performed by GRDB, and others by your code: + +1. GRDB: If foreign key constraints are enabled, disable them using PRAGMA foreign_keys=OFF. + +2. GRDB: Start a transaction. + +3. **Your code**: Remember the format of all indexes, triggers, and views associated with table X. This information will be needed in step 8 below. One way to do this is to run a query like the following: `SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'`. + +4. **Your code**: Use `CREATE TABLE` to construct a new table "new_X" that is in the desired revised format of table X. Make sure that the name "new_X" does not collide with any existing table name, of course. + +5. **Your code**: Transfer content from X into new_X using a statement like: `INSERT INTO new_X SELECT ... FROM X`. + +6. **Your code**: Drop the old table X: `DROP TABLE X`. + +7. **Your code**: Change the name of new_X to X using: `ALTER TABLE new_X RENAME TO X`. + +8. **Your code**: Use `CREATE INDEX`, `CREATE TRIGGER`, and `CREATE VIEW` to reconstruct indexes, triggers, and views associated with table X. Perhaps use the old format of the triggers, indexes, and views saved from step 3 above as a guide, making changes as appropriate for the alteration. + +9. **Your code**: If any views refer to table X in a way that is affected by the schema change, then drop those views using `DROP VIEW` and recreate them with whatever changes are necessary to accommodate the schema change using `CREATE VIEW`. + +10. GRDB: If foreign key constraints were originally enabled then run [`PRAGMA foreign_key_check`](https://www.sqlite.org/pragma.html#pragma_foreign_key_check) to verify that the schema change did not break any foreign key constraints. + +11. GRDB: Commit the transaction started in step 2. + +12. GRDB: If foreign keys constraints were originally enabled, reenable them now. + +> :point_up: **Note**: Take care to follow the procedure above precisely, in the same order, or you might corrupt triggers, views, and foreign key constraints. Have a second look at [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes) if necessary. +> +> :point_up: **Note**: By default, all migrations perform, at step 10, a full check of all foreign keys in your database. When your database is big, those checks may have a noticeable impact on migration performances. See [Foreign Key Checks] for a discussion of your ways to avoid this toll. ## Foreign Key Checks -You'll need to read this chapter if your migrations spend a lot of time performing foreign key checks, and you are looking for a mitigation. +SQLite makes it [difficult](https://www.sqlite.org/lang_altertable.html) to perform some schema changes, and this creates very undesired churn w.r.t. foreign keys. GRDB makes its best to hide those problems to you, but you might have to deal with them one day, especially if your database becomes *very big*: -What are we talking about? SQLite has [limited support](https://www.sqlite.org/lang_altertable.html) for database schema change, and this unfortunately creates unwanted churn regarding foreign keys. In order to accept any kind of schema changes, GRDB migration runs, by default, with deferred foreign key checks. They precisely apply the technique described in [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes): +You'll need to read this chapter if you are looking for a mitigation to the time spent by migrations performing foreign key checks. You'll know this by instrumenting your migrations, and looking for the time spent in the `checkForeignKeyViolations` method. See [Advanced Database Schema Changes] right above to know what are those foreign key checks. -1. Disable foreign keys -2. Start a transaction -3. Apply migration -4. Run [`PRAGMA foreign_key_check`](https://www.sqlite.org/pragma.html#pragma_foreign_key_check) to verify that the schema change did not break any foreign key constraints. -5. Commit -6. Reenable foreign keys +**Your first mitigation technique are immediate foreign key checks.** -The step 4 can take a long time. - -**Mitigation technique 1: immediate foreign key checks** - -If you register a migration with `.immediate` foreign key checks, the migration will not disable foreign keys, and avoid the slow `PRAGMA foreign_key_check`: +If you register a migration with `.immediate` foreign key checks, the migration will not disable foreign keys, and won't need to perform the full check of all foreign keys in your database: ```swift -migrator.registerMigration("slow", foreignKeyChecks: .immediate) { db in ... } -``` - -1. Start a transaction -2. Apply migration -3. Commit - -Such a migration still guarantees that no foreign key constraint is broken. But it can not run the kind of migrations covered by [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes). - -**Mitigation technique 2: unsafely disable deferred foreign key checks** - -You can ask the migrator to never run `PRAGMA foreign_key_check` for all newly registered migrations: - -```swift -migrator = migrator.unsafeWithoutDeferredForeignKeyChecks() -migrator.registerMigration("unchecked") { db in ... } -``` - -1. Disable foreign keys -2. Start a transaction -3. Apply migration -4. Commit -5. Reenable foreign keys - -You keep the ability to run any kind of migration. But the migrator can no longer guarantees that foreign key constraints are honored :warning: - -Individual migrations can still immediately check their foreign keys (as long as they do not require the technique described by [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes)): - -```swift -migrator = migrator.unsafeWithoutDeferredForeignKeyChecks() -migrator.registerMigration("unchecked") { db in ... } -migrator.registerMigration("checked", foreignKeyChecks: .immediate) { db in ... } -``` - -Since such a migrator does not guarantee that foreign key constraints are honored, you may want to check them at some point, with [`PRAGMA foreign_key_check`](https://www.sqlite.org/pragma.html#pragma_foreign_key_check): - -```swift -try migrator.migrate(dbQueue) -let foreignKeyViolationExists = try dbQueue.read { db - try Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty() == false -} -if foreignKeyViolationExists { - // Well, too bad +migrator.registerMigration("make it faster please", foreignKeyChecks: .immediate) { db in + try db.create(table: ...) // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ... } ``` +Such a migration is much faster, and it still guarantees that no foreign key constraint is broken. But it can not run the kind of migrations covered by [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes). In this case, you'll need to use the second mitigation technique: + +**Your second mitigation technique is to disable deferred foreign key checks.** + +You can ask the migrator to stop performing foreign key checks for all newly registered migrations. + +:warning: If you use this technique, your app becomes responsible for preventing foreign key violations from being committed to disk! + +```swift +migrator = migrator.unsafeWithoutDeferredForeignKeyChecks() + +// From now on, migrations are unchecked! +migrator.registerMigration("fast but unchecked") { db in ... } +``` + +In order to prevent foreign key violations from being committed to disk, you can: + +- Run migrations with immediate foreign key check, as long as they do not require the technique described by [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes): + + ```swift + migrator = migrator.unsafeWithoutDeferredForeignKeyChecks() + migrator.registerMigration("unchecked") { db in ... } + migrator.registerMigration("checked", foreignKeyChecks: .immediate) { db in ... } + ``` + +- Perform foreign key checks on some tables only: + + ```swift + migrator = migrator.unsafeWithoutDeferredForeignKeyChecks() + migrator.registerMigration("partially checked") { db in + ... + + // Throws an error and stops migrations if there exists a + // foreign key violation in the 'player' table. + try db.checkForeignKeyViolations(in: "player") + } + ``` + +- Perform a full check of foreign keys, eventually: + + ```swift + try migrator.migrate(dbQueue) + + // Throws an error if there exists any foreign key violation. + try dbQueue.read { db in + try db.checkForeignKeyViolations() + } + ``` + +In order to check for foreign key violations, the `checkForeignKeyViolations()` and `checkForeignKeyViolations(in:)` methods are recommended over the raw use of the [`PRAGMA foreign_key_check`](https://www.sqlite.org/pragma.html#pragma_foreign_key_check). Those methods throw a nicely detailed DatabaseError that contains a lot of debugging information: + +```swift +// SQLite error 19: foreign key constraint failed from player(teamId) to team(id), +// in [id:1 teamId:2 name:"O'Brien" score: 1000] +try db.checkForeignKeyViolations() +``` + +If you want to precisely introspect each foreign key violation, you will use instead: + +```swift +let violations = try db.foreignKeyViolations() +while let violation = try violations.next() { + // The name of the table that contains the `REFERENCES` clause + print(violation.originTable) + + // The rowid of the row that contains the invalid `REFERENCES` clause, or + // nil if the origin table is a `WITHOUT ROWID` table. + print(violation.originRowID) + + // The name of the table that is referred to. + print(violation.destinationTable) + + // The id of the specific foreign key constraint that failed. This id + // matches `ForeignKeyInfo.id`. See `Database.foreignKeys(on:)` for more + // information. + print(violation.foreignKeyId) +} +``` ## Asynchronous Migrations From 63ba4fb294543521fdccca2cb3021356d2c92679 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 4 Nov 2021 15:10:33 +0100 Subject: [PATCH 05/11] Rename unsafeWithoutDeferredForeignKeyChecks to disablingDeferredForeignKeyChecks --- Documentation/Migrations.md | 6 +++--- GRDB/Migration/DatabaseMigrator.swift | 8 ++++---- Tests/GRDBTests/DatabaseMigratorTests.swift | 14 +++++++------- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index f3ee41b39..dc04387ad 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -185,7 +185,7 @@ You can ask the migrator to stop performing foreign key checks for all newly reg :warning: If you use this technique, your app becomes responsible for preventing foreign key violations from being committed to disk! ```swift -migrator = migrator.unsafeWithoutDeferredForeignKeyChecks() +migrator = migrator.disablingDeferredForeignKeyChecks() // From now on, migrations are unchecked! migrator.registerMigration("fast but unchecked") { db in ... } @@ -196,7 +196,7 @@ In order to prevent foreign key violations from being committed to disk, you can - Run migrations with immediate foreign key check, as long as they do not require the technique described by [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes): ```swift - migrator = migrator.unsafeWithoutDeferredForeignKeyChecks() + migrator = migrator.disablingDeferredForeignKeyChecks() migrator.registerMigration("unchecked") { db in ... } migrator.registerMigration("checked", foreignKeyChecks: .immediate) { db in ... } ``` @@ -204,7 +204,7 @@ In order to prevent foreign key violations from being committed to disk, you can - Perform foreign key checks on some tables only: ```swift - migrator = migrator.unsafeWithoutDeferredForeignKeyChecks() + migrator = migrator.disablingDeferredForeignKeyChecks() migrator.registerMigration("partially checked") { db in ... diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 6c967e4c7..52f55892d 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -53,7 +53,7 @@ public struct DatabaseMigrator { /// are checked right before changes are committed on disk. /// /// These deferred checks are not executed if the migrator comes - /// from `unsafeWithoutDeferredForeignKeyChecks()`. + /// from `disablingDeferredForeignKeyChecks()`. /// /// Deferred foreign key checks are necessary for migrations that /// perform schema changes as described in @@ -122,7 +122,7 @@ public struct DatabaseMigrator { /// // Runs with immediate foreign key checks /// } /// - /// migrator = migrator.unsafeWithoutDeferredForeignKeyChecks() + /// migrator = migrator.disablingDeferredForeignKeyChecks() /// migrator.registerMigration("C") { db in /// // Runs with disabled foreign key checks /// } @@ -133,7 +133,7 @@ public struct DatabaseMigrator { /// - warning: Before using this unsafe method, try to run your migrations with /// `.immediate` foreign key checks, if possible. This may enhance migration /// performances, while preserving the database integrity guarantee. - public func unsafeWithoutDeferredForeignKeyChecks() -> DatabaseMigrator { + public func disablingDeferredForeignKeyChecks() -> DatabaseMigrator { with { $0.defersForeignKeyChecks = false } } @@ -158,7 +158,7 @@ public struct DatabaseMigrator { /// disabled foreign keys, until foreign keys are checked right before /// changes are committed on disk. These deferred checks are not /// executed if the migrator comes - /// from `unsafeWithoutDeferredForeignKeyChecks()`. + /// from `disablingDeferredForeignKeyChecks()`. /// /// The `.immediate` checks have the migration run with foreign /// keys enabled. diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 7e9befa09..cdae329fc 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -920,7 +920,7 @@ class DatabaseMigratorTests : GRDBTestCase { } } - func testUnsafeWithoutDeferredForeignKeyChecks() throws { + func testDisablingDeferredForeignKeyChecks() throws { let foreignKeyViolation = """ CREATE TABLE parent(id INTEGER NOT NULL PRIMARY KEY); CREATE TABLE child(parentId INTEGER REFERENCES parent(id)); @@ -935,7 +935,7 @@ class DatabaseMigratorTests : GRDBTestCase { // Foreign key violation do { - var migrator = DatabaseMigrator().unsafeWithoutDeferredForeignKeyChecks() + var migrator = DatabaseMigrator().disablingDeferredForeignKeyChecks() migrator.registerMigration("A") { db in try db.execute(sql: foreignKeyViolation) } @@ -947,7 +947,7 @@ class DatabaseMigratorTests : GRDBTestCase { } } do { - var migrator = DatabaseMigrator().unsafeWithoutDeferredForeignKeyChecks() + var migrator = DatabaseMigrator().disablingDeferredForeignKeyChecks() migrator.registerMigration("A", foreignKeyChecks: .immediate) { db in try db.execute(sql: foreignKeyViolation) } @@ -963,7 +963,7 @@ class DatabaseMigratorTests : GRDBTestCase { // Transient foreign key violation do { - var migrator = DatabaseMigrator().unsafeWithoutDeferredForeignKeyChecks() + var migrator = DatabaseMigrator().disablingDeferredForeignKeyChecks() migrator.registerMigration("A") { db in try db.execute(sql: transientForeignKeyViolation) } @@ -974,7 +974,7 @@ class DatabaseMigratorTests : GRDBTestCase { } } do { - var migrator = DatabaseMigrator().unsafeWithoutDeferredForeignKeyChecks() + var migrator = DatabaseMigrator().disablingDeferredForeignKeyChecks() migrator.registerMigration("A", foreignKeyChecks: .immediate) { db in try db.execute(sql: transientForeignKeyViolation) } @@ -989,7 +989,7 @@ class DatabaseMigratorTests : GRDBTestCase { } } - func testUnsafeWithoutDeferredForeignKeyChecks_applies_to_newly_registered_migrations() throws { + func test_disablingDeferredForeignKeyChecks_applies_to_newly_registered_migrations_only() throws { let foreignKeyViolation = """ CREATE TABLE parent(id INTEGER NOT NULL PRIMARY KEY); CREATE TABLE child(parentId INTEGER REFERENCES parent(id)); @@ -1000,7 +1000,7 @@ class DatabaseMigratorTests : GRDBTestCase { migrator.registerMigration("A") { db in try db.execute(sql: foreignKeyViolation) } - migrator = migrator.unsafeWithoutDeferredForeignKeyChecks() + migrator = migrator.disablingDeferredForeignKeyChecks() migrator.registerMigration("B") { db in XCTFail("Should not run") } From 8a36f4d94e3841a72001bf7c53b712fde4b20b3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 4 Nov 2021 15:10:41 +0100 Subject: [PATCH 06/11] Clean up tests --- Tests/GRDBTests/DatabaseMigratorTests.swift | 37 +++++++-------------- 1 file changed, 12 insertions(+), 25 deletions(-) diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index cdae329fc..9263ae75e 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -873,9 +873,7 @@ class DatabaseMigratorTests : GRDBTestCase { try migrator.migrate(dbQueue) XCTFail("Expected error") } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } - try dbQueue.read { db in - try XCTAssertTrue(Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty()) - } + try dbQueue.read { try $0.checkForeignKeyViolations() } } do { var migrator = DatabaseMigrator() @@ -887,9 +885,7 @@ class DatabaseMigratorTests : GRDBTestCase { try migrator.migrate(dbQueue) XCTFail("Expected error") } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } - try dbQueue.read { db in - try XCTAssertTrue(Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty()) - } + try dbQueue.read { try $0.checkForeignKeyViolations() } } // Transient foreign key violation @@ -900,9 +896,7 @@ class DatabaseMigratorTests : GRDBTestCase { } let dbQueue = try makeDatabaseQueue() try migrator.migrate(dbQueue) - try dbQueue.read { db in - try XCTAssertTrue(Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty()) - } + try dbQueue.read { try $0.checkForeignKeyViolations() } } do { var migrator = DatabaseMigrator() @@ -914,9 +908,7 @@ class DatabaseMigratorTests : GRDBTestCase { try migrator.migrate(dbQueue) XCTFail("Expected error") } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } - try dbQueue.read { db in - try XCTAssertTrue(Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty()) - } + try dbQueue.read { try $0.checkForeignKeyViolations() } } } @@ -941,10 +933,11 @@ class DatabaseMigratorTests : GRDBTestCase { } let dbQueue = try makeDatabaseQueue() try migrator.migrate(dbQueue) - try dbQueue.read { db in - // The unique opportunity for corrupt data - try XCTAssertFalse(Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty()) - } + do { + // The unique opportunity for corrupt data! + try dbQueue.read { try $0.checkForeignKeyViolations() } + XCTFail("Expected foreign key violation") + } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } } do { var migrator = DatabaseMigrator().disablingDeferredForeignKeyChecks() @@ -956,9 +949,7 @@ class DatabaseMigratorTests : GRDBTestCase { try migrator.migrate(dbQueue) XCTFail("Expected error") } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } - try dbQueue.read { db in - try XCTAssertTrue(Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty()) - } + try dbQueue.read { try $0.checkForeignKeyViolations() } } // Transient foreign key violation @@ -969,9 +960,7 @@ class DatabaseMigratorTests : GRDBTestCase { } let dbQueue = try makeDatabaseQueue() try migrator.migrate(dbQueue) - try dbQueue.read { db in - try XCTAssertTrue(Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty()) - } + try dbQueue.read { try $0.checkForeignKeyViolations() } } do { var migrator = DatabaseMigrator().disablingDeferredForeignKeyChecks() @@ -983,9 +972,7 @@ class DatabaseMigratorTests : GRDBTestCase { try migrator.migrate(dbQueue) XCTFail("Expected error") } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } - try dbQueue.read { db in - try XCTAssertTrue(Row.fetchCursor(db, sql: "PRAGMA foreign_key_check").isEmpty()) - } + try dbQueue.read { try $0.checkForeignKeyViolations() } } } From 7e9a2f5a737f43e95e23acc104c7cb4941bea1be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 4 Nov 2021 15:12:24 +0100 Subject: [PATCH 07/11] Fix typo --- Documentation/Migrations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index dc04387ad..4439cb9e6 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -229,7 +229,7 @@ In order to check for foreign key violations, the `checkForeignKeyViolations()` ```swift // SQLite error 19: foreign key constraint failed from player(teamId) to team(id), -// in [id:1 teamId:2 name:"O'Brien" score: 1000] +// in [id:1 teamId:2 name:"O'Brien" score:1000] try db.checkForeignKeyViolations() ``` From ffdc80646e0982a256a141832253d3c7d951efc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 4 Nov 2021 15:15:23 +0100 Subject: [PATCH 08/11] Documentation --- Documentation/Migrations.md | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index 4439cb9e6..5f1fd02fc 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -114,8 +114,7 @@ The `eraseDatabaseOnSchemaChange` option triggers a recreation of the database i If SQLite does not directly support all kinds of schema alterations, you can make arbitrary changes to the schema design of any table using a sequence of operations, as in the example below: ```swift -migrator.registerMigration("AddNotNullCheckOnName") { db in - // Add a NOT NULL constraint on player.name: +migrator.registerMigration("Add NOT NULL check on player.name") { db in try db.create(table: "new_player") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() @@ -165,9 +164,9 @@ SQLite makes it [difficult](https://www.sqlite.org/lang_altertable.html) to perf You'll need to read this chapter if you are looking for a mitigation to the time spent by migrations performing foreign key checks. You'll know this by instrumenting your migrations, and looking for the time spent in the `checkForeignKeyViolations` method. See [Advanced Database Schema Changes] right above to know what are those foreign key checks. -**Your first mitigation technique are immediate foreign key checks.** +**Your first mitigation technique is immediate foreign key checks.** -If you register a migration with `.immediate` foreign key checks, the migration will not disable foreign keys, and won't need to perform the full check of all foreign keys in your database: +If you register a migration with `.immediate` foreign key checks, the migration will not temporarily disable foreign keys, and won't need to perform a deferred full check of all foreign keys in your database: ```swift migrator.registerMigration("make it faster please", foreignKeyChecks: .immediate) { db in @@ -233,25 +232,34 @@ In order to check for foreign key violations, the `checkForeignKeyViolations()` try db.checkForeignKeyViolations() ``` -If you want to precisely introspect each foreign key violation, you will use instead: +You can also iterate a lazy [cursor](../README.md#cursors) of all individual foreign key violations found in the database: ```swift let violations = try db.foreignKeyViolations() while let violation = try violations.next() { // The name of the table that contains the `REFERENCES` clause - print(violation.originTable) + violation.originTable // The rowid of the row that contains the invalid `REFERENCES` clause, or // nil if the origin table is a `WITHOUT ROWID` table. - print(violation.originRowID) + violation.originRowID // The name of the table that is referred to. - print(violation.destinationTable) + violation.destinationTable // The id of the specific foreign key constraint that failed. This id // matches `ForeignKeyInfo.id`. See `Database.foreignKeys(on:)` for more // information. - print(violation.foreignKeyId) + violation.foreignKeyId + + // Plain description: + // "Foreign key violation from player to team, in rowid 1" + String(describing: violation) + + // Rich description: + // "foreign key constraint failed from player(teamId) to team(id), + // in [id:1 teamId:2 name:"O'Brien" score:1000]" + try violation.failureDescription(db) } ``` From 127c4e04400a11e9ba4bd23d52495a9d2e7db527 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 4 Nov 2021 18:26:24 +0100 Subject: [PATCH 09/11] Rename methods that check foreign keys --- Documentation/Migrations.md | 10 +++++----- GRDB/Core/Database+Schema.swift | 10 +++++----- GRDB/Migration/Migration.swift | 2 +- Tests/GRDBTests/DatabaseMigratorTests.swift | 16 ++++++++-------- Tests/GRDBTests/ForeignKeyInfoTests.swift | 8 ++++---- 5 files changed, 23 insertions(+), 23 deletions(-) diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index 5f1fd02fc..9b870923a 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -162,7 +162,7 @@ The detailed sequence of operations is described below, some of them are perform SQLite makes it [difficult](https://www.sqlite.org/lang_altertable.html) to perform some schema changes, and this creates very undesired churn w.r.t. foreign keys. GRDB makes its best to hide those problems to you, but you might have to deal with them one day, especially if your database becomes *very big*: -You'll need to read this chapter if you are looking for a mitigation to the time spent by migrations performing foreign key checks. You'll know this by instrumenting your migrations, and looking for the time spent in the `checkForeignKeyViolations` method. See [Advanced Database Schema Changes] right above to know what are those foreign key checks. +You'll need to read this chapter if you are looking for a mitigation to the time spent by migrations performing foreign key checks. You'll know this by instrumenting your migrations, and looking for the time spent in the `checkForeignKeys` method. See [Advanced Database Schema Changes] right above to know what are those foreign key checks. **Your first mitigation technique is immediate foreign key checks.** @@ -209,7 +209,7 @@ In order to prevent foreign key violations from being committed to disk, you can // Throws an error and stops migrations if there exists a // foreign key violation in the 'player' table. - try db.checkForeignKeyViolations(in: "player") + try db.checkForeignKeys(in: "player") } ``` @@ -220,16 +220,16 @@ In order to prevent foreign key violations from being committed to disk, you can // Throws an error if there exists any foreign key violation. try dbQueue.read { db in - try db.checkForeignKeyViolations() + try db.checkForeignKeys() } ``` -In order to check for foreign key violations, the `checkForeignKeyViolations()` and `checkForeignKeyViolations(in:)` methods are recommended over the raw use of the [`PRAGMA foreign_key_check`](https://www.sqlite.org/pragma.html#pragma_foreign_key_check). Those methods throw a nicely detailed DatabaseError that contains a lot of debugging information: +In order to check for foreign key violations, the `checkForeignKeys()` and `checkForeignKeys(in:)` methods are recommended over the raw use of the [`PRAGMA foreign_key_check`](https://www.sqlite.org/pragma.html#pragma_foreign_key_check). Those methods throw a nicely detailed DatabaseError that contains a lot of debugging information: ```swift // SQLite error 19: foreign key constraint failed from player(teamId) to team(id), // in [id:1 teamId:2 name:"O'Brien" score:1000] -try db.checkForeignKeyViolations() +try db.checkForeignKeys() ``` You can also iterate a lazy [cursor](../README.md#cursors) of all individual foreign key violations found in the database: diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 55adb1589..04e2414dd 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -479,14 +479,14 @@ extension Database { /// Throws a DatabaseError of extended code `SQLITE_CONSTRAINT_FOREIGNKEY` /// if there exists a foreign key violation in the database. - public func checkForeignKeyViolations() throws { - try checkForeignKeyViolations(from: foreignKeyViolations()) + public func checkForeignKeys() throws { + try checkForeignKeys(from: foreignKeyViolations()) } /// Throws a DatabaseError of extended code `SQLITE_CONSTRAINT_FOREIGNKEY` /// if there exists a foreign key violation in the table. - public func checkForeignKeyViolations(in tableName: String) throws { - try checkForeignKeyViolations(from: foreignKeyViolations(in: tableName)) + public func checkForeignKeys(in tableName: String) throws { + try checkForeignKeys(from: foreignKeyViolations(in: tableName)) } private func foreignKeyViolations(in table: TableIdentifier) throws -> RecordCursor { @@ -495,7 +495,7 @@ extension Database { """) } - private func checkForeignKeyViolations(from violations: RecordCursor) throws { + private func checkForeignKeys(from violations: RecordCursor) throws { guard let violation = try violations.next() else { return } diff --git a/GRDB/Migration/Migration.swift b/GRDB/Migration/Migration.swift index 789da9c46..f0cc2eac4 100644 --- a/GRDB/Migration/Migration.swift +++ b/GRDB/Migration/Migration.swift @@ -67,7 +67,7 @@ struct Migration { // > then run PRAGMA foreign_key_check to verify that the // > schema change did not break any foreign // > key constraints. - try db.checkForeignKeyViolations() + try db.checkForeignKeys() // > 11. Commit the transaction started in step 2. return .commit diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 9263ae75e..196f08e05 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -873,7 +873,7 @@ class DatabaseMigratorTests : GRDBTestCase { try migrator.migrate(dbQueue) XCTFail("Expected error") } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } - try dbQueue.read { try $0.checkForeignKeyViolations() } + try dbQueue.read { try $0.checkForeignKeys() } } do { var migrator = DatabaseMigrator() @@ -885,7 +885,7 @@ class DatabaseMigratorTests : GRDBTestCase { try migrator.migrate(dbQueue) XCTFail("Expected error") } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } - try dbQueue.read { try $0.checkForeignKeyViolations() } + try dbQueue.read { try $0.checkForeignKeys() } } // Transient foreign key violation @@ -896,7 +896,7 @@ class DatabaseMigratorTests : GRDBTestCase { } let dbQueue = try makeDatabaseQueue() try migrator.migrate(dbQueue) - try dbQueue.read { try $0.checkForeignKeyViolations() } + try dbQueue.read { try $0.checkForeignKeys() } } do { var migrator = DatabaseMigrator() @@ -908,7 +908,7 @@ class DatabaseMigratorTests : GRDBTestCase { try migrator.migrate(dbQueue) XCTFail("Expected error") } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } - try dbQueue.read { try $0.checkForeignKeyViolations() } + try dbQueue.read { try $0.checkForeignKeys() } } } @@ -935,7 +935,7 @@ class DatabaseMigratorTests : GRDBTestCase { try migrator.migrate(dbQueue) do { // The unique opportunity for corrupt data! - try dbQueue.read { try $0.checkForeignKeyViolations() } + try dbQueue.read { try $0.checkForeignKeys() } XCTFail("Expected foreign key violation") } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } } @@ -949,7 +949,7 @@ class DatabaseMigratorTests : GRDBTestCase { try migrator.migrate(dbQueue) XCTFail("Expected error") } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } - try dbQueue.read { try $0.checkForeignKeyViolations() } + try dbQueue.read { try $0.checkForeignKeys() } } // Transient foreign key violation @@ -960,7 +960,7 @@ class DatabaseMigratorTests : GRDBTestCase { } let dbQueue = try makeDatabaseQueue() try migrator.migrate(dbQueue) - try dbQueue.read { try $0.checkForeignKeyViolations() } + try dbQueue.read { try $0.checkForeignKeys() } } do { var migrator = DatabaseMigrator().disablingDeferredForeignKeyChecks() @@ -972,7 +972,7 @@ class DatabaseMigratorTests : GRDBTestCase { try migrator.migrate(dbQueue) XCTFail("Expected error") } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { } - try dbQueue.read { try $0.checkForeignKeyViolations() } + try dbQueue.read { try $0.checkForeignKeys() } } } diff --git a/Tests/GRDBTests/ForeignKeyInfoTests.swift b/Tests/GRDBTests/ForeignKeyInfoTests.swift index dee225f6d..ab8cb362d 100644 --- a/Tests/GRDBTests/ForeignKeyInfoTests.swift +++ b/Tests/GRDBTests/ForeignKeyInfoTests.swift @@ -177,7 +177,7 @@ class ForeignKeyInfoTests: GRDBTestCase { } } - func testCheckForeignKeyViolations() throws { + func testCheckForeignKeys() throws { try makeDatabaseQueue().writeWithoutTransaction { db in try db.execute(sql: """ CREATE TABLE parent(id TEXT NOT NULL PRIMARY KEY); @@ -187,7 +187,7 @@ class ForeignKeyInfoTests: GRDBTestCase { """) do { - try db.checkForeignKeyViolations() + try db.checkForeignKeys() } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) @@ -205,7 +205,7 @@ class ForeignKeyInfoTests: GRDBTestCase { """) do { - try db.checkForeignKeyViolations() + try db.checkForeignKeys() } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) @@ -223,7 +223,7 @@ class ForeignKeyInfoTests: GRDBTestCase { """) do { - try db.checkForeignKeyViolations() + try db.checkForeignKeys() } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) From c81a4dbf320a45222341a457305d503d8652cee4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 4 Nov 2021 18:44:44 +0100 Subject: [PATCH 10/11] Distinguish "FOREIGN KEY constraint failed" from "FOREIGN KEY constraint violation" errors --- Documentation/Migrations.md | 4 ++-- GRDB/Core/Database+Schema.swift | 6 +++--- Tests/GRDBTests/DatabaseMigratorTests.swift | 6 +++--- Tests/GRDBTests/ForeignKeyInfoTests.swift | 12 ++++++------ 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index 9b870923a..7831f3b6c 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -227,7 +227,7 @@ In order to prevent foreign key violations from being committed to disk, you can In order to check for foreign key violations, the `checkForeignKeys()` and `checkForeignKeys(in:)` methods are recommended over the raw use of the [`PRAGMA foreign_key_check`](https://www.sqlite.org/pragma.html#pragma_foreign_key_check). Those methods throw a nicely detailed DatabaseError that contains a lot of debugging information: ```swift -// SQLite error 19: foreign key constraint failed from player(teamId) to team(id), +// SQLite error 19: FOREIGN KEY constraint violation - from player(teamId) to team(id), // in [id:1 teamId:2 name:"O'Brien" score:1000] try db.checkForeignKeys() ``` @@ -257,7 +257,7 @@ while let violation = try violations.next() { String(describing: violation) // Rich description: - // "foreign key constraint failed from player(teamId) to team(id), + // "FOREIGN KEY constraint violation - from player(teamId) to team(id), // in [id:1 teamId:2 name:"O'Brien" score:1000]" try violation.failureDescription(db) } diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 04e2414dd..161d967c0 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -808,7 +808,7 @@ public struct ForeignKeyViolation: FetchableRecord, CustomStringConvertible { /// Returns a precise description of the foreign key violation. /// - /// For example: 'foreign key constraint failed from player(teamId) to team(id), + /// For example: 'FOREIGN KEY constraint violation - from player(teamId) to team(id), /// in [id:1 teamId:2 name:"O'Brien" score: 1000]' public func failureDescription(_ db: Database) throws -> String { // Grab detailed information, if possible, for better error message @@ -822,12 +822,12 @@ public struct ForeignKeyViolation: FetchableRecord, CustomStringConvertible { var description: String if let foreignKey = foreignKey { description = """ - foreign key constraint failed \ + FOREIGN KEY constraint violation - \ from \(originTable)(\(foreignKey.originColumns.joined(separator: ", "))) \ to \(destinationTable)(\(foreignKey.destinationColumns.joined(separator: ", "))) """ } else { - description = "foreign key constraint failed from \(originTable) to \(destinationTable)" + description = "FOREIGN KEY constraint violation - from \(originTable) to \(destinationTable)" } if let originRow = originRow { diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 196f08e05..acfa29399 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -400,7 +400,7 @@ class DatabaseMigratorTests : GRDBTestCase { XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) - XCTAssertEqual(error.message, #"foreign key constraint failed from pets(masterId) to persons(id), in [masterId:123 name:"Bobby"]"#) + XCTAssertEqual(error.message, #"FOREIGN KEY constraint violation - from pets(masterId) to persons(id), in [masterId:123 name:"Bobby"]"#) let names = try dbQueue.inDatabase { db in try String.fetchAll(db, sql: "SELECT name FROM persons") @@ -420,7 +420,7 @@ class DatabaseMigratorTests : GRDBTestCase { let error = error as! DatabaseError XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) - XCTAssertEqual(error.message, #"foreign key constraint failed from pets(masterId) to persons(id), in [masterId:123 name:"Bobby"]"#) + XCTAssertEqual(error.message, #"FOREIGN KEY constraint violation - from pets(masterId) to persons(id), in [masterId:123 name:"Bobby"]"#) let names = try! String.fetchAll(db, sql: "SELECT name FROM persons") XCTAssertEqual(names, ["Arthur"]) @@ -463,7 +463,7 @@ class DatabaseMigratorTests : GRDBTestCase { XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) - XCTAssertEqual(error.message, #"foreign key constraint failed from pets(masterId) to persons(id), in [masterId:123 name:"Bobby"]"#) + XCTAssertEqual(error.message, #"FOREIGN KEY constraint violation - from pets(masterId) to persons(id), in [masterId:123 name:"Bobby"]"#) try dbQueue.inDatabase { db in // Arthur inserted (migration 1), Barbara (migration 3) not inserted. diff --git a/Tests/GRDBTests/ForeignKeyInfoTests.swift b/Tests/GRDBTests/ForeignKeyInfoTests.swift index ab8cb362d..483db5179 100644 --- a/Tests/GRDBTests/ForeignKeyInfoTests.swift +++ b/Tests/GRDBTests/ForeignKeyInfoTests.swift @@ -191,8 +191,8 @@ class ForeignKeyInfoTests: GRDBTestCase { } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) - XCTAssertEqual(error.message, #"foreign key constraint failed from child(parentId) to parent(id), in [id:13 parentId:"1"]"#) - XCTAssertEqual(error.description, #"SQLite error 19: foreign key constraint failed from child(parentId) to parent(id), in [id:13 parentId:"1"]"#) + XCTAssertEqual(error.message, #"FOREIGN KEY constraint violation - from child(parentId) to parent(id), in [id:13 parentId:"1"]"#) + XCTAssertEqual(error.description, #"SQLite error 19: FOREIGN KEY constraint violation - from child(parentId) to parent(id), in [id:13 parentId:"1"]"#) } } @@ -209,8 +209,8 @@ class ForeignKeyInfoTests: GRDBTestCase { } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) - XCTAssertEqual(error.message, #"foreign key constraint failed from child(parentA, parentB) to parent(a, b), in [id:13 parentA:"foo" parentB:"bar"]"#) - XCTAssertEqual(error.description, #"SQLite error 19: foreign key constraint failed from child(parentA, parentB) to parent(a, b), in [id:13 parentA:"foo" parentB:"bar"]"#) + XCTAssertEqual(error.message, #"FOREIGN KEY constraint violation - from child(parentA, parentB) to parent(a, b), in [id:13 parentA:"foo" parentB:"bar"]"#) + XCTAssertEqual(error.description, #"SQLite error 19: FOREIGN KEY constraint violation - from child(parentA, parentB) to parent(a, b), in [id:13 parentA:"foo" parentB:"bar"]"#) } } @@ -227,8 +227,8 @@ class ForeignKeyInfoTests: GRDBTestCase { } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT) XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY) - XCTAssertEqual(error.message, "foreign key constraint failed from child(parentA, parentB) to parent(a, b)") - XCTAssertEqual(error.description, "SQLite error 19: foreign key constraint failed from child(parentA, parentB) to parent(a, b)") + XCTAssertEqual(error.message, "FOREIGN KEY constraint violation - from child(parentA, parentB) to parent(a, b)") + XCTAssertEqual(error.description, "SQLite error 19: FOREIGN KEY constraint violation - from child(parentA, parentB) to parent(a, b)") } } } From 454dd73c4cfd5ffc5d9f1d5ca3e3d155b511abf2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 4 Nov 2021 18:52:19 +0100 Subject: [PATCH 11/11] CHANGELOG --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index eb2da7366..8fad6c93d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -84,12 +84,14 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Breaking Change**: [#1076](https://github.com/groue/GRDB.swift/pull/1076) by [@groue](https://github.com/groue): Require Swift 5.3 - **New**: [#1078](https://github.com/groue/GRDB.swift/pull/1078) by [@groue](https://github.com/groue): More convenience methods (non-mutating persistence methods, and existence-checking methods) - **New**: [#1088](https://github.com/groue/GRDB.swift/pull/1088) by [@groue](https://github.com/groue): Shared ValueObservation +- **New**: [#1095](https://github.com/groue/GRDB.swift/pull/1095) by [@groue](https://github.com/groue): Precise foreign key checks for migrations - **New**: `DatabasePool.erase()` prevents concurrent reads until it has completed. - **New**: A new `close()` method allows precise closing of database connections. - **Fixed**: Filtering records by primary key now properly encodes dates and uuids according to the customized strategies (`filter(id:)`, `deleteAll(_:keys:)`, etc.) - **Documentation Update**: The [Date and UUID Coding Strategies](README.md#date-and-uuid-coding-strategies) was updated for the new support for customized date and uuid primary key coding. - **Documentation Update**: A new [Testing for Record Existence](README.md#testing-for-record-existence) chapter describes the new `request.isEmpty(_:)`, `Record.exists(_:id:)` and `Record.exists(_:key:)` methods. - **Documentation Update**: A new [ValueObservation Sharing](README.md#valueobservation-sharing) chapter describes how to share database observations and spare database resources. +- **Documentation Update**: The [Migrations](Documentation/Migrations.md) guide has a much more detailed description of how you can mitigate that difficulties that SQLite creates around foreign keys during schema changes. ## 5.12.0