DatabaseMigrator
public struct DatabaseMigrator
A DatabaseMigrator registers and applies database migrations.
Migrations are named blocks of SQL statements that are guaranteed to be applied in order, once and only once.
When a user upgrades your application, only non-applied migration are run.
Usage:
var migrator = DatabaseMigrator()
// v1.0 database
migrator.registerMigration("createPersons") { db in
try db.execute(
"CREATE TABLE persons (" +
"id INTEGER PRIMARY KEY, " +
"creationDate TEXT, " +
"name TEXT NOT NULL" +
")")
}
migrator.registerMigration("createBooks") { db in
try db.execute(
"CREATE TABLE books (" +
"uuid TEXT PRIMARY KEY, " +
"ownerID INTEGER NOT NULL " +
" REFERENCES persons(id) " +
" ON DELETE CASCADE ON UPDATE CASCADE, " +
"title TEXT NOT NULL" +
")")
}
// v2.0 database
migrator.registerMigration("AddAgeToPersons") { db in
try db.execute("ALTER TABLE persons ADD COLUMN age INT")
}
try migrator.migrate(dbQueue)
-
A new migrator.
Declaration
Swift
public init()
-
Registers a migration.
migrator.registerMigration("createPersons") { db in try db.execute( "CREATE TABLE persons (" + "id INTEGER PRIMARY KEY, " + "creationDate TEXT, " + "name TEXT NOT NULL" + ")") }
Precondition
No migration with the same same as already been registered.Declaration
Swift
public mutating func registerMigration(_ identifier: String, migrate: @escaping (Database) throws -> Void)
Parameters
identifier
The migration identifier.
block
The migration block that performs SQL statements.
-
Undocumented
Declaration
Swift
public struct DatabaseMigrator
-
Undocumented
Declaration
Swift
public struct DatabaseMigrator
-
Iterate migrations in the same order as they were registered. If a migration has not yet been applied, its block is executed in a transaction.
Throws
An eventual error thrown by the registered migration blocks.Declaration
Swift
public func migrate(_ db: DatabaseWriter) throws
Parameters
db
A DatabaseWriter (DatabaseQueue or DatabasePool) where migrations should apply.