diff --git a/CHANGELOG.md b/CHANGELOG.md index d99c788ab..73dfe2ef4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,9 @@ Release Notes - The Record class no longer adopts CustomStringConvertible. This frees the `description` identifier for your record properties. Fixes [#58](https://github.com/groue/GRDB.swift/issues/58). +- Several database connections can now be used at the same time: you can move values from one database to another. Fixes [#55](https://github.com/groue/GRDB.swift/issues/55). + + **Breaking Changes** - The maximum number of reader connections in a database pool is now configured in a Configuration object. diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index bbbfa7223..aaa833414 100644 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -362,6 +362,16 @@ 569531351C919DF200CF1A2B /* DatabasePoolCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531331C919DF200CF1A2B /* DatabasePoolCollationTests.swift */; }; 569531371C919DF700CF1A2B /* DatabasePoolFunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */; }; 569531381C919DF700CF1A2B /* DatabasePoolFunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */; }; + 569C1EAC1CF07CCA0042627B /* DatabaseScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EAB1CF07CCA0042627B /* DatabaseScheduler.swift */; }; + 569C1EAD1CF07CCA0042627B /* DatabaseScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EAB1CF07CCA0042627B /* DatabaseScheduler.swift */; }; + 569C1EAE1CF07CCA0042627B /* DatabaseScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EAB1CF07CCA0042627B /* DatabaseScheduler.swift */; }; + 569C1EAF1CF07CCA0042627B /* DatabaseScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EAB1CF07CCA0042627B /* DatabaseScheduler.swift */; }; + 569C1EB21CF07DDD0042627B /* DatabaseSchedulerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* DatabaseSchedulerTests.swift */; }; + 569C1EB31CF07DDD0042627B /* DatabaseSchedulerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* DatabaseSchedulerTests.swift */; }; + 569C1EB41CF07DDD0042627B /* DatabaseSchedulerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* DatabaseSchedulerTests.swift */; }; + 569C1EB51CF07DDD0042627B /* DatabaseSchedulerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* DatabaseSchedulerTests.swift */; }; + 569C1EB61CF07DDD0042627B /* DatabaseSchedulerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* DatabaseSchedulerTests.swift */; }; + 569C1EB71CF07DDD0042627B /* DatabaseSchedulerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* DatabaseSchedulerTests.swift */; }; 56A238371B9C74A90082EB20 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238131B9C74A90082EB20 /* DatabaseTests.swift */; }; 56A238381B9C74A90082EB20 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238131B9C74A90082EB20 /* DatabaseTests.swift */; }; 56A238391B9C74A90082EB20 /* InMemoryDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238141B9C74A90082EB20 /* InMemoryDatabaseTests.swift */; }; @@ -916,6 +926,8 @@ 569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolSchemaCacheTests.swift; sourceTree = ""; }; 569531331C919DF200CF1A2B /* DatabasePoolCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolCollationTests.swift; sourceTree = ""; }; 569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolFunctionTests.swift; sourceTree = ""; }; + 569C1EAB1CF07CCA0042627B /* DatabaseScheduler.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseScheduler.swift; sourceTree = ""; }; + 569C1EB11CF07DDD0042627B /* DatabaseSchedulerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSchedulerTests.swift; sourceTree = ""; }; 56A238131B9C74A90082EB20 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = ""; }; 56A238141B9C74A90082EB20 /* InMemoryDatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InMemoryDatabaseTests.swift; sourceTree = ""; }; 56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseErrorTests.swift; sourceTree = ""; }; @@ -1349,6 +1361,14 @@ path = Public; sourceTree = ""; }; + 569C1EB01CF07DC80042627B /* DatabaseScheduler */ = { + isa = PBXGroup; + children = ( + 569C1EB11CF07DDD0042627B /* DatabaseSchedulerTests.swift */, + ); + path = DatabaseScheduler; + sourceTree = ""; + }; 56A238111B9C74A90082EB20 /* Core */ = { isa = PBXGroup; children = ( @@ -1357,6 +1377,7 @@ 56A238151B9C74A90082EB20 /* DatabaseError */, 560A37A91C90084600949E71 /* DatabasePool */, 563363BB1C93FD32000BE133 /* DatabaseQueue */, + 569C1EB01CF07DC80042627B /* DatabaseScheduler */, 560B3FA41C19DFF800C58EC7 /* Persistable */, 56EA86921C91DFDA002BB4DF /* DatabaseReader */, 56A238171B9C74A90082EB20 /* DatabaseValue */, @@ -1467,6 +1488,7 @@ 56A238731B9C75030082EB20 /* DatabaseError.swift */, 560A37A31C8F625000949E71 /* DatabasePool.swift */, 56A238741B9C75030082EB20 /* DatabaseQueue.swift */, + 569C1EAB1CF07CCA0042627B /* DatabaseScheduler.swift */, 563363BF1C942C04000BE133 /* DatabaseReader.swift */, 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */, 563363D71C95787F000BE133 /* DatabaseStore.swift */, @@ -2227,6 +2249,7 @@ 560FC52A1CB003810014AA8E /* DatabaseError.swift in Sources */, 560FC52B1CB003810014AA8E /* DatabaseValue.swift in Sources */, 560FC52C1CB003810014AA8E /* SQLOperator.swift in Sources */, + 569C1EAD1CF07CCA0042627B /* DatabaseScheduler.swift in Sources */, 560FC52D1CB003810014AA8E /* StatementArguments+Foundation.swift in Sources */, 560FC52E1CB003810014AA8E /* Record.swift in Sources */, 560FC52F1CB003810014AA8E /* DatabaseCoder.swift in Sources */, @@ -2264,6 +2287,7 @@ 560FC5621CB00B880014AA8E /* Record+QueryInterfaceRequestTests.swift in Sources */, 560FC5641CB00B880014AA8E /* DatabaseQueueConcurrencyTests.swift in Sources */, 560FC5B21CB031E30014AA8E /* SQLiteStatementConvertibleFetchTests.swift in Sources */, + 569C1EB31CF07DDD0042627B /* DatabaseSchedulerTests.swift in Sources */, 560FC5651CB00B880014AA8E /* PrimaryKeyNoneTests.swift in Sources */, 560FC5661CB00B880014AA8E /* MinimalPrimaryKeyRowIDTests.swift in Sources */, 560FC5671CB00B880014AA8E /* DictionaryRowTests.swift in Sources */, @@ -2378,6 +2402,7 @@ 567156311CB16729007DC145 /* RecordFetchTests.swift in Sources */, 567156321CB16729007DC145 /* DatabasePoolFunctionTests.swift in Sources */, 567156341CB16729007DC145 /* DetachedRowTests.swift in Sources */, + 569C1EB41CF07DDD0042627B /* DatabaseSchedulerTests.swift in Sources */, 567156351CB16729007DC145 /* DatabaseQueueSchemaCacheTests.swift in Sources */, 567156361CB16729007DC145 /* MetalRowTests.swift in Sources */, 567156371CB16729007DC145 /* PrimaryKeyMultipleTests.swift in Sources */, @@ -2452,6 +2477,7 @@ 56AFC9FF1CB1A8BB00F48B96 /* DatabaseValueConvertible.swift in Sources */, 56AFCA001CB1A8BB00F48B96 /* Record.swift in Sources */, 56AFCA011CB1A8BB00F48B96 /* SQLOperator.swift in Sources */, + 569C1EAF1CF07CCA0042627B /* DatabaseScheduler.swift in Sources */, 56AFCA021CB1A8BB00F48B96 /* StatementArguments+Foundation.swift in Sources */, 56AFCA031CB1A8BB00F48B96 /* TableMapping.swift in Sources */, 56AFCA041CB1A8BB00F48B96 /* DatabaseCoder.swift in Sources */, @@ -2489,6 +2515,7 @@ 56AFCA321CB1AA9900F48B96 /* DatabaseQueueConcurrencyTests.swift in Sources */, 56AFCA331CB1AA9900F48B96 /* MinimalPrimaryKeyRowIDTests.swift in Sources */, 56AFCA341CB1AA9900F48B96 /* DictionaryRowTests.swift in Sources */, + 569C1EB61CF07DDD0042627B /* DatabaseSchedulerTests.swift in Sources */, 56AFCA351CB1AA9900F48B96 /* DatabaseCoderTests.swift in Sources */, 56AFCA361CB1AA9900F48B96 /* CollationTests.swift in Sources */, 56AFCA371CB1AA9900F48B96 /* SQLiteStatementConvertibleFetchTests.swift in Sources */, @@ -2587,6 +2614,7 @@ 56AFCA9D1CB1ABC800F48B96 /* DetachedRowTests.swift in Sources */, 56AFCA9E1CB1ABC800F48B96 /* DatabaseQueueSchemaCacheTests.swift in Sources */, 56AFCA9F1CB1ABC800F48B96 /* PrimaryKeyMultipleTests.swift in Sources */, + 569C1EB71CF07DDD0042627B /* DatabaseSchedulerTests.swift in Sources */, 56AFCAA01CB1ABC800F48B96 /* MetalRowTests.swift in Sources */, 56AFCAA21CB1ABC800F48B96 /* StatementArgumentsTests.swift in Sources */, 56AFCAA31CB1ABC800F48B96 /* RecordInitializersTests.swift in Sources */, @@ -2661,6 +2689,7 @@ 560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */, 56A238A51B9C753B0082EB20 /* Record.swift in Sources */, 5605F1921C6B1A8700235C62 /* SQLOperator.swift in Sources */, + 569C1EAE1CF07CCA0042627B /* DatabaseScheduler.swift in Sources */, 5605F1701C672E4000235C62 /* StatementArguments+Foundation.swift in Sources */, 560D924C1C672C4B00F4F92B /* TableMapping.swift in Sources */, 5605F15C1C672E4000235C62 /* DatabaseCoder.swift in Sources */, @@ -2698,6 +2727,7 @@ 563363BE1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */, 56A238501B9C74A90082EB20 /* MinimalPrimaryKeyRowIDTests.swift in Sources */, 56A238461B9C74A90082EB20 /* DictionaryRowTests.swift in Sources */, + 569C1EB51CF07DDD0042627B /* DatabaseSchedulerTests.swift in Sources */, 56B7F4381BE4C11200E39BBF /* DatabaseCoderTests.swift in Sources */, 564A50C81BFF4B7F00B3A3A2 /* CollationTests.swift in Sources */, 56E8CE111BB4FE5B00828BEC /* SQLiteStatementConvertibleFetchTests.swift in Sources */, @@ -2777,6 +2807,7 @@ 563363BD1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */, 56A238551B9C74A90082EB20 /* PrimaryKeyNoneTests.swift in Sources */, 56A2384F1B9C74A90082EB20 /* MinimalPrimaryKeyRowIDTests.swift in Sources */, + 569C1EB21CF07DDD0042627B /* DatabaseSchedulerTests.swift in Sources */, 56A238451B9C74A90082EB20 /* DictionaryRowTests.swift in Sources */, 56A238491B9C74A90082EB20 /* SelectStatementTests.swift in Sources */, 56B7F4371BE4C11200E39BBF /* DatabaseCoderTests.swift in Sources */, @@ -2869,6 +2900,7 @@ 56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */, 56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */, 5605F1911C6B1A8700235C62 /* SQLOperator.swift in Sources */, + 569C1EAC1CF07CCA0042627B /* DatabaseScheduler.swift in Sources */, 5605F16F1C672E4000235C62 /* StatementArguments+Foundation.swift in Sources */, 56A238A41B9C753B0082EB20 /* Record.swift in Sources */, 5605F15B1C672E4000235C62 /* DatabaseCoder.swift in Sources */, diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 4d234e33f..911811814 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -47,7 +47,7 @@ public final class Database { /// /// For more detailed information, see https://www.sqlite.org/c3ref/last_insert_rowid.html public var lastInsertedRowID: Int64 { - preconditionValidQueue() + DatabaseScheduler.preconditionValidQueue(self) return sqlite3_last_insert_rowid(sqliteConnection) } @@ -56,7 +56,7 @@ public final class Database { /// /// For more detailed information, see https://www.sqlite.org/c3ref/changes.html public var changesCount: Int { - preconditionValidQueue() + DatabaseScheduler.preconditionValidQueue(self) return Int(sqlite3_changes(sqliteConnection)) } @@ -66,7 +66,7 @@ public final class Database { /// /// For more detailed information, see https://www.sqlite.org/c3ref/total_changes.html public var totalChangesCount: Int { - preconditionValidQueue() + DatabaseScheduler.preconditionValidQueue(self) return Int(sqlite3_total_changes(sqliteConnection)) } @@ -97,10 +97,6 @@ public final class Database { /// See setupBusyMode() private var busyCallback: BusyCallback? - /// The value for the dispatch queue specific that holds the Database identity. - /// See preconditionValidQueue. - var dispatchQueueID: UnsafeMutablePointer = nil - init(path: String, configuration: Configuration, schemaCache: DatabaseSchemaCacheType) throws { // See https://www.sqlite.org/c3ref/open.html var sqliteConnection: SQLiteConnection = nil @@ -135,10 +131,12 @@ public final class Database { self.sqliteConnection = sqliteConnection configuration.SQLiteConnectionDidOpen?() - - // Setup trace first, so that all queries, including initialization queries, are traced. + } + + /// This method must be called after database initialization + func setup() throws { + // Setup trace first, so that setup queries are traced. setupTrace() - try setupForeignKeys() setupBusyMode() setupDefaultFunctions() @@ -147,7 +145,7 @@ public final class Database { private var isClosed: Bool = false func close() { - preconditionValidQueue() + DatabaseScheduler.preconditionValidQueue(self) assert(!isClosed) configuration.SQLiteConnectionWillClose?(sqliteConnection) @@ -336,21 +334,6 @@ public enum BusyMode { } -// ========================================================================= -// MARK: - SerializedDatabase Support - -extension Database { - - /// The key for the dispatch queue specific that holds the Database identity. - /// See preconditionValidQueue. - static let dispatchQueueIDKey = unsafeBitCast(Database.self, UnsafePointer.self) // some unique pointer - - func preconditionValidQueue(@autoclosure message: () -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) { - GRDBPrecondition(dispatchQueueID == nil || dispatchQueueID == dispatch_get_specific(Database.dispatchQueueIDKey), message, file: file, line: line) - } -} - - // ========================================================================= // MARK: - Statements @@ -427,7 +410,7 @@ extension Database { /// - arguments: Optional statement arguments. /// - throws: A DatabaseError whenever an SQLite error occurs. public func execute(sql: String, arguments: StatementArguments? = nil) throws { - preconditionValidQueue() + DatabaseScheduler.preconditionValidQueue(self) // The tricky part is to consume arguments as statements are executed. // @@ -782,7 +765,7 @@ extension Database { /// You may need to clear the cache manually if the database schema is /// modified by another connection. public func clearSchemaCache() { - preconditionValidQueue() + DatabaseScheduler.preconditionValidQueue(self) schemaCache.clear() // We also clear updateStatementCache and selectStatementCache despite @@ -795,7 +778,7 @@ extension Database { /// Returns whether a table exists. public func tableExists(tableName: String) -> Bool { - preconditionValidQueue() + DatabaseScheduler.preconditionValidQueue(self) // SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html) return Row.fetchOne(self, @@ -1123,7 +1106,7 @@ extension Database { /// The transaction observer is weakly referenced: it is not retained, and /// stops getting notifications after it is deallocated. public func addTransactionObserver(transactionObserver: TransactionObserverType) { - preconditionValidQueue() + DatabaseScheduler.preconditionValidQueue(self) transactionObservers.append(WeakTransactionObserver(transactionObserver)) if transactionObservers.count == 1 { installTransactionObserverHooks() @@ -1132,7 +1115,7 @@ extension Database { /// Remove a transaction observer. public func removeTransactionObserver(transactionObserver: TransactionObserverType) { - preconditionValidQueue() + DatabaseScheduler.preconditionValidQueue(self) transactionObservers.removeFirst { $0.observer === transactionObserver } if transactionObservers.isEmpty { uninstallTransactionObserverHooks() diff --git a/GRDB/Core/DatabaseScheduler.swift b/GRDB/Core/DatabaseScheduler.swift new file mode 100644 index 000000000..bfb582035 --- /dev/null +++ b/GRDB/Core/DatabaseScheduler.swift @@ -0,0 +1,144 @@ +/// DatabaseScheduler makes sure that databases are used on correct dispatch +/// queues. +/// +/// It has three entry points: +/// +/// - DatabaseScheduler.makeSerializedQueueAllowing(database:) creates a +/// dispatch queue that allows one database. +/// +/// It does so by registering one instance of DatabaseScheduler as a specific +/// of the dispatch queue, a DatabaseScheduler that allows that database. +/// +/// - The dispatchSync() function helps using several databases in the same +/// dispatch queue. It does so by temporarily extending the allowed databases +/// in the dispatch queue when it is called from a dispatch queue that already +/// allows some databases. +/// +/// - preconditionValidQueue() crashes whenever a database is used in an invalid +/// dispatch queue. +class DatabaseScheduler { + private static let specificKey = unsafeBitCast(DatabaseScheduler.self, UnsafePointer.self) // some unique pointer + private var allowedSerializedDatabases: [Database] + + private init(allowedSerializedDatabase database: Database) { + allowedSerializedDatabases = [database] + } + + static func makeSerializedQueueAllowing(database database: Database) -> dispatch_queue_t { + let queue = dispatch_queue_create("GRDB.SerializedDatabase", nil) + let scheduler = DatabaseScheduler(allowedSerializedDatabase: database) + let unmanagedScheduler = Unmanaged.passRetained(scheduler) + let schedulerPointer = unsafeBitCast(unmanagedScheduler, UnsafeMutablePointer.self) + dispatch_queue_set_specific(queue, DatabaseScheduler.specificKey, schedulerPointer, destroyDatabaseScheduler) + return queue + } + + static func dispatchSync(queue: dispatch_queue_t, database: Database, block: (db: Database) throws -> T) rethrows -> T { + if let sourceScheduler = currentScheduler() { + // We're in a queue where some databases are allowed. + // + // First things first: forbid reentrancy. + // + // Reentrancy looks nice at first sight: + // + // dbQueue.inDatabase { db in + // dbQueue.inDatabase { db in + // // Look, ma! I'm reentrant! + // } + // } + // + // But it does not survive this code, which deadlocks: + // + // let queue = dispatch_queue_create("...", nil) + // dbQueue.inDatabase { db in + // dispatch_sync(queue) { + // dbQueue.inDatabase { db in + // // Never run + // } + // } + // } + // + // I try not to ship half-baked solutions, so until a robust + // solution is found to this problem, I prefer discouraging + // reentrancy altogether, hoping that users will learn and avoid + // the deadlock pattern. + GRDBPrecondition(!sourceScheduler.allows(database), "Database methods are not reentrant.") + + // Now let's enter the new queue, and temporarily allow the + // currently allowed databases inside. + // + // The impl function helps us turn dispatch_sync into a rethrowing function + func impl(queue: dispatch_queue_t, database: Database, block: (db: Database) throws -> T, onError: (ErrorType) throws -> ()) rethrows -> T { + var result: T? = nil + var blockError: ErrorType? = nil + dispatch_sync(queue) { + let targetScheduler = currentScheduler()! + assert(targetScheduler.allowedSerializedDatabases[0] === database) // sanity check + + do { + let backup = targetScheduler.allowedSerializedDatabases + targetScheduler.allowedSerializedDatabases.appendContentsOf(sourceScheduler.allowedSerializedDatabases) + defer { + targetScheduler.allowedSerializedDatabases = backup + } + result = try block(db: database) + } catch { + blockError = error + } + } + if let blockError = blockError { + try onError(blockError) + } + return result! + } + return try impl(queue, database: database, block: block, onError: { throw $0 }) + } else { + // We're in a queue where no database is allowed: just dispatch + // block to queue. + // + // The impl function helps us turn dispatch_sync into a rethrowing function + func impl(queue: dispatch_queue_t, database: Database, block: (db: Database) throws -> T, onError: (ErrorType) throws -> ()) rethrows -> T { + var result: T? = nil + var blockError: ErrorType? = nil + dispatch_sync(queue) { + do { + result = try block(db: database) + } catch { + blockError = error + } + } + if let blockError = blockError { + try onError(blockError) + } + return result! + } + return try impl(queue, database: database, block: block, onError: { throw $0 }) + } + } + + static func preconditionValidQueue(db: Database, @autoclosure _ message: () -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) { + GRDBPrecondition(currentScheduler()?.allows(db) ?? false, message, file: file, line: line) + } + + private func allows(db: Database) -> Bool { + return allowedSerializedDatabases.contains { $0 === db } + } + + private static func currentScheduler() -> DatabaseScheduler? { + return scheduler(from: dispatch_get_specific(specificKey)) + } + + private static func scheduler(from schedulerPointer: UnsafeMutablePointer) -> DatabaseScheduler? { + guard schedulerPointer != nil else { + return nil + } + let unmanagedScheduler = unsafeBitCast(schedulerPointer, Unmanaged.self) + return unmanagedScheduler.takeUnretainedValue() + } +} + +/// Destructor for dispatch_queue_set_specific +private func destroyDatabaseScheduler(schedulerPointer: UnsafeMutablePointer) { + let unmanagedScheduler = unsafeBitCast(schedulerPointer, Unmanaged.self) + unmanagedScheduler.release() +} diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index a680e6792..d87e7848f 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -35,12 +35,10 @@ final class SerializedDatabase { config.threadingMode = .MultiThread db = try Database(path: path, configuration: config, schemaCache: schemaCache) - queue = dispatch_queue_create("GRDB.SerializedDatabase", nil) - - // Activate database.preconditionValidQueue() - let dispatchQueueID = unsafeBitCast(db, UnsafeMutablePointer.self) - dispatch_queue_set_specific(queue, Database.dispatchQueueIDKey, dispatchQueueID, nil) - db.dispatchQueueID = dispatchQueueID + queue = DatabaseScheduler.makeSerializedQueueAllowing(database: db) + try dispatchSync(queue) { + try self.db.setup() + } } deinit { @@ -54,34 +52,7 @@ final class SerializedDatabase { /// /// This method is *not* reentrant. func performSync(block: (db: Database) throws -> T) rethrows -> T { - // This method is NOT reentrant. - // - // Avoiding dispatch_sync and calling block() right away if the specific - // is currently self.dispatchQueueID looks like a promising solution: - // - // serializedDatabase.inDatabase { db in - // serializedDatabase.inDatabase { db in - // // Look, ma! I'm reentrant! - // } - // } - // - // However it does not survive this code, which deadlocks: - // - // let queue = dispatch_queue_create("...", nil) - // serializedDatabase.inDatabase { db in - // dispatch_sync(queue) { - // serializedDatabase.inDatabase { db in - // // Never run - // } - // } - // } - // - // I try not to ship half-baked solutions, so until a complete solution - // is found to this problem, I prefer discouraging reentrancy. - GRDBPrecondition(db.dispatchQueueID != dispatch_get_specific(Database.dispatchQueueIDKey), "Database methods are not reentrant.") - return try dispatchSync(queue) { - try block(db: self.db) - } + return try DatabaseScheduler.dispatchSync(queue, database: db, block: block) } /// Asynchronously executes a block in the serialized dispatch queue. @@ -101,6 +72,6 @@ final class SerializedDatabase { /// Fatal error if current dispatch queue is not valid. func preconditionValidQueue(@autoclosure message: () -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) { - db.preconditionValidQueue(message, file: file, line: line) + DatabaseScheduler.preconditionValidQueue(db, message, file: file, line: line) } } diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 3de1bf266..3089edfc0 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -38,7 +38,7 @@ public class Statement { } private init(database: Database, sql: String, observer: StatementCompilationObserver) throws { - database.preconditionValidQueue() + DatabaseScheduler.preconditionValidQueue(database) observer.start() defer { observer.stop() } @@ -326,7 +326,7 @@ public struct DatabaseSequence: SequenceType { private init(statement: SelectStatement, element: () -> Element) { self.generateImpl = { // Check that generator is built on a valid queue. - statement.database.preconditionValidQueue("Database was not used on the correct thread. Iterate sequences in a protected dispatch queue, or consider using an array returned by fetchAll() instead.") + DatabaseScheduler.preconditionValidQueue(statement.database, "Database was not used on the correct thread. Iterate sequences in a protected dispatch queue, or consider using an array returned by fetchAll() instead.") // Support multiple sequence iterations try statement.reset() @@ -353,7 +353,7 @@ public struct DatabaseSequence: SequenceType { // to be used on the database queue. return DatabaseSequence() { // Check that generator is built on a valid queue. - database.preconditionValidQueue("Database was not used on the correct thread. Iterate sequences in a protected dispatch queue, or consider using an array returned by fetchAll() instead.") + DatabaseScheduler.preconditionValidQueue(database, "Database was not used on the correct thread. Iterate sequences in a protected dispatch queue, or consider using an array returned by fetchAll() instead.") return DatabaseGenerator() } } @@ -438,7 +438,7 @@ public final class UpdateStatement : Statement { /// - parameter arguments: Statement arguments. /// - throws: A DatabaseError whenever an SQLite error occurs. public func execute(arguments arguments: StatementArguments? = nil) throws { - database.preconditionValidQueue() + DatabaseScheduler.preconditionValidQueue(database) // Force arguments validity. See SelectStatement.fetchSequence(), and Database.execute() try! prepareWithArguments(arguments) diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index f944d39be..bdeb14d41 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/Persistable.swift @@ -323,7 +323,7 @@ extension MutablePersistable { /// /// - throws: A DatabaseError if table does not exist. static func primaryKeyFunction(db: Database) throws -> (Self) -> [String: DatabaseValue] { - db.preconditionValidQueue() + DatabaseScheduler.preconditionValidQueue(db) let columns = try db.primaryKey(databaseTableName()).columns return { record in let dictionary = record.persistentDictionary diff --git a/Tests/GRDBTestCase.swift b/Tests/GRDBTestCase.swift index 57c7bd61d..be4c44467 100644 --- a/Tests/GRDBTestCase.swift +++ b/Tests/GRDBTestCase.swift @@ -108,7 +108,7 @@ class GRDBTestCase: XCTestCase { do { try NSFileManager.defaultManager().removeItemAtPath(dbDirectoryPath) } catch { } } - func assertNoError(file: StaticString = #file, line: UInt = #line, @noescape test: (Void) throws -> Void) { + func assertNoError(file: StaticString = #file, line: UInt = #line, @noescape _ test: (Void) throws -> Void) { do { try test() } catch { diff --git a/Tests/Public/Core/DatabaseScheduler/DatabaseSchedulerTests.swift b/Tests/Public/Core/DatabaseScheduler/DatabaseSchedulerTests.swift new file mode 100644 index 000000000..4a0326c62 --- /dev/null +++ b/Tests/Public/Core/DatabaseScheduler/DatabaseSchedulerTests.swift @@ -0,0 +1,93 @@ +import XCTest +#if SQLITE_HAS_CODEC + import GRDBCipher +#else + import GRDB +#endif + +class DatabaseSchedulerTests: GRDBTestCase { + + func testDatabaseQueueFromDatabaseQueue() { + assertNoError { + let dbQueue1 = try makeDatabaseQueue("db1") + let dbQueue2 = try makeDatabaseQueue("db2") + try dbQueue1.inDatabase { db1 in + try db1.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + try db1.execute("INSERT INTO items (id) VALUES (NULL)") + try dbQueue2.inDatabase { db2 in + try db2.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + for row in Row.fetch(db1, "SELECT * FROM items") { + try db2.execute("INSERT INTO items (id) VALUES (?)", arguments: [row.value(named: "id")]) + } + } + } + let count = dbQueue2.inDatabase { db2 in + Int.fetchOne(db2, "SELECT COUNT(*) FROM items")! + } + XCTAssertEqual(count, 1) + } + } + + func testDatabaseQueueFromDatabasePool() { + assertNoError { + let dbPool1 = try makeDatabasePool("db1") + let dbQueue2 = try makeDatabaseQueue("db2") + try dbPool1.write { db1 in + try db1.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + try db1.execute("INSERT INTO items (id) VALUES (NULL)") + try dbQueue2.inDatabase { db2 in + try db2.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + for row in Row.fetch(db1, "SELECT * FROM items") { + try db2.execute("INSERT INTO items (id) VALUES (?)", arguments: [row.value(named: "id")]) + } + } + } + let count = dbQueue2.inDatabase { db2 in + Int.fetchOne(db2, "SELECT COUNT(*) FROM items")! + } + XCTAssertEqual(count, 1) + } + } + + func testDatabasePoolFromDatabaseQueue() { + assertNoError { + let dbQueue1 = try makeDatabaseQueue("db1") + let dbPool2 = try makeDatabasePool("db2") + try dbQueue1.inDatabase { db1 in + try db1.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + try db1.execute("INSERT INTO items (id) VALUES (NULL)") + try dbPool2.write { db2 in + try db2.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + for row in Row.fetch(db1, "SELECT * FROM items") { + try db2.execute("INSERT INTO items (id) VALUES (?)", arguments: [row.value(named: "id")]) + } + } + } + let count = dbPool2.read { db2 in + Int.fetchOne(db2, "SELECT COUNT(*) FROM items")! + } + XCTAssertEqual(count, 1) + } + } + + func testDatabasePoolFromDatabasePool() { + assertNoError { + let dbPool1 = try makeDatabasePool("db1") + let dbPool2 = try makeDatabasePool("db2") + try dbPool1.write { db1 in + try db1.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + try db1.execute("INSERT INTO items (id) VALUES (NULL)") + try dbPool2.write { db2 in + try db2.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + for row in Row.fetch(db1, "SELECT * FROM items") { + try db2.execute("INSERT INTO items (id) VALUES (?)", arguments: [row.value(named: "id")]) + } + } + } + let count = dbPool2.write { db2 in + Int.fetchOne(db2, "SELECT COUNT(*) FROM items")! + } + XCTAssertEqual(count, 1) + } + } +}