From 71e09a38d491dd0e358cec6bb1de08289e7a2d65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 15 Mar 2025 11:47:24 +0100 Subject: [PATCH] Document that migrations that rename foreign key columns should use immediate foreign key checks Fix #1740 --- GRDB/Documentation.docc/Migrations.md | 20 +++++++++++++++++ .../Schema/TableAlteration.swift | 22 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/GRDB/Documentation.docc/Migrations.md b/GRDB/Documentation.docc/Migrations.md index ee7ed0f83..0d2b65124 100644 --- a/GRDB/Documentation.docc/Migrations.md +++ b/GRDB/Documentation.docc/Migrations.md @@ -94,6 +94,26 @@ migrator.registerMigration("Create authors") { db in } ``` +#### How to Rename a Foreign Key + +When a migration **renames a foreign key**, make sure the migration runs with `.immediate` foreign key checks, in order to avoid database integrity problems: + +```swift +// IMPORTANT: rename foreign keys with immediate foreign key checks. +migrator.registerMigration("Guilds", foreignKeyChecks: .immediate) { db in + try db.rename(table: "team", to: "guild") + + try db.alter(table: "player") { t in + // Rename a foreign key + t.rename(column: "teamId", to: "guildId") + } +} +``` + +Note: migrations that run with `.immediate` foreign key checks can not be used to recreated database tables, as described below. When needed, define two migrations instead of one. + +#### How to Recreate a Database Table + When you need to modify a table in a way that is not directly supported by SQLite, or not available on your target operating system, you will need to recreate the database table. For example: diff --git a/GRDB/QueryInterface/Schema/TableAlteration.swift b/GRDB/QueryInterface/Schema/TableAlteration.swift index 9b40a2d62..d967d073a 100644 --- a/GRDB/QueryInterface/Schema/TableAlteration.swift +++ b/GRDB/QueryInterface/Schema/TableAlteration.swift @@ -125,6 +125,28 @@ public final class TableAlteration { /// } /// ``` /// + /// Take care, when you rename **foreign keys** in , + /// to run the migration with the ``DatabaseMigrator/ForeignKeyChecks/immediate`` + /// foreign key checks, in order to avoid integrity failures: + /// + /// ```swift + /// // RECOMMENDED: rename foreign keys with immediate foreign key checks. + /// migrator.registerMigration("Guilds", foreignKeyChecks: .immediate) { db in + /// try db.rename(table: "team", to: "guild") + /// try db.alter(table: "player") { t in + /// t.rename(column: "teamId", to: "guildId") + /// } + /// } + /// + /// // NOT RECOMMENDED: rename foreign keys with disabled foreign keys. + /// migrator.registerMigration("Guilds") { db in + /// try db.rename(table: "team", to: "guild") + /// try db.alter(table: "player") { t in + /// t.rename(column: "teamId", to: "guildId") + /// } + /// } + /// ``` + /// /// Related SQLite documentation: /// /// - parameter name: the old name of the column.