Merge pull request #1095 from groue/dev/foreign-keys-checks

Precise foreign key checks for migrations
This commit is contained in:
Gwendal Roué authored and GitHub committed 2021-11-04 19:38:56 +01:00
commit 088f76db9e
7 files changed
+726 -47

No files matched your search

+2
View File
@@ -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
+158 -6
View File
@@ -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).
@@ -102,13 +111,10 @@ 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
// 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()
@@ -119,6 +125,144 @@ migrator.registerMigration("AddNotNullCheckOnName") { db in
}
```
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
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 `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.**
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
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.disablingDeferredForeignKeyChecks()
// 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.disablingDeferredForeignKeyChecks()
migrator.registerMigration("unchecked") { db in ... }
migrator.registerMigration("checked", foreignKeyChecks: .immediate) { db in ... }
```
- Perform foreign key checks on some tables only:
```swift
migrator = migrator.disablingDeferredForeignKeyChecks()
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.checkForeignKeys(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.checkForeignKeys()
}
```
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 violation - from player(teamId) to team(id),
// in [id:1 teamId:2 name:"O'Brien" score:1000]
try db.checkForeignKeys()
```
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
violation.originTable
// The rowid of the row that contains the invalid `REFERENCES` clause, or
// nil if the origin table is a `WITHOUT ROWID` table.
violation.originRowID
// The name of the table that is referred to.
violation.destinationTable
// The id of the specific foreign key constraint that failed. This id
// matches `ForeignKeyInfo.id`. See `Database.foreignKeys(on:)` for more
// information.
violation.foreignKeyId
// Plain description:
// "Foreign key violation from player to team, in rowid 1"
String(describing: violation)
// Rich description:
// "FOREIGN KEY constraint violation - from player(teamId) to team(id),
// in [id:1 teamId:2 name:"O'Brien" score:1000]"
try violation.failureDescription(db)
}
```
## Asynchronous Migrations
`DatabaseMigrator` provides two ways to migrate a database in an asynchronous way.
@@ -142,3 +286,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
+125 -7
View File
@@ -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<ForeignKeyViolation> {
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<ForeignKeyViolation> {
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 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 checkForeignKeys(in tableName: String) throws {
try checkForeignKeys(from: foreignKeyViolations(in: tableName))
}
private func foreignKeyViolations(in table: TableIdentifier) throws -> RecordCursor<ForeignKeyViolation> {
try ForeignKeyViolation.fetchCursor(self, sql: """
PRAGMA \(table.schemaID.sql).foreign_key_check(\(table.name.quotedDatabaseIdentifier))
""")
}
private func checkForeignKeys(from violations: RecordCursor<ForeignKeyViolation>) 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 <https://www.sqlite.org/pragma.html#pragma_foreign_key_check>
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 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
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 violation - \
from \(originTable)(\(foreignKey.originColumns.joined(separator: ", "))) \
to \(destinationTable)(\(foreignKey.destinationColumns.joined(separator: ", ")))
"""
} else {
description = "FOREIGN KEY constraint violation - 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
+93 -2
View File
@@ -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 `disablingDeferredForeignKeyChecks()`.
///
/// Deferred foreign key checks are necessary for migrations that
/// perform schema changes as described in
/// <https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes>
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
/// <https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes>
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.disablingDeferredForeignKeyChecks()
/// 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 disablingDeferredForeignKeyChecks() -> 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 `disablingDeferredForeignKeyChecks()`.
///
/// 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
/// <https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes>
/// - 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
+33 -20
View File
@@ -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
@@ -38,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.checkForeignKeys()
// > 11. Commit the transaction started in step 2.
return .commit
+155 -6
View File
@@ -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 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")
@@ -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 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"])
@@ -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 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.
@@ -848,4 +848,153 @@ 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_FOREIGNKEY { }
try dbQueue.read { try $0.checkForeignKeys() }
}
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_FOREIGNKEY { }
try dbQueue.read { try $0.checkForeignKeys() }
}
// 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 { try $0.checkForeignKeys() }
}
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_FOREIGNKEY { }
try dbQueue.read { try $0.checkForeignKeys() }
}
}
func testDisablingDeferredForeignKeyChecks() 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().disablingDeferredForeignKeyChecks()
migrator.registerMigration("A") { db in
try db.execute(sql: foreignKeyViolation)
}
let dbQueue = try makeDatabaseQueue()
try migrator.migrate(dbQueue)
do {
// The unique opportunity for corrupt data!
try dbQueue.read { try $0.checkForeignKeys() }
XCTFail("Expected foreign key violation")
} catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { }
}
do {
var migrator = DatabaseMigrator().disablingDeferredForeignKeyChecks()
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_FOREIGNKEY { }
try dbQueue.read { try $0.checkForeignKeys() }
}
// Transient foreign key violation
do {
var migrator = DatabaseMigrator().disablingDeferredForeignKeyChecks()
migrator.registerMigration("A") { db in
try db.execute(sql: transientForeignKeyViolation)
}
let dbQueue = try makeDatabaseQueue()
try migrator.migrate(dbQueue)
try dbQueue.read { try $0.checkForeignKeys() }
}
do {
var migrator = DatabaseMigrator().disablingDeferredForeignKeyChecks()
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_FOREIGNKEY { }
try dbQueue.read { try $0.checkForeignKeys() }
}
}
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));
INSERT INTO child (parentId) VALUES (1);
"""
var migrator = DatabaseMigrator()
migrator.registerMigration("A") { db in
try db.execute(sql: foreignKeyViolation)
}
migrator = migrator.disablingDeferredForeignKeyChecks()
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_FOREIGNKEY { }
}
}
+160 -6
View File
@@ -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 testCheckForeignKeys() 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.checkForeignKeys()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY)
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"]"#)
}
}
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.checkForeignKeys()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY)
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"]"#)
}
}
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.checkForeignKeys()
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
XCTAssertEqual(error.extendedResultCode, .SQLITE_CONSTRAINT_FOREIGNKEY)
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)")
}
}
}