Extract SerializedDatabase from DatabaseQueue

This commit is contained in:
Gwendal Roué committed 2016-03-09 07:54:06 +01:00
1 parent d18d2a5921
commit 0091de918b
5 files changed
+121 -108

No files matched your search

+6
View File
@@ -48,6 +48,8 @@
5606AF911C0ED37000D20487 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 56BB86301BA98AB0001F9168 /* libsqlite3.tbd */; };
5607EFD31BB8254800605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; };
5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; };
560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */; };
560A37A81C8FF6E500949E71 /* SerializedDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */; };
560B3FAC1C19E01000C58EC7 /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560B3FAB1C19E01000C58EC7 /* PersistableTests.swift */; };
560B3FAD1C19E01000C58EC7 /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560B3FAB1C19E01000C58EC7 /* PersistableTests.swift */; };
560C97C71BFD0B8400BF8471 /* FunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560C97C61BFD0B8400BF8471 /* FunctionTests.swift */; };
@@ -321,6 +323,7 @@
5605F18B1C6B1A8700235C62 /* SQLOperator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperator.swift; sourceTree = "<group>"; };
5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectQuery.swift; sourceTree = "<group>"; };
5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = "<group>"; };
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerializedDatabase.swift; sourceTree = "<group>"; };
560B3FAB1C19E01000C58EC7 /* PersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableTests.swift; sourceTree = "<group>"; };
560C97C61BFD0B8400BF8471 /* FunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FunctionTests.swift; sourceTree = "<group>"; };
560C981A1C0E22D300BF8471 /* GRDBOSXPerformanceTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXPerformanceTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -758,6 +761,7 @@
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
56A238761B9C75030082EB20 /* Row.swift */,
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
56A238781B9C75030082EB20 /* Statement.swift */,
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
563445041C4A7FD7003D3DC6 /* Utils.swift */,
@@ -1284,6 +1288,7 @@
5605F1901C6B1A8700235C62 /* SQLFunction.swift in Sources */,
5605F1721C672E4000235C62 /* RawRepresentable.swift in Sources */,
563445061C4A7FD7003D3DC6 /* Utils.swift in Sources */,
560A37A81C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
56A238941B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
5605F16A1C672E4000235C62 /* NSString.swift in Sources */,
5605F16E1C672E4000235C62 /* Row+Foundation.swift in Sources */,
@@ -1454,6 +1459,7 @@
5605F18F1C6B1A8700235C62 /* SQLFunction.swift in Sources */,
5605F1711C672E4000235C62 /* RawRepresentable.swift in Sources */,
56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */,
560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
5605F1691C672E4000235C62 /* NSString.swift in Sources */,
5605F16D1C672E4000235C62 /* Row+Foundation.swift in Sources */,
560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
+18 -13
View File
@@ -41,9 +41,9 @@ public final class Database {
/// See setupBusyMode()
private var busyCallback: BusyCallback?
/// The queue from which the database can be used.
/// See preconditionValidQueue().
var databaseQueueID: DatabaseQueueID = nil
/// The value for the dispatch queue specific that holds the Database identity.
/// See preconditionValidQueue.
var databaseQueueID: UnsafeMutablePointer<Void> = nil
init(path: String, configuration: Configuration) throws {
self.configuration = configuration
@@ -63,21 +63,12 @@ public final class Database {
setupBusyMode()
}
// Initializes an in-memory database
convenience init(configuration: Configuration) {
try! self.init(path: ":memory:", configuration: configuration)
}
deinit {
if sqliteConnection != nil {
sqlite3_close(sqliteConnection)
}
}
func preconditionValidQueue() {
precondition(databaseQueueID == nil || databaseQueueID == dispatch_get_specific(DatabaseQueue.databaseQueueIDKey), "Database was not used on the correct thread: execute your statements inside DatabaseQueue.inDatabase() or DatabaseQueue.inTransaction(). If you get this error while iterating the result of a fetch() method, consider using the array returned by fetchAll() instead.")
}
private func setupForeignKeys() throws {
if configuration.foreignKeysEnabled {
try execute("PRAGMA foreign_keys = ON")
@@ -120,7 +111,6 @@ public final class Database {
}
}
/// An SQLite threading mode. See https://www.sqlite.org/threadsafe.html.
enum ThreadingMode {
case Default
@@ -183,6 +173,21 @@ public enum BusyMode {
}
// =========================================================================
// MARK: - SerializedDatabase Support
extension Database {
/// The key for the dispatch queue specific that holds the Database identity.
/// See preconditionValidQueue.
static let databaseQueueIDKey = unsafeBitCast(Database.self, UnsafePointer<Void>.self) // some unique pointer
func preconditionValidQueue() {
precondition(databaseQueueID == nil || databaseQueueID == dispatch_get_specific(Database.databaseQueueIDKey), "Database was not used on the correct thread. If you get this error while iterating the result of a fetch() method, consider using the array returned by fetchAll() instead.")
}
}
// =========================================================================
// MARK: - Statements
+15 -92
View File
@@ -7,7 +7,7 @@ public final class DatabaseQueue {
/// The database configuration
public var configuration: Configuration {
return database.configuration
return serializedDatabase.configuration
}
@@ -23,24 +23,8 @@ public final class DatabaseQueue {
/// - path: The path to the database file.
/// - configuration: A configuration.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public convenience init(path: String, var configuration: Configuration = Configuration()) throws {
// IMPLEMENTATION NOTE
//
// According to https://www.sqlite.org/threadsafe.html:
//
// > Multi-thread. In this mode, SQLite can be safely used by multiple
// > threads provided that no single database connection is used
// > simultaneously in two or more threads.
// >
// > Serialized. In serialized mode, SQLite can be safely used by
// > multiple threads with no restriction.
// >
// > The default mode is serialized.
//
// Since our database connection is only used via our serial dispatch
// queue, there is no purpose using the default serialized mode.
configuration.threadingMode = .MultiThread
try self.init(database: Database(path: path, configuration: configuration))
public convenience init(path: String, configuration: Configuration = Configuration()) throws {
try self.init(serializedDatabase: SerializedDatabase(path: path, configuration: configuration))
}
/// Opens an in-memory SQLite database.
@@ -50,9 +34,8 @@ public final class DatabaseQueue {
/// Database memory is released when the database queue gets deallocated.
///
/// - parameter configuration: A configuration.
public convenience init(var configuration: Configuration = Configuration()) {
configuration.threadingMode = .MultiThread // See IMPLEMENTATION NOTE in init(_:configuration:)
self.init(database: Database(configuration: configuration))
public convenience init(configuration: Configuration = Configuration()) {
try! self.init(serializedDatabase: SerializedDatabase(path: ":memory:", configuration: configuration))
}
@@ -69,9 +52,7 @@ public final class DatabaseQueue {
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func inDatabase(block: (db: Database) throws -> Void) rethrows {
try inQueue {
try block(db: self.database)
}
try serializedDatabase.inDatabase(block)
}
/// Synchronously executes a block in the database queue, and returns
@@ -86,9 +67,7 @@ public final class DatabaseQueue {
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func inDatabase<T>(block: (db: Database) throws -> T) rethrows -> T {
return try inQueue {
try block(db: self.database)
}
return try serializedDatabase.inDatabase(block)
}
/// Synchronously executes a block in the database queue, wrapped inside a
@@ -113,9 +92,9 @@ public final class DatabaseQueue {
/// .Commit or .Rollback.
/// - throws: The error thrown by the block.
public func inTransaction(kind: TransactionKind? = nil, block: (db: Database) throws -> TransactionCompletion) throws {
try inQueue {
try self.database.inTransaction(kind) {
try block(db: self.database)
try serializedDatabase.inDatabase { db in
try db.inTransaction(kind) {
try block(db: db)
}
}
}
@@ -123,29 +102,10 @@ public final class DatabaseQueue {
// MARK: - Not public
/// The Database
private var database: Database
/// The serialized database
private var serializedDatabase: SerializedDatabase
/// The dispatch queue
private let queue: dispatch_queue_t
/// The key for the dispatch queue specific that holds the DatabaseQueue
/// identity. See databaseQueueID.
static let databaseQueueIDKey = unsafeBitCast(DatabaseQueue.self, UnsafePointer<Void>.self) // some unique pointer
/// The value for the dispatch queue specific that holds the DatabaseQueue
/// identity.
///
/// It helps:
/// - warning the user when he wraps calls to inDatabase() or
/// inTransaction(), which would create a deadlock
/// - warning the user the he uses a statement outside of the database
/// queue.
private lazy var databaseQueueID: DatabaseQueueID = {
unsafeBitCast(self, DatabaseQueueID.self) // pointer to self
}()
init(database: Database) {
init(serializedDatabase: SerializedDatabase) {
// IMPLEMENTATION NOTE
//
// https://www.sqlite.org/isolation.html
@@ -164,44 +124,7 @@ public final class DatabaseQueue {
// > see the changes made by the UPDATE or not? The answer is that this
// > behavior is undefined.
//
// This is why we use a serial queue: to avoid UPDATE to fuck up SELECT.
self.database = database
queue = dispatch_queue_create("com.github.groue.GRDB", nil)
dispatch_queue_set_specific(queue, DatabaseQueue.databaseQueueIDKey, databaseQueueID, nil)
database.databaseQueueID = databaseQueueID
}
private func inQueue<T>(block: () throws -> T) rethrows -> T {
// IMPLEMENTATION NOTE
//
// DatabaseQueue.inDatabase() and DatabaseQueue.inTransaction() are not
// reentrant.
//
// Avoiding dispatch_sync and calling block() right away if the specific
// is currently self.databaseQueueID looks like a promising solution:
//
// dbQueue.inDatabase { db in
// dbQueue.inDatabase { db in
// // Look, ma! I'm reentrant!
// }
// }
//
// However 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 complete solution
// is found to this problem, I prefer totally disabling reentrancy.
precondition(databaseQueueID != dispatch_get_specific(DatabaseQueue.databaseQueueIDKey), "DatabaseQueue.inDatabase(_:) or DatabaseQueue.inTransaction(_:) was called reentrantly, which would lead to a deadlock.")
return try dispatchSync(queue, block: block)
// This is why we use a serialized database:
self.serializedDatabase = serializedDatabase
}
}
typealias DatabaseQueueID = UnsafeMutablePointer<Void>
+79
View File
@@ -0,0 +1,79 @@
/// A class that serializes accesses to a database.
final class SerializedDatabase {
/// The database
private let database: Database
/// The database configuration
var configuration: Configuration {
return database.configuration
}
/// The dispatch queue
private let queue: dispatch_queue_t
convenience init(path: String, configuration: Configuration = Configuration()) throws {
// According to https://www.sqlite.org/threadsafe.html
//
// > SQLite support three different threading modes:
// >
// > 1. Multi-thread. In this mode, SQLite can be safely used by
// > multiple threads provided that no single database connection is
// > used simultaneously in two or more threads.
// >
// > 2. Serialized. In serialized mode, SQLite can be safely used by
// > multiple threads with no restriction.
// >
// > [...]
// >
// > The default mode is serialized.
//
// Since our database connection is only used via our serial dispatch
// queue, there is no purpose using the default serialized mode.
var config = configuration
config.threadingMode = .MultiThread
let database = try Database(path: path, configuration: config)
self.init(database: database)
}
private init(database: Database) {
self.database = database
self.queue = dispatch_queue_create("com.github.groue.GRDB", nil)
// Activate database.preconditionValidQueue()
let databaseQueueID = unsafeBitCast(database, UnsafeMutablePointer<Void>.self)
dispatch_queue_set_specific(queue, Database.databaseQueueIDKey, databaseQueueID, nil)
database.databaseQueueID = databaseQueueID
}
func inDatabase<T>(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.databaseQueueID 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.
precondition(database.databaseQueueID != dispatch_get_specific(Database.databaseQueueIDKey), "Database methods are not reentrant.")
return try dispatchSync(queue) {
try block(db: self.database)
}
}
}
+3 -3
View File
@@ -112,7 +112,7 @@ class CrashTests: GRDBTestCase {
// MARK: - Queue
func testInDatabaseIsNotReentrant() {
assertCrash("DatabaseQueue.inDatabase(_:) or DatabaseQueue.inTransaction(_:) was called reentrantly, which would lead to a deadlock.") {
assertCrash("Database methods are not reentrant.") {
dbQueue.inDatabase { db in
self.dbQueue.inDatabase { db in
}
@@ -121,7 +121,7 @@ class CrashTests: GRDBTestCase {
}
func testInTransactionInsideInDatabaseIsNotReentrant() {
assertCrash("DatabaseQueue.inDatabase(_:) or DatabaseQueue.inTransaction(_:) was called reentrantly, which would lead to a deadlock.") {
assertCrash("Database methods are not reentrant.") {
try dbQueue.inDatabase { db in
try self.dbQueue.inTransaction { db in
return .Commit
@@ -131,7 +131,7 @@ class CrashTests: GRDBTestCase {
}
func testInTransactionIsNotReentrant() {
assertCrash("DatabaseQueue.inDatabase(_:) or DatabaseQueue.inTransaction(_:) was called reentrantly, which would lead to a deadlock.") {
assertCrash("Database methods are not reentrant.") {
try dbQueue.inTransaction { db in
try self.dbQueue.inTransaction { db in
return .Commit