diff --git a/CHANGELOG.md b/CHANGELOG.md index e1f80dd6f..cfc96129f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,13 @@ Release Notes ============= +## Next Release + +**New** + +- `Configuration.busyMode` let you specify how concurrent connections should handle database locking. + + ## 0.15.0 Released September 12, 2015 diff --git a/GRDB Tests/Public/Core/Concurrency/ConcurrencyTests.swift b/GRDB Tests/Public/Core/Concurrency/ConcurrencyTests.swift index 1d339e04c..1dfcdf6de 100644 --- a/GRDB Tests/Public/Core/Concurrency/ConcurrencyTests.swift +++ b/GRDB Tests/Public/Core/Concurrency/ConcurrencyTests.swift @@ -5,19 +5,32 @@ class ConcurrencyTests: XCTestCase { var databasePath: String! var dbQueue1: DatabaseQueue! var dbQueue2: DatabaseQueue! + var busyCallback: Database.BusyCallback? override func setUp() { super.setUp() databasePath = "/tmp/GRDBConcurrencyTests.sqlite" do { try NSFileManager.defaultManager().removeItemAtPath(databasePath) } catch { } - let configuration = Configuration(trace: Configuration.logSQL) + let busyCallback: Database.BusyCallback = { + if let busyCallback = self.busyCallback { + return busyCallback(numberOfTries: $0) + } else { + // Default give up + return false + } + } + let configuration = Configuration( + trace: Configuration.logSQL, + busyMode: .Callback(busyCallback)) dbQueue1 = try! DatabaseQueue(path: databasePath, configuration: configuration) dbQueue2 = try! DatabaseQueue(path: databasePath, configuration: configuration) } override func tearDown() { super.tearDown() + dbQueue1 = nil + dbQueue2 = nil try! NSFileManager.defaultManager().removeItemAtPath(databasePath) } @@ -163,4 +176,49 @@ class ConcurrencyTests: XCTestCase { XCTFail("Expected concurrency error") } } + + func testBusyCallback() { + self.busyCallback = { numberOfTries in + // Just wait until lock is released. + sleep(1) + return true + } + + var concurrencyError: DatabaseError? = nil + + let queue = NSOperationQueue() + queue.maxConcurrentOperationCount = 2 + queue.addOperation(NSBlockOperation { + do { + try self.dbQueue1.inTransaction(.Exclusive) { db in + sleep(1) // let other queue try to open transaction + return .Commit + } + } + catch let error as DatabaseError { + concurrencyError = error + } + catch { + XCTFail("\(error)") + } + }) + + queue.addOperation(NSBlockOperation { + do { + try self.dbQueue2.inTransaction(.Exclusive) { db in + sleep(1) // let other queue try to open transaction + return .Commit + } + } + catch let error as DatabaseError { + concurrencyError = error + } + catch { + XCTFail("\(error)") + } + }) + + queue.waitUntilAllOperationsAreFinished() + XCTAssertTrue(concurrencyError == nil) + } } diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index d8cf3b3ab..ac338ae27 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -51,6 +51,9 @@ public struct Configuration { /// Default transaction type public var transactionType: Database.TransactionType + /// Busy Mode + public var busyMode: Database.BusyMode + /// The Threading mode /// /// Not public because we don't expose any public API that could have a use @@ -82,13 +85,21 @@ public struct Configuration { .Exclusive). Unless specified otherwise, transactions opened by DatabaseQueue.inTransaction() will use this transaction type. See https://www.sqlite.org/lang_transaction.html for more information. + - parameter busyMode: A BusyMode (default .ImmediateError). - parameter trace: An optional tracing function (default nil). - returns: A Configuration. */ - public init(foreignKeysEnabled: Bool = true, readonly: Bool = false, transactionType: Database.TransactionType = .Exclusive, trace: TraceFunction? = nil) { + public init( + foreignKeysEnabled: Bool = true, + readonly: Bool = false, + transactionType: Database.TransactionType = .Exclusive, + busyMode: Database.BusyMode = .ImmediateError, + trace: TraceFunction? = nil) + { self.foreignKeysEnabled = foreignKeysEnabled self.readonly = readonly self.transactionType = transactionType + self.busyMode = busyMode self.trace = trace } diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index e96a145d0..8efc1f392 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -347,9 +347,56 @@ public final class Database { // MARK: - Initialization + /// See BusyMode and https://www.sqlite.org/c3ref/busy_handler.html + public typealias BusyCallback = (numberOfTries: Int) -> Bool + + /** + When there are several connections to a database, a connection may try to + access the database while it is locked by another connection. + + The BusyMode enum describes the behavior of GRDB when such a situation + occurs: + + - .ImmediateError: The SQLITE_BUSY error is immediately returned to the + connection that tries to access the locked database. + + - .Timeout: The SQLITE_BUSY error will be returned only if the database + remains locked for more than the specified duration. + + - .Callback: Perform your custom lock handling. + + To set the busy mode of a database, use Configuration: + + let configuration = Configuration(busyMode: .Timeout(1)) + let dbQueue = DatabaseQueue(path: "...", configuration: configuration) + + Relevant SQLite documentation: + + - https://www.sqlite.org/c3ref/busy_timeout.html + - https://www.sqlite.org/c3ref/busy_handler.html + - https://www.sqlite.org/lang_transaction.html + - https://www.sqlite.org/wal.html + */ + public enum BusyMode { + /// The SQLITE_BUSY error is immediately returned to the connection that + /// tries to access the locked database. + case ImmediateError + + /// The SQLITE_BUSY error will be returned only if the database remains + /// locked for more than the specified duration. + case Timeout(NSTimeInterval) + + /// A custom callback that is called when a database is locked. + /// See https://www.sqlite.org/c3ref/busy_handler.html + case Callback(BusyCallback) + } + /// The database configuration let configuration: Configuration + /// The busy handler callback, if any. See Configuration.busyMode. + var busyCallback: BusyCallback? + /// The SQLite connection handle let sqliteConnection: SQLiteConnection @@ -372,6 +419,17 @@ public final class Database { if configuration.foreignKeysEnabled { try execute("PRAGMA foreign_keys = ON") } + + switch configuration.busyMode { + case .ImmediateError: + break + case .Timeout(let duration): + let milliseconds = Int32(duration * 1000) + sqlite3_busy_timeout(sqliteConnection, milliseconds) + case .Callback(let callback): + self.busyCallback = callback + sqlite3_busy_handler(sqliteConnection, sqliteBusyHandler, unsafeBitCast(self, UnsafeMutablePointer.self)) + } } // Initializes an in-memory database @@ -390,6 +448,12 @@ public final class Database { } } +let sqliteBusyHandler: @convention(c) (UnsafeMutablePointer, Int32) -> Int32 = { dbPointer, numberOfTries in + let database = unsafeBitCast(dbPointer, Database.self) + let callback = database.busyCallback! + return callback(numberOfTries: Int(numberOfTries)) ? 1 : 0 +} + // MARK: - Database Information diff --git a/README.md b/README.md index 002639915..a15ec9b12 100644 --- a/README.md +++ b/README.md @@ -686,14 +686,18 @@ try dbQueue1.inTransaction { ... } try dbQueue2.inTransaction { ... } ``` -The interested reader should now that by default, GRDB opens database in the **DELETE journal mode**, and uses **EXCLUSIVE transactions**. Override those default with Configuration, or by providing a transaction type to the inTransaction method: +The interested reader should now that by default, GRDB opens database in the **DELETE journal mode**, uses **EXCLUSIVE transactions**, and registers **no busy handler** of any kind. Override those defaults with Configuration, or by providing a transaction type to the inTransaction method: ```swift -// Choose default transaction type: -let configuration = Configuration(transactionType: .Exclusive) +let configuration = Configuration( + transactionType: .Exclusive, // Default transaction type. + busyMode: .Timeout(1)) // Wait at most 1 second before SQLITE_BUSY + // is thrown. + let dbQueue = try DatabaseQueue( path: "/path/to/database.sqlite", configuration: configuration) + try dbQueue.inTransaction { ... } // BEGIN EXCLUSIVE TRANSACTION try dbQueue.inTransaction(.Exclusive) { ... } // BEGIN EXCLUSIVE TRANSACTION try dbQueue.inTransaction(.Immediate) { ... } // BEGIN IMMEDIATE TRANSACTION @@ -705,6 +709,8 @@ The relevant pieces of SQLite documentation are: - https://www.sqlite.org/isolation.html - https://www.sqlite.org/lang_transaction.html - https://www.sqlite.org/wal.html +- https://www.sqlite.org/c3ref/busy_timeout.html +- https://www.sqlite.org/c3ref/busy_handler.html ### Prepared Statements