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()
// 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
// ...
// }
try migrator.migrate(dbQueue)
-
A new migrator.
Declaration
Swift
public init()
-
Registers a migration.
migrator.registerMigration("createAuthors") { db in try db.create(table: "author") { t in t.autoIncrementedPrimaryKey("id") t.column("creationDate", .datetime) t.column("name", .text).notNull() } }
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 mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void)
-
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(_ writer: DatabaseWriter) throws
Parameters
db
A DatabaseWriter (DatabaseQueue or DatabasePool) where migrations should apply.
-
Iterate migrations in the same order as they were registered, up to the provided target. If a migration has not yet been applied, its block is executed in a transaction.
- targetIdentifier: The identifier of a registered migration.
Throws
An eventual error thrown by the registered migration blocks.Declaration
Swift
public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws
Parameters
db
A DatabaseWriter (DatabaseQueue or DatabasePool) where migrations should apply.
-
Returns the set of applied migration identifiers.
Declaration
Swift
public func appliedMigrations(in reader: DatabaseReader) throws -> Set<String>