diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index abee19b36..ffb786612 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -260,6 +260,9 @@ while let violation = try violations.next() { // "FOREIGN KEY constraint violation - from player(teamId) to team(id), // in [id:1 teamId:2 name:"O'Brien" score:1000]" try violation.failureDescription(db) + + // Turn violation into a DatabaseError + throw violation.databaseError(db) } ``` diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index c607636cf..1fd259700 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -496,16 +496,9 @@ extension Database { } private func checkForeignKeys(from violations: RecordCursor) throws { - guard let violation = try violations.next() else { - return + if let violation = try violations.next() { + throw violation.databaseError(self) } - - // 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 @@ -843,6 +836,16 @@ public struct ForeignKeyViolation: FetchableRecord, CustomStringConvertible { return description } + + /// Returns a DatabaseError of extended code `SQLITE_CONSTRAINT_FOREIGNKEY` + public func databaseError(_ db: Database) -> DatabaseError { + // Grab detailed information, if possible, for better error message. + // If detailed information is not available, fallback to plain description. + let message = (try? failureDescription(db)) ?? String(describing: self) + return DatabaseError( + resultCode: .SQLITE_CONSTRAINT_FOREIGNKEY, + message: message) + } } /// Primary keys are returned from the Database.primaryKey(_:) method.