Document that migrations that rename foreign key columns should use immediate foreign key checks

Fix #1740
This commit is contained in:
Gwendal Roué committed 2025-03-15 12:06:14 +01:00
1 parent d800a79d5d
commit 71e09a38d4
2 files changed
+42

No files matched your search

+20
View File
@@ -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:
@@ -125,6 +125,28 @@ public final class TableAlteration {
/// }
/// ```
///
/// Take care, when you rename **foreign keys** in <doc:Migrations>,
/// 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: <https://www.sqlite.org/lang_altertable.html>
///
/// - parameter name: the old name of the column.