diff --git a/GRDB Tests/DatabaseTests.swift b/GRDB Tests/DatabaseTests.swift index 956ef5501..ff74e8bc2 100644 --- a/GRDB Tests/DatabaseTests.swift +++ b/GRDB Tests/DatabaseTests.swift @@ -18,7 +18,7 @@ class DatabaseTests: XCTestCase { let configuration = DatabaseConfiguration(verbose: true) let dbQueue = try DatabaseQueue(path: "/tmp/GRDB.sqlite", configuration: configuration) - try dbQueue.inTransaction { db in + try dbQueue.inTransaction { db -> Void in let dropTableStmt = try db.updateStatement("DROP TABLE IF EXISTS persons") try dropTableStmt.execute() @@ -58,7 +58,7 @@ class DatabaseTests: XCTestCase { try insert4Stmt.execute() } - try dbQueue.inDatabase { db in + try dbQueue.inDatabase { db -> Void in let selectStmt = try db.selectStatement("SELECT * FROM persons") for row in selectStmt.fetchRows() { diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 9febbfdbd..4204a1bb6 100644 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -17,6 +17,7 @@ 5699AE5F1B42E59F00C35172 /* DBValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5699AE5E1B42E59F00C35172 /* DBValue.swift */; }; 56CC3C8F1B43A5A700A9A534 /* DatabaseQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC3C8E1B43A5A700A9A534 /* DatabaseQueue.swift */; }; 56CC3C931B43BF0100A9A534 /* DatabaseConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC3C921B43BF0100A9A534 /* DatabaseConfiguration.swift */; }; + 56CC3C951B43C0E600A9A534 /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC3C941B43C0E600A9A534 /* DatabaseMigrator.swift */; }; DC2393C81ABE35F8003FF113 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; DC2F675E1AEA7CD600151C15 /* fts3_tokenizer.h in Headers */ = {isa = PBXBuildFile; fileRef = DC2F675D1AEA7CD600151C15 /* fts3_tokenizer.h */; }; DC3773F919C8CBB3004FCF85 /* GRDB.h in Headers */ = {isa = PBXBuildFile; fileRef = DC3773F819C8CBB3004FCF85 /* GRDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -45,6 +46,7 @@ 5699AE5E1B42E59F00C35172 /* DBValue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DBValue.swift; sourceTree = ""; }; 56CC3C8E1B43A5A700A9A534 /* DatabaseQueue.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueue.swift; sourceTree = ""; }; 56CC3C921B43BF0100A9A534 /* DatabaseConfiguration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfiguration.swift; sourceTree = ""; }; + 56CC3C941B43C0E600A9A534 /* DatabaseMigrator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMigrator.swift; sourceTree = ""; }; DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = ""; }; DC2F675D1AEA7CD600151C15 /* fts3_tokenizer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = fts3_tokenizer.h; sourceTree = ""; }; DC3773F319C8CBB3004FCF85 /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -124,6 +126,7 @@ 5699AE5E1B42E59F00C35172 /* DBValue.swift */, 565E191D1B42B2B600D32814 /* Database.swift */, 56CC3C921B43BF0100A9A534 /* DatabaseConfiguration.swift */, + 56CC3C941B43C0E600A9A534 /* DatabaseMigrator.swift */, 56CC3C8E1B43A5A700A9A534 /* DatabaseQueue.swift */, 565E191F1B42B9C000D32814 /* Error.swift */, 5699AE581B42CD7800C35172 /* Row.swift */, @@ -264,6 +267,7 @@ 5699AE571B42C34A00C35172 /* Statement.swift in Sources */, 56CC3C8F1B43A5A700A9A534 /* DatabaseQueue.swift in Sources */, 56CC3C931B43BF0100A9A534 /* DatabaseConfiguration.swift in Sources */, + 56CC3C951B43C0E600A9A534 /* DatabaseMigrator.swift in Sources */, 5699AE5D1B42D49C00C35172 /* UpdateStatement.swift in Sources */, 565E19201B42B9C000D32814 /* Error.swift in Sources */, 565E191E1B42B2B600D32814 /* Database.swift in Sources */, diff --git a/GRDB/Database.swift b/GRDB/Database.swift index f3a6bd052..e2143cb07 100644 --- a/GRDB/Database.swift +++ b/GRDB/Database.swift @@ -38,16 +38,34 @@ public class Database { } } - public func selectStatement(sql: String) throws -> SelectStatement { - return try SelectStatement(database: self, sql: sql) + public func selectStatement(sql: String, arguments: [DBValue?]? = nil) throws -> SelectStatement { + let statement = try SelectStatement(database: self, sql: sql) + if let arguments = arguments { + statement.bind(arguments) + } + return statement } - public func updateStatement(sql: String) throws -> UpdateStatement { - return try UpdateStatement(database: self, sql: sql) + public func fetchRows(sql: String, arguments: [DBValue?]? = nil) throws -> AnySequence { + let statement = try selectStatement(sql, arguments: arguments) + return statement.fetchRows() } - public func execute(sql: String) throws { - let statement = try updateStatement(sql) + public func fetchValues(type: T.Type, sql: String, arguments: [DBValue?]? = nil) throws -> AnySequence { + let statement = try selectStatement(sql, arguments: arguments) + return statement.fetchValues(type) + } + + public func updateStatement(sql: String, arguments: [DBValue?]? = nil) throws -> UpdateStatement { + let statement = try UpdateStatement(database: self, sql: sql) + if let arguments = arguments { + statement.bind(arguments) + } + return statement + } + + public func execute(sql: String, arguments: [DBValue?]? = nil) throws { + let statement = try updateStatement(sql, arguments: arguments) try statement.execute() } @@ -61,6 +79,15 @@ public class Database { throw error } } + + public func tableExist(tableName: String) -> Bool { + let statement = try! selectStatement("SELECT [sql] FROM sqlite_master WHERE [type] = 'table' AND LOWER(name) = ?") + statement.bind(tableName.lowercaseString, atIndex: 1) + for _ in statement.fetchRows() { + return true + } + return false + } private func beginTransaction(type: TransactionType = .Exclusive) throws { switch type { diff --git a/GRDB/DatabaseMigrator.swift b/GRDB/DatabaseMigrator.swift new file mode 100644 index 000000000..9df903c2c --- /dev/null +++ b/GRDB/DatabaseMigrator.swift @@ -0,0 +1,52 @@ +// +// DatabaseMigrator.swift +// GRDB +// +// Created by Gwendal Roué on 01/07/2015. +// Copyright © 2015 Gwendal Roué. All rights reserved. +// + +public struct DatabaseMigrator { + + 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)) + } + + public func migrate(dbQueue: DatabaseQueue) throws { + try setupMigrations(dbQueue) + try runMigrations(dbQueue) + } + + private struct Migration { + let identifier: String + let block: (db: Database) throws -> Void + } + + private var migrations: [Migration] = [] + + private func setupMigrations(dbQueue: DatabaseQueue) throws { + try dbQueue.inDatabase { db in + try db.execute( + "CREATE TABLE grdb_migrations IF NOT EXISTS (" + + "identifier VARCHAR(128) PRIMARY KEY NOT NULL," + + "position INT" + + ")") + } + } + + private func runMigrations(dbQueue: DatabaseQueue) throws { + try dbQueue.inTransaction { db -> Void in + let appliedMigrationIdentifiers = try db.fetchValues(String.self, sql: "SELECT identifier FROM db_migrations").map { $0! } + + for (position, migration) in self.migrations.enumerate() { + if appliedMigrationIdentifiers.indexOf(migration.identifier) == nil { + try migration.block(db: db) + try db.execute("INSERT INTO db_migrations (position, identifier) VALUES (?, ?)", arguments: [position, migration.identifier]) + } + } + } + } +} \ No newline at end of file diff --git a/GRDB/DatabaseQueue.swift b/GRDB/DatabaseQueue.swift index c3f72f60a..72ec686e3 100644 --- a/GRDB/DatabaseQueue.swift +++ b/GRDB/DatabaseQueue.swift @@ -16,27 +16,31 @@ public class DatabaseQueue { _database = try Database(path: path, configuration: configuration) } - public func inDatabase(block: (db: Database) throws -> Void) throws { + public func inDatabase(block: (db: Database) throws -> R) throws -> R { var dbError: ErrorType? + var result: R? = nil dispatch_sync(queue) { () -> Void in do { - try block(db: self.database) + result = try block(db: self.database) } catch { dbError = error } } if let dbError = dbError { throw dbError + } else { + return result! } } - public func inTransaction(type: Database.TransactionType = .Exclusive, block: (db: Database) throws -> Void) throws { + public func inTransaction(type: Database.TransactionType = .Exclusive, block: (db: Database) throws -> R) throws -> R { var dbError: ErrorType? + var result: R? = nil let database = self.database dispatch_sync(queue) { () -> Void in do { try database.inTransaction(type) { () in - try block(db: database) + result = try block(db: database) } } catch { dbError = error @@ -44,6 +48,8 @@ public class DatabaseQueue { } if let dbError = dbError { throw dbError + } else { + return result! } } } diff --git a/GRDB/Row.swift b/GRDB/Row.swift index 21cea49dc..6d24c62f0 100644 --- a/GRDB/Row.swift +++ b/GRDB/Row.swift @@ -75,6 +75,10 @@ public struct Row { } } + public func valueAtIndex(index: Int, type: T.Type) -> T? { + return nil + } + public var asDictionary: [String: DBValue?] { var dictionary = [String: DBValue?]() for index in 0..(type: T.Type) -> AnyGenerator { + let rowGenerator = self.rowGenerator + return anyGenerator { () -> T?? in + if let row = rowGenerator.next() { + return Optional.Some(row.valueAtIndex(0, type: type)) + } else { + return nil + } + } + } + // TODO: Document the reset performed on each generation public func fetchRows() -> AnySequence { return AnySequence { return self.rowGenerator } } + + public func fetchValues(type: T.Type) -> AnySequence { + return AnySequence { + return self.valueGenerator(type) + } + } }