From 9bfe893908a70934fb49f1716445c0bfc4fa9207 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Sep 2018 13:12:35 +0200 Subject: [PATCH] DatabaseWriter.concurrentRead replaces readFromCurrentState --- GRDB/Core/DatabasePool.swift | 127 +++++++++++++++++- GRDB/Core/DatabaseQueue.swift | 21 +++ GRDB/Core/DatabaseWriter.swift | 86 ++++++++++++ GRDB/Record/FetchedRecordsController.swift | 77 ++++------- GRDB/Utils/Result.swift | 9 ++ .../GRDBTests/CompilationProtocolTests.swift | 1 + .../DatabasePoolConcurrencyTests.swift | 67 +++++++++ 7 files changed, 337 insertions(+), 51 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index bb604e734..8a46f7723 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -374,6 +374,9 @@ extension DatabasePool : DatabaseReader { /// - parameter block: A block that accesses the database. /// - throws: The error thrown by the block, or any DatabaseError that would /// happen while establishing the read access to the database. + /// + /// :nodoc: + @available(*, deprecated) public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws { // https://www.sqlite.org/isolation.html // @@ -422,7 +425,12 @@ extension DatabasePool : DatabaseReader { // Check that we're on the writer queue... writer.execute { db in // ... and that no transaction is opened. - GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction. If this error is raised from a DatabasePool.write block, use DatabasePool.writeWithoutTransaction instead (and use transactions when needed).") + GRDBPrecondition(!db.isInsideTransaction, """ + readFromCurrentState must not be called from inside a transaction. \ + If this error is raised from a DatabasePool.write block, use \ + DatabasePool.writeWithoutTransaction instead (and use \ + transactions when needed). + """) } // The semaphore that blocks the writing dispatch queue until snapshot @@ -456,7 +464,122 @@ extension DatabasePool : DatabaseReader { throw readError } } - + + /// See `DatabaseWriter.concurrentRead`. + /// + /// :nodoc: + public func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future { + // https://www.sqlite.org/isolation.html + // + // > In WAL mode, SQLite exhibits "snapshot isolation". When a read + // > transaction starts, that reader continues to see an unchanging + // > "snapshot" of the database file as it existed at the moment in time + // > when the read transaction started. Any write transactions that + // > commit while the read transaction is active are still invisible to + // > the read transaction, because the reader is seeing a snapshot of + // > database file from a prior moment in time. + // + // That's exactly what we need. But what does "when read transaction + // starts" mean? + // + // http://www.sqlite.org/lang_transaction.html + // + // > Deferred [transaction] means that no locks are acquired on the + // > database until the database is first accessed. [...] Locks are not + // > acquired until the first read or write operation. [...] Because the + // > acquisition of locks is deferred until they are needed, it is + // > possible that another thread or process could create a separate + // > transaction and write to the database after the BEGIN on the + // > current thread has executed. + // + // Now that's precise enough: SQLite defers "snapshot isolation" until + // the first SELECT: + // + // Reader Writer + // BEGIN DEFERRED TRANSACTION + // UPDATE ... (1) + // Here the change (1) is visible + // SELECT ... + // UPDATE ... (2) + // Here the change (2) is not visible + // + // The readFromCurrentState method says that no change should be visible + // at all. We thus have to perform a select that establishes the + // snapshot isolation before we release the writer queue: + // + // Reader Writer + // BEGIN DEFERRED TRANSACTION + // SELECT anything + // UPDATE ... + // Here the change is not visible by GRDB user + + // Check that we're on the writer queue... + writer.execute { db in + // ... and that no transaction is opened. + GRDBPrecondition(!db.isInsideTransaction, """ + concurrentRead must not be called from inside a transaction. \ + If this error is raised from a DatabasePool.write block, use \ + DatabasePool.writeWithoutTransaction instead (and use \ + transactions when needed). + """) + } + + // The semaphore that blocks the writing dispatch queue until snapshot + // isolation has been established: + let isolationSemaphore = DispatchSemaphore(value: 0) + + // The semaphore that blocks until futureResult is defined: + let futureSemaphore = DispatchSemaphore(value: 0) + var futureResult: Result? = nil + + do { + try readerPool.get { reader in + reader.async { db in + // Open a deferred transaction and access the database in + // order to establish snapshot isolation. + defer { _ = try? db.commit() } + do { + try db.beginTransaction(.deferred) + try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").makeCursor().next() + } catch { + // Snapshot isolation failure + futureResult = .failure(error) + isolationSemaphore.signal() + futureSemaphore.signal() + return + } + + // Release the writer queue + isolationSemaphore.signal() + + // Reset the schema cache before running user code in snapshot isolation + db.schemaCache = SimpleDatabaseSchemaCache() + + // Fetch and release the future + futureResult = Result { try block(db) } + futureSemaphore.signal() + } + } + } catch { + return Future { throw error } + } + + // Block the writer queue until snapshot isolation success or error + _ = isolationSemaphore.wait(timeout: .distantFuture) + + return Future { + // Block the future until results are fetched + _ = futureSemaphore.wait(timeout: .distantFuture) + + switch futureResult! { + case .failure(let error): + throw error + case .success(let result): + return result + } + } + } + /// Returns a reader that can be used from the current dispatch queue, /// if any. private var currentReader: SerializedDatabase? { diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 5ddaa7ed0..33a231b28 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -215,6 +215,7 @@ extension DatabaseQueue { /// See `DatabaseWriter.readFromCurrentState`. /// /// :nodoc: + @available(*, deprecated) public func readFromCurrentState(_ block: @escaping (Database) -> Void) { // Check that we're on the correct queue... writer.execute { db in @@ -224,6 +225,26 @@ extension DatabaseQueue { } } + /// See `DatabaseWriter.concurrentRead`. + /// + /// :nodoc: + public func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future { + // DatabaseQueue can't perform parallel reads. + let result = Result { + // Check that we're on the writer queue... + try writer.execute { db in + // ... and that no transaction is opened. + GRDBPrecondition(!db.isInsideTransaction, "concurrentRead must not be called from inside a transaction.") + return try db.readOnly { + try block(db) + } + } + } + return Future { + try result.unwrap() + } + } + // MARK: - Writing in Database /// Synchronously executes a block in a protected dispatch queue, wrapped diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 3f5b11060..2d5926d9b 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -80,7 +80,44 @@ public protocol DatabaseWriter : DatabaseReader { /// } /// try db.execute("INSERT INTO player ...") /// } + /// + /// :nodoc: + @available(*, deprecated) func readFromCurrentState(_ block: @escaping (Database) -> Void) throws + + /// Concurrently executes a read-only block that takes a + /// database connection. + /// + /// This method must be called from a writing dispatch queue, outside of any + /// transaction. You'll get a fatal error otherwise. + /// + /// The *block* argument is guaranteed to see the database in the last + /// committed state at the moment this method is called. Eventual concurrent + /// database updates are *not visible* inside the block. + /// + /// This method returns as soon as the isolation guarantees described above + /// are established. To access the fetched results, you use the wait() + /// method of the returned future. + /// + /// In the example below, the number of players is fetched concurrently with + /// the player insertion. Yet the future is guaranteed to return zero: + /// + /// try writer.writeWithoutTransaction { db in + /// // Delete all players + /// try Player.deleteAll() + /// + /// // Count players concurrently + /// let future = writer.concurrentRead { db in + /// return try Player.fetchCount() + /// } + /// + /// // Insert a player + /// try Player(...).insert(db) + /// + /// // Guaranteed to be zero + /// let count = try future.wait() + /// } + func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future } extension DatabaseWriter { @@ -148,6 +185,37 @@ extension DatabaseWriter { #endif } + // MARK: - Reading from Database + + /// Default implementation, based on the deprecated readFromCurrentState. + /// + /// :nodoc: + public func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future { + let semaphore = DispatchSemaphore(value: 0) + var result: Result? = nil + + do { + try readFromCurrentState { db in + result = Result { try block(db) } + semaphore.signal() + } + } catch { + result = .failure(error) + semaphore.signal() + } + + return Future { + _ = semaphore.wait(timeout: .distantFuture) + + switch result! { + case .failure(let error): + throw error + case .success(let result): + return result + } + } + } + // MARK: - Claiming Disk Space /// Rebuilds the database file, repacking it into a minimal amount of @@ -159,6 +227,18 @@ extension DatabaseWriter { } } +public struct Future { + private let _wait: () throws -> T + + init(_ wait: @escaping () throws -> T) { + _wait = wait + } + + public func wait() throws -> T { + return try _wait() + } +} + /// A type-erased DatabaseWriter /// /// Instances of AnyDatabaseWriter forward their methods to an arbitrary @@ -189,9 +269,15 @@ public final class AnyDatabaseWriter : DatabaseWriter { } /// :nodoc: + @available(*, deprecated) public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws { try base.readFromCurrentState(block) } + + /// :nodoc: + public func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future { + return base.concurrentRead(block) + } // MARK: - Writing in Database diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 48dce6b61..f4e3ca161 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -580,62 +580,41 @@ private func makeFetchFunction( // Should controller become strong at any point before callbacks are // called, such unowned reference would have an opportunity to crash. return { [weak controller] observer in - // Return if observer has been invalidated - guard observer.isValid else { return } - - // Return if fetched records controller has been deallocated - guard let request = controller?.request, let databaseWriter = controller?.databaseWriter else { return } + // Return if observer has been invalidated, or if fetched records + // controller has been deallocated + guard observer.isValid, + let request = controller?.request, + let databaseWriter = controller?.databaseWriter + else { return } willProcessTransaction() - // Fetch items. - // - // This method is called from the database writer's serialized - // queue, so that we can fetch items before other writes have the - // opportunity to modify the database. - // - // However, we don't have to block the writer queue for all the - // duration of the fetch. We just need to block the writer queue - // until we can perform a fetch in isolation. This is the role of - // the readFromCurrentState method (see below). - // - // However, our fetch will last for an unknown duration. And since - // we release the writer queue early, the next database modification - // will triggers this callback while our fetch is, maybe, still - // running. This next callback will also perform its own fetch, that - // will maybe end before our own fetch. - // - // We have to make sure that our fetch is processed *before* the - // next fetch: let's immediately dispatch the processing task in our - // serialized FIFO queue, but have it wait for our fetch to - // complete, with a semaphore: - let semaphore = DispatchSemaphore(value: 0) - var result: Result<(fetchedItems: [Item], fetchedAlongside: T)>? = nil - do { - try databaseWriter.readFromCurrentState { db in - result = Result { try ( - fetchedItems: request.fetchAll(db), - fetchedAlongside: fetchAlongside(db)) } - semaphore.signal() - } - } catch { - result = .failure(error) - semaphore.signal() + // Perform a concurrent read so that writer dispatch queue is released + // as soon as possible. + let future = databaseWriter.concurrentRead { db in + try (fetchedItems: request.fetchAll(db), + fetchedAlongside: fetchAlongside(db)) } - // Process the fetched items - + // Dispatch processing immediately on observer.queue in order to + // process fetched values in the same order as transactions: observer.queue.async { [weak observer] in - // Wait for the fetch to complete: - _ = semaphore.wait(timeout: .distantFuture) + // Return if observer has been deallocated or invalidated + guard let observer = observer, + observer.isValid + else { return } - // Return if observer has been invalidated - guard let strongObserver = observer else { return } - guard strongObserver.isValid else { return } - - completion(result!.map { (fetchedItems, fetchedAlongside) in - (fetchedItems: fetchedItems, fetchedAlongside: fetchedAlongside, observer: strongObserver) - }) + do { + // Wait for concurrent read to complete + let values = try future.wait() + + completion(.success(( + fetchedItems: values.fetchedItems, + fetchedAlongside: values.fetchedAlongside, + observer: observer))) + } catch { + completion(.failure(error)) + } } } } diff --git a/GRDB/Utils/Result.swift b/GRDB/Utils/Result.swift index b388fe1a2..ee5bbfdfc 100644 --- a/GRDB/Utils/Result.swift +++ b/GRDB/Utils/Result.swift @@ -37,4 +37,13 @@ enum Result { return .failure(error) } } + + func unwrap() throws -> Value { + switch self { + case .success(let value): + return value + case .failure(let error): + throw error + } + } } diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index 1d999c64f..109d65759 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -80,6 +80,7 @@ private class UserDatabaseWriter : DatabaseWriter { func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T { preconditionFailure() } func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T { preconditionFailure() } func readFromCurrentState(_ block: @escaping (Database) -> Void) throws { preconditionFailure() } + func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future { preconditionFailure() } } // MARK: - FTS5Tokenizer diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 280b43b9d..a56830c49 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -836,6 +836,21 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { _ = s.wait(timeout: .distantFuture) } + func testConcurrentReadOpensATransaction() throws { + let dbPool = try makeDatabasePool() + let future = dbPool.writeWithoutTransaction { db in + dbPool.concurrentRead { db in + XCTAssertTrue(db.isInsideTransaction) + do { + try db.execute("BEGIN DEFERRED TRANSACTION") + XCTFail("Expected error") + } catch { + } + } + } + try future.wait() + } + func testReadFromCurrentStateOutsideOfTransaction() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in @@ -871,6 +886,38 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { XCTAssertEqual(i, 0) } + func testConcurrentReadOutsideOfTransaction() throws { + let dbPool = try makeDatabasePool() + try dbPool.write { db in + try db.create(table: "persons") { t in + t.column("id", .integer).primaryKey() + } + } + + // Writer Reader + // dbPool.writeWithoutTransaction { + // > + // dbPool.concurrentRead { + // < + // INSERT INTO items (id) VALUES (NULL) + // > + let s1 = DispatchSemaphore(value: 0) + // } SELECT COUNT(*) FROM persons -> 0 + // < + // } + + let future: Future = try dbPool.writeWithoutTransaction { db in + let future: Future = dbPool.concurrentRead { db in + _ = s1.wait(timeout: .distantFuture) + return try! Int.fetchOne(db, "SELECT COUNT(*) FROM persons")! + } + try db.execute("INSERT INTO persons DEFAULT VALUES") + s1.signal() + return future + } + XCTAssertEqual(try future.wait(), 0) + } + func testReadFromCurrentStateError() throws { let dbPool = try makeDatabasePool() try dbPool.writeWithoutTransaction { db in @@ -890,6 +937,26 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { } } + func testConcurrentReadError() throws { + let dbPool = try makeDatabasePool() + try dbPool.writeWithoutTransaction { db in + try db.execute("PRAGMA locking_mode=EXCLUSIVE") + try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") + let future = dbPool.concurrentRead { db in + fatalError("Should not run") + } + do { + try future.wait() + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_BUSY) + XCTAssertEqual(error.message!, "database is locked") + XCTAssertTrue(error.sql == nil) + XCTAssertEqual(error.description, "SQLite error 5: database is locked") + } + } + } + func testLongRunningReadTransaction() throws { // A test for a "user-defined" DatabaseSnapshot based on DatabaseQueue let dbName = "test.sqlite"