Migrations Guide in now a DocC article

This commit is contained in:
Gwendal Roué committed 2022-11-07 22:44:37 +01:00
1 parent 1be868c4b0
commit fb81ec6792
16 files changed
+328 -377

No files matched your search

+1 -1
View File
@@ -2963,7 +2963,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[Further Refinements to Associations]: #further-refinements-to-associations
[The Types of Associations]: #the-types-of-associations
[FetchableRecord]: ../README.md#fetchablerecord-protocols
[migration]: Migrations.md
[migration]: http://groue.github.io/GRDB.swift/docs/6.3/documentation/grdb/migrations
[Record]: ../README.md#records
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
[Associations and the Database Schema]: #associations-and-the-database-schema
+1 -1
View File
@@ -398,7 +398,7 @@ let cancellable = hallOfFamePublisher.sink(
[`readPublisher(receiveOn:value:)`]: #databasereaderreadpublisherreceiveonvalue
[`writePublisher(receiveOn:updates:)`]: #databasewriterwritepublisherreceiveonupdates
[`writePublisher(receiveOn:updates:thenRead:)`]: #databasewriterwritepublisherreceiveonupdatesthenread
[`migratePublisher(_:receiveOn:)`]: Migrations.md#asynchronous-migrations
[`migratePublisher(_:receiveOn:)`]: http://groue.github.io/GRDB.swift/docs/6.3/documentation/grdb/databasemigrator/migratepublisher(_:receiveon:)
[configured]: ../README.md#databasepool-configuration
[database pool]: ../README.md#database-pools
[database queue]: ../README.md#database-queues
@@ -22,13 +22,13 @@ struct AppDatabase {
/// The DatabaseMigrator that defines the database schema.
///
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md>
/// See <http://groue.github.io/GRDB.swift/docs/6.3/documentation/grdb/migrations>
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
#if DEBUG
// Speed up development by nuking the database when migrations change
// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md#the-erasedatabaseonschemachange-option
// See <http://groue.github.io/GRDB.swift/docs/6.3/documentation/grdb/migrations>
migrator.eraseDatabaseOnSchemaChange = true
#endif
@@ -25,7 +25,7 @@ The topics covered in this demo are:
- [AppDatabase.swift](GRDBAsyncDemo/AppDatabase.swift)
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema.
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](http://groue.github.io/GRDB.swift/docs/6.3/documentation/grdb/databasemigrator) in order to setup the database schema.
- [Persistence.swift](GRDBAsyncDemo/Persistence.swift)
@@ -23,13 +23,13 @@ struct AppDatabase {
/// The DatabaseMigrator that defines the database schema.
///
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md>
/// See <http://groue.github.io/GRDB.swift/docs/6.3/documentation/grdb/migrations>
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
#if DEBUG
// Speed up development by nuking the database when migrations change
// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md#the-erasedatabaseonschemachange-option
// See <http://groue.github.io/GRDB.swift/docs/6.3/documentation/grdb/migrations>
migrator.eraseDatabaseOnSchemaChange = true
#endif
@@ -25,7 +25,7 @@ The topics covered in this demo are:
- [AppDatabase.swift](GRDBCombineDemo/AppDatabase.swift)
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema.
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](http://groue.github.io/GRDB.swift/docs/6.3/documentation/grdb/databasemigrator) in order to setup the database schema.
- [Persistence.swift](GRDBCombineDemo/Persistence.swift)
@@ -21,13 +21,13 @@ final class AppDatabase {
/// The DatabaseMigrator that defines the database schema.
///
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md>
/// See <http://groue.github.io/GRDB.swift/docs/6.3/documentation/grdb/migrations>
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
#if DEBUG
// Speed up development by nuking the database when migrations change
// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md#the-erasedatabaseonschemachange-option
// See <http://groue.github.io/GRDB.swift/docs/6.3/documentation/grdb/migrations>
migrator.eraseDatabaseOnSchemaChange = true
#endif
+1 -1
View File
@@ -20,7 +20,7 @@ The topics covered in this demo are:
- [AppDatabase.swift](GRDBDemoiOS/AppDatabase.swift)
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema, and [ValueObservation](../../../README.md#valueobservation) in order to let the application observe database changes.
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](http://groue.github.io/GRDB.swift/docs/6.3/documentation/grdb/databasemigrator) in order to setup the database schema, and [ValueObservation](../../../README.md#valueobservation) in order to let the application observe database changes.
- [Persistence.swift](GRDBDemoiOS/Persistence.swift)
@@ -804,8 +804,8 @@ Instead, have a look at [Database Observation]:
[Divide and Conquer]: https://en.wikipedia.org/wiki/Divide_and_rule
[Why Adopt GRDB?]: WhyAdoptGRDB.md
[isolation]: https://en.wikipedia.org/wiki/Isolation_(database_systems)
[migrations]: Migrations.md
[migration]: Migrations.md
[migrations]: http://groue.github.io/GRDB.swift/docs/6.3/documentation/grdb/migrations
[migration]: http://groue.github.io/GRDB.swift/docs/6.3/documentation/grdb/migrations
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
[Concurrency Guide]: Concurrency.md
[GRDB concurrency rules]: Concurrency.md#concurrency-rules
+1 -300
View File
@@ -1,302 +1,3 @@
# Migrations
**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:
```swift
var migrator = DatabaseMigrator()
// 1st migration
migrator.registerMigration("v1") { db in
try db.create(table: "author") { t in ... }
try db.create(table: "book") { t in ... }
try db.create(index: ...)
}
// 2nd migration
migrator.registerMigration("v2") { db in
try db.alter(table: "author") { t in ... }
}
// Migrations for future versions will be inserted here:
//
// // 3rd migration
// migrator.registerMigration("...") { 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). See [Foreign Key Checks] below for more information.
**The memory of applied migrations is stored in the database itself** (in a reserved table).
You migrate the database up to the latest version with the `migrate(_:)` method:
```swift
try migrator.migrate(dbQueue) // or migrator.migrate(dbPool)
```
Migrate a database up to a specific version (useful for testing):
```swift
try migrator.migrate(dbQueue, upTo: "v2")
// Migrations can only run forward:
try migrator.migrate(dbQueue, upTo: "v2")
try migrator.migrate(dbQueue, upTo: "v1")
// ^ fatal error: database is already migrated beyond migration "v1"
```
When several versions of your app are deployed in the wild, you may want to perform extra checks:
```swift
try dbQueue.read { db in
// Readonly apps may want to check if database lacks expected migrations:
if try migrator.hasCompletedMigrations(db) == false {
// database too old
}
// All apps may want to check if database contains unknown (future) migrations:
if try migrator.hasBeenSuperseded(db) {
// database too new
}
}
```
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/6.3/documentation/grdb/databasemigrator) for more migrator methods.
## The `eraseDatabaseOnSchemaChange` Option
A DatabaseMigrator can automatically wipe out the full database content, and recreate the whole database from scratch, if it detects that migrations have changed their definition:
```swift
var migrator = DatabaseMigrator()
migrator.eraseDatabaseOnSchemaChange = true
```
> **Warning**: This option can destroy your precious users' data!
Setting `eraseDatabaseOnSchemaChange` is useful during application development, as you are still designing migrations, and the schema changes often.
It is recommended that this option does not ship in the released application:
```swift
var migrator = DatabaseMigrator()
#if DEBUG
// Speed up development by nuking the database when migrations change
migrator.eraseDatabaseOnSchemaChange = true
#endif
```
The `eraseDatabaseOnSchemaChange` option triggers a recreation of the database if and only if:
- A migration has been removed, or renamed.
- A *schema change* is detected. A schema change is any difference in the `sqlite_master` table, which contains the SQL used to create database tables, indexes, triggers, and views.
## Advanced Database Schema Changes
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("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()
}
try db.execute(sql: "INSERT INTO new_player SELECT * FROM player")
try db.drop(table: "player")
try db.rename(table: "new_player", to: "player")
}
```
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.
> **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.
>
> **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 constraint 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)
// Turn violation into a DatabaseError
throw violation.databaseError(db)
}
```
## Asynchronous Migrations
`DatabaseMigrator` provides the following ways to migrate a database in an asynchronous way.
The `asyncMigrate(_:completion:)` method:
```swift
// Completes in a protected dispatch queue that can write in the database
migrator.asyncMigrate(dbQueue, completion: { result in
switch result {
case .failure:
// Some error occurred during migrations
case let .success(db):
// Migrations succeeded
}
})
```
The `migratePublisher(_:receiveOn:)` [Combine](https://developer.apple.com/documentation/combine) publisher:
```swift
// DatabasePublishers.Migrate
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
This guide [has moved](http://groue.github.io/GRDB.swift/docs/6.3/documentation/grdb/migrations).
+1 -1
View File
@@ -230,7 +230,7 @@ extension AppConfiguration: FetchableRecord, PersistableRecord {
```
[migrations]: Migrations.md
[migrations]: http://groue.github.io/GRDB.swift/docs/6.3/documentation/grdb/migrations
[record]: ../README.md#records
[The Single-Row Table]: #the-single-row-table
[The Single-Row Record]: #the-single-row-record
+36
View File
@@ -947,6 +947,42 @@ public struct IndexInfo {
/// ``Database/foreignKeyViolations()`` and
/// ``Database/foreignKeyViolations(in:)`` methods.
///
/// For example:
///
/// ```swift
/// try dbQueue.read {
/// 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 constraint 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)
///
/// // Turn violation into a DatabaseError
/// throw violation.databaseError(db)
/// }
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_foreign_key_check>
public struct ForeignKeyViolation: FetchableRecord, CustomStringConvertible {
/// The name of the table that contains the foreign key.
+1 -1
View File
@@ -17,7 +17,7 @@ GRDB provides raw access to SQL and advanced SQLite features, because one someti
### Migrations
- ``DatabaseMigrator``
- <doc:Migrations>
### Record Types and the Query Interface
+241
View File
@@ -0,0 +1,241 @@
# Migrations
Migrations allow you to evolve your database schema over time.
## Overview
You can think of migrations as being 'versions' of the database. A database schema starts off in an empty state, and each migration adds or removes tables, columns, or entries.
GRDB can update the database schema along this timeline, bringing it from whatever point it is in the history to the latest version. When a user upgrades your application, only non-applied migrations are run.
You setup migrations in a ``DatabaseMigrator`` instance. For example:
```swift
var migrator = DatabaseMigrator()
// 1st migration
migrator.registerMigration("createLibrary") { db in
try db.create(table: "author") { t in
t.autoIncrementedPrimaryKey("id")
t.column("creationDate", .datetime)
t.column("name", .text)
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("authorId", .integer)
.notNull()
.indexed()
.references("author", onDelete: .cascade)
t.column("title", .text).notNull()
}
}
// 2nd migration
migrator.registerMigration("AddBirthYearToAuthors") { db in
try db.alter(table: "author") { t
t.add(column: "birthYear", .integer)
}
}
```
To migrate a database, open a connection (see <doc:DatabaseConnections>), and call the ``DatabaseMigrator/migrate(_:)`` method:
```swift
let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
// Migrate the database up to the latest version
try migrator.migrate(dbQueue)
```
You can also migrate a database up to a specific version (useful for testing):
```swift
try migrator.migrate(dbQueue, upTo: "v2")
// Migrations can only run forward:
try migrator.migrate(dbQueue, upTo: "v2")
try migrator.migrate(dbQueue, upTo: "v1")
// ^ fatal error: database is already migrated beyond migration "v1"
```
When several versions of your app are deployed in the wild, you may want to perform extra checks:
```swift
try dbQueue.read { db in
// Read-only apps or extensions may want to check if the database
// lacks expected migrations:
if try migrator.hasCompletedMigrations(db) == false {
// database too old
}
// Some apps may want to check if the database
// contains unknown (future) migrations:
if try migrator.hasBeenSuperseded(db) {
// database too new
}
}
```
**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 ``DatabaseMigrator/migrate(_:)``.
**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 <doc:Migrations#Foreign-Key-Checks> below for more information.
**The memory of applied migrations is stored in the database itself** (in a reserved table).
## Good Practices for Defining Migrations
**A good migration is a migration that you never modify once it has shipped.**
It is must easier to control the schema of all databases deployed on your users' devices when migrations define a stable timeline of schema versions. For this reason, make sure your the definition of your migrations define tables and columns with **strings**:
```swift
migrator.registerMigration("createLibrary") { db in
// 👍 RECOMMENDED
try db.create(table: "author") { t in
t.autoIncrementedPrimaryKey("id")
...
}
// 👎 NOT RECOMMENDED
try db.create(table: Author.databaseTableName) { t in
t.autoIncrementedPrimaryKey(Author.Columns.id.name)
...
}
}
```
Migrations should talk to the database, only to the database, and use the database language: **strings**. This makes sure you will never have to change the Swift code of your migrations in the future.
Migrations and the rest of the application code do not live at the same "moment". Migrations describe the past states of the database, while the rest of the application code targets the latest one. This difference is the reason why repeating a column name in a migration and in a Swift struct or class is a good practice. It is not a violation of the [DRY principle](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself).
## The eraseDatabaseOnSchemaChange Option
A `DatabaseMigrator` can automatically wipe out the full database content, and recreate the whole database from scratch, if it detects that migrations have changed their definition.
Setting ``DatabaseMigrator/eraseDatabaseOnSchemaChange`` is useful during application development, as you are still designing migrations, and the schema changes often:
- A migration is removed, or renamed.
- A schema change is detected: any difference in the `sqlite_master` table, which contains the SQL used to create database tables, indexes, triggers, and views.
> Warning: This option can destroy your precious users' data!
It is recommended that this option does not ship in the released application. Hide it behind `#if DEBUG`:
```swift
var migrator = DatabaseMigrator()
#if DEBUG
// Speed up development by nuking the database when migrations change
migrator.eraseDatabaseOnSchemaChange = true
#endif
```
## Advanced Database Schema Changes
SQLite directly supports a [limited set of schema alterations](https://www.sqlite.org/lang.html). Many of them are available as `Database` methods such as ``Database/create(table:options:body:)``, etc.
> You should prefer the Swift API, because GRDB only enables apis that are available on SQLite version that ships on your target operating system.
Arbitrary changes to the schema design of any table are still possible, by recreating the table. For example:
```swift
migrator.registerMigration("Add NOT NULL check on author.name") { db in
try db.create(table: "new_author") { t in
t.autoIncrementedPrimaryKey("id")
t.column("creationDate", .datetime)
t.column("name", .text).notNull()
}
try db.execute(sql: "INSERT INTO new_author SELECT * FROM author")
try db.drop(table: "author")
try db.rename(table: "new_author", to: "author")
}
```
This technique is described in the [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes) section of the SQLite documentation.
The detailed sequence of operations for recreating a database table is:
1. Remember the format of all indexes, triggers, and views associated with table X. This information will be needed in step 5 below. One way to do this is to run a query like the following: `SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'`.
2. 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.
2. Transfer content from X into new_X using a statement like: `INSERT INTO new_X SELECT ... FROM X`.
3. Drop the old table X: `DROP TABLE X`.
4. Change the name of new_X to X using: `ALTER TABLE new_X RENAME TO X`.
5. 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.
6. 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`.
> Warning: Be sure to follow the above procedure exactly, in the given order, or you might corrupt triggers, views, and foreign key constraints.
## Foreign Key Checks
The technique described in the previous <doc:Migrations#Advanced-Database-Schema-Changes> chapter creates very undesired churn w.r.t. foreign keys:
by default, each migration temporarily disables foreign keys, and performs a full check of all foreign keys in your database before it is committed on disk.
When your database becomes very big, those checks may have a noticeable impact on migration performances. You'll know this by instrumenting your migrations, and looking for the time spent in the `checkForeignKeys` method.
You can make those migrations faster, but this requires a little care.
**Your first mitigation technique is immediate foreign key checks.**
When you register a migration with `.immediate` foreign key checks, the migration does not temporarily disable foreign keys, and does not need to perform a deferred full check of all foreign keys in your database:
```swift
migrator.registerMigration("Faster migration", foreignKeyChecks: .immediate) { db in ... }
```
Such a migration is much faster, and it still guarantees database integrity. But it must only execute schema alterations directly supported by SQLite. Migrations that recreate tables as described in <doc:Migrations#Advanced-Database-Schema-Changes> **must not** run with immediate foreign keys checks. 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:
```swift
migrator = migrator.disablingDeferredForeignKeyChecks()
```
> Warning: When deferred foreign key checks are disabled, your app becomes responsible for preventing foreign key violations from being committed to disk!
In order to prevent foreign key violations from being committed to disk, you can:
- Register migrations with immediate foreign key checks, as long as they do not recreate tables as described in <doc:Migrations#Advanced-Database-Schema-Changes>:
```swift
migrator = migrator.disablingDeferredForeignKeyChecks()
migrator.registerMigration("Checked migration ✅", foreignKeyChecks: .immediate) { db in ... }
```
- Perform foreign key checks on some tables only, at the end of a migration:
```swift
migrator = migrator.disablingDeferredForeignKeyChecks()
migrator.registerMigration("Partially checked migration") { db in
...
// Throws an error and stops migrations if there exists a
// foreign key violation in the 'book' table.
try db.checkForeignKeys(in: "book")
}
```
As in the above example, check for foreign key violations with the ``Database/checkForeignKeys()`` and ``Database/checkForeignKeys(in:)`` methods. They throw a nicely detailed ``DatabaseError`` that contains a lot of debugging information:
```swift
// SQLite error 19: FOREIGN KEY constraint violation - from book(authorId) to author(id),
// in [id:1 authorId:2 name:"Moby-Dick"]
try db.checkForeignKeys(in: "book")
```
Alternatively, you can iterate a cursor of ``ForeignKeyViolation``.
## Topics
### DatabaseMigrator
- ``DatabaseMigrator``
+32 -59
View File
@@ -6,63 +6,25 @@ import Foundation
// TODO: provide concurrent apis for migrations that run @Sendable closures.
/// A `DatabaseMigrator` registers and applies database migrations.
///
/// Migrations are named blocks of database operations that are guaranteed to be
/// applied in order, once and only once.
///
/// When a migrator migrates a database, only non-applied migration are run.
///
/// Usage:
///
/// ```swift
/// // Define a DatabaseMigrator
/// var migrator = DatabaseMigrator()
///
/// // 1st migration
/// migrator.registerMigration("createLibrary") { db in
/// try db.create(table: "author") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("creationDate", .datetime)
/// t.column("name", .text).notNull()
/// }
///
/// try db.create(table: "book") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("authorId", .integer)
/// .notNull()
/// .references("author", onDelete: .cascade)
/// t.column("title", .text).notNull()
/// }
/// }
///
/// // 2nd migration
/// migrator.registerMigration("AddBirthYearToAuthors") { db in
/// try db.alter(table: "author") { t
/// t.add(column: "birthYear", .integer)
/// }
/// }
///
/// // Migrations for future versions will be inserted here:
/// //
/// // // 3rd migration
/// // migrator.registerMigration("...") { db in
/// // ...
/// // }
///
/// // Connect and migrate a database
/// let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
/// try migrator.migrate(dbQueue)
/// ```
/// For an overview of database migrations and `DatabaseMigrator` usage,
/// see <doc:Migrations>.
///
/// ## Topics
///
/// ### Creating and Configuring a DatabaseMigrator
/// ### Creating a DatabaseMigrator
///
/// - ``init()``
/// - ``eraseDatabaseOnSchemaChange``
/// - ``disablingDeferredForeignKeyChecks()``
///
/// ### Registering Migrations
///
/// - ``registerMigration(_:foreignKeyChecks:migrate:)``
/// - ``ForeignKeyChecks``
///
/// ### Configuring a DatabaseMigrator
///
/// - ``eraseDatabaseOnSchemaChange``
/// - ``disablingDeferredForeignKeyChecks()``
///
/// ### Migrating a Database
///
/// - ``asyncMigrate(_:completion:)``
@@ -81,22 +43,33 @@ import Foundation
public struct DatabaseMigrator {
/// Controls how a migration 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.
/// The migration runs with disabled foreign keys.
///
/// These deferred checks are not executed if the migrator is the
/// result of ``DatabaseMigrator/disablingDeferredForeignKeyChecks()``.
/// Foreign keys are checked right before changes are committed on disk,
/// unless the `DatabaseMigrator` is the result of
/// ``DatabaseMigrator/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>
/// In this case, you can perform your own deferred foreign key checks
/// with ``Database/checkForeignKeys(in:)`` or
/// ``Database/checkForeignKeys()``:
///
/// ```swift
/// migrator = migrator.disablingDeferredForeignKeyChecks()
/// migrator.registerMigration("Partially checked migration") { db in
/// ...
///
/// // Throws an error and stops migrations if there exists a
/// // foreign key violation in the 'book' table.
/// try db.checkForeignKeys(in: "book")
/// }
/// ```
case deferred
/// The migration runs with enabled foreign keys.
///
/// 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>
/// Immediate foreign key checks are NOT compatible with migrations that
/// recreate tables as described
/// in <doc:Migrations#Advanced-Database-Schema-Changes>.
case immediate
}
+3 -3
View File
@@ -4687,7 +4687,7 @@ try db.alter(table: "player") { t in
}
```
> **Note**: SQLite restricts the possible table alterations, and may require you to recreate dependent triggers or views. See the documentation of the [ALTER TABLE](https://www.sqlite.org/lang_altertable.html) for details. See [Advanced Database Schema Changes](Documentation/Migrations.md#advanced-database-schema-changes) for a way to lift restrictions.
> **Note**: SQLite restricts the possible table alterations, and may require you to recreate dependent triggers or views. See the documentation of the [ALTER TABLE](https://www.sqlite.org/lang_altertable.html) for details.
### Drop Tables
@@ -8713,7 +8713,7 @@ This chapter has [moved](Documentation/FullTextSearch.md).
#### Migrations
This chapter has [moved](Documentation/Migrations.md).
This chapter has [moved](http://groue.github.io/GRDB.swift/docs/6.3/documentation/grdb/migrations).
#### NSNumber and NSDecimalNumber
@@ -8792,7 +8792,7 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests].
[Fetching from Requests]: #fetching-from-requests
[Embedding SQL in Query Interface Requests]: #embedding-sql-in-query-interface-requests
[Full-Text Search]: Documentation/FullTextSearch.md
[Migrations]: Documentation/Migrations.md
[Migrations]: http://groue.github.io/GRDB.swift/docs/6.3/documentation/grdb/migrations
[The Implicit RowID Primary Key]: #the-implicit-rowid-primary-key
[The userInfo Dictionary]: #the-userinfo-dictionary
[JSON Columns]: #json-columns