foreignKeyViolations() and checkForeignKeyViolations()

This commit is contained in:
Gwendal Roué committed 2021-11-04 14:19:11 +01:00
1 parent b66b907fbc
commit 6193c6aa00
4 files changed
+298 -42

No files matched your search

+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 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<ForeignKeyViolation> {
try ForeignKeyViolation.fetchCursor(self, sql: """
PRAGMA \(table.schemaID.sql).foreign_key_check(\(table.name.quotedDatabaseIdentifier))
""")
}
private func checkForeignKeyViolations(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 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
+1 -17
View File
@@ -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
+12 -12
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 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 { }
}
}
+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 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)")
}
}
}