From 78cef92c078fff92419d488d3ea900a63ea13ff8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 5 Jul 2015 07:14:13 +0200 Subject: [PATCH] Documentation WIP --- GRDB/DatabaseMigrator.swift | 59 +++++++++++++++++++++++++++++++++++-- 1 file changed, 57 insertions(+), 2 deletions(-) diff --git a/GRDB/DatabaseMigrator.swift b/GRDB/DatabaseMigrator.swift index 04f7f9b60..695c8f91c 100644 --- a/GRDB/DatabaseMigrator.swift +++ b/GRDB/DatabaseMigrator.swift @@ -22,23 +22,78 @@ // THE SOFTWARE. +/** +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, " + + "creationTimestamp DOUBLE, " + + "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) + +*/ public struct DatabaseMigrator { + /// A new migrator. public init() { } + /** + Registers a migration. + + - parameter identifier: The migration identifier. It must be unique. + - parameter block: The migration block that performs SQL statements. + */ public mutating func registerMigration(identifier: String, _ block: (db: Database) throws -> Void) { guard migrations.map({ $0.identifier }).indexOf(identifier) == nil else { fatalError("Already registered migration: \"\(identifier)\"") } migrations.append(Migration(identifier: identifier, block: block)) } - + + /** + 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. + + - parameter dbQueue: The Database Queue where migrations should apply. + */ public func migrate(dbQueue: DatabaseQueue) throws { try setupMigrations(dbQueue) try runMigrations(dbQueue) } - + + + // MARK: - Non public + private struct Migration { let identifier: String let block: (db: Database) throws -> Void