From 05f7d3c8d411f9ae1ae22107d6f4d2dd39b439ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 30 Mar 2024 17:29:26 +0100 Subject: [PATCH] [BREAKING] Remove DatabaseFuture and concurrentRead That's one less DispatchSemaphore. We don't need this method anymore. --- GRDB/Core/DatabasePool.swift | 18 ---- GRDB/Core/DatabaseQueue.swift | 13 --- GRDB/Core/DatabaseWriter.swift | 92 ------------------- GRDB/Documentation.docc/Concurrency.md | 29 +----- TODO.md | 2 +- .../DatabasePoolConcurrencyTests.swift | 70 +------------- 6 files changed, 4 insertions(+), 220 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 1362135f4..778cbf8d3 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -442,24 +442,6 @@ extension DatabasePool: DatabaseReader { } } - public func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture { - // The semaphore that blocks until futureResult is defined: - let futureSemaphore = DispatchSemaphore(value: 0) - var futureResult: Result? = nil - - asyncConcurrentRead { dbResult in - // Fetch and release the future - futureResult = dbResult.flatMap { db in Result { try value(db) } } - futureSemaphore.signal() - } - - return DatabaseFuture { - // Block the future until results are fetched - _ = futureSemaphore.wait(timeout: .distantFuture) - return try futureResult!.get() - } - } - public func spawnConcurrentRead(_ value: @escaping (Result) -> Void) { asyncConcurrentRead(value) } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 604345883..69ec2fe16 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -266,19 +266,6 @@ extension DatabaseQueue: DatabaseReader { try writer.reentrantSync(value) } - public func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture { - // DatabaseQueue can't perform parallel reads. - // Perform a blocking read instead. - return DatabaseFuture(Result { - // Check that we're on the writer queue, as documented - try writer.execute { db in - try db.isolated(readOnly: true) { - try value(db) - } - } - }) - } - public func spawnConcurrentRead(_ value: @escaping (Result) -> Void) { // Check that we're on the writer queue... writer.execute { db in diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 87937214a..e92334047 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -38,9 +38,7 @@ import Dispatch /// /// ### Reading from the Latest Committed Database State /// -/// - ``concurrentRead(_:)`` /// - ``spawnConcurrentRead(_:)`` -/// - ``DatabaseFuture`` /// /// ### Unsafe Methods /// @@ -251,49 +249,6 @@ public protocol DatabaseWriter: DatabaseReader { // MARK: - Reading from Database - /// Schedules read-only database operations for execution, and returns a - /// future value. - /// - /// This method must be called from the writer dispatch queue, outside of - /// any transaction. You'll get a fatal error otherwise. - /// - /// Database operations performed by the `value` closure are isolated in a - /// transaction: they do not see changes performed by eventual concurrent - /// writes (even writes performed by other processes). - /// - /// They see the database in the state left by the last updates performed - /// by the database writer. - /// - /// To access the fetched results, you call the ``DatabaseFuture/wait()`` - /// method of the returned future, on any dispatch queue. - /// - /// In the example below, the number of players is fetched concurrently with - /// the player insertion. Yet the future is guaranteed to return zero: - /// - /// ```swift - /// 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() - /// } - /// ``` - /// - /// - note: Usage of this method is discouraged, because waiting on the - /// returned ``DatabaseFuture`` blocks a thread. You may prefer - /// ``spawnConcurrentRead(_:)`` instead. - /// - parameter value: A closure which accesses the database. - func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture - // Exposed for RxGRDB and GRBCombine. Naming is not stabilized. /// Schedules read-only database operations for execution. /// @@ -924,49 +879,6 @@ extension Publisher where Failure == Error { } #endif -/// A future database value. -/// -/// You get instances of `DatabaseFuture` from the `DatabaseWriter` -/// ``DatabaseWriter/concurrentRead(_:)`` method. For example: -/// -/// ```swift -/// let futureCount: Future = try writer.writeWithoutTransaction { db in -/// try Player(...).insert() -/// -/// // Count players concurrently -/// return writer.concurrentRead { db in -/// return try Player.fetchCount() -/// } -/// } -/// -/// let count: Int = try futureCount.wait() -/// ``` -public class DatabaseFuture { - private var consumed = false - private let _wait: () throws -> Value - - init(_ wait: @escaping () throws -> Value) { - _wait = wait - } - - init(_ result: Result) { - _wait = result.get - } - - /// Blocks the current thread until the value is available, and returns it. - /// - /// It is a programmer error to call this method several times. - /// - /// - throws: Any error that prevented the value from becoming available. - public func wait() throws -> Value { - // Not thread-safe and quick and dirty. - // Goal is that users learn not to call this method twice. - GRDBPrecondition(consumed == false, "DatabaseFuture.wait() must be called only once") - consumed = true - return try _wait() - } -} - /// A type-erased database writer. /// /// An instance of `AnyDatabaseWriter` forwards its operations to an underlying @@ -1056,10 +968,6 @@ extension AnyDatabaseWriter: DatabaseWriter { try base.unsafeReentrantWrite(updates) } - public func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture { - base.concurrentRead(value) - } - public func spawnConcurrentRead(_ value: @escaping (Result) -> Void) { base.spawnConcurrentRead(value) } diff --git a/GRDB/Documentation.docc/Concurrency.md b/GRDB/Documentation.docc/Concurrency.md index 4c5f7e908..1b8050419 100644 --- a/GRDB/Documentation.docc/Concurrency.md +++ b/GRDB/Documentation.docc/Concurrency.md @@ -277,31 +277,7 @@ let newPlayerCount = try dbPool.write { db in } ``` -➡️ The synchronous solution is the ``DatabaseWriter/concurrentRead(_:)`` method. It must be called from within a write access, outside of any transaction. It returns a ``DatabaseFuture`` which you consume any time later, with the ``DatabaseFuture/wait()`` method: - -```swift -let future: DatabaseFuture = try dbPool.writeWithoutTransaction { db in - // Increment the number of players - try db.inTransaction { - try Player(...).insert(db) - return .commit - } - - // <- Not in a transaction here - return dbPool.concurrentRead { db - try Player.fetchCount(db) - } -} - -do { - // Handle the new player count - guaranteed greater than zero - let newPlayerCount = try future.wait() -} catch { - // Handle error -} -``` - -🔀 The asynchronous version of `concurrentRead` is ``DatabasePool/asyncConcurrentRead(_:)``: +🔀 The solution is ``DatabasePool/asyncConcurrentRead(_:)``. It must be called from within a write access, outside of any transaction: ```swift try dbPool.writeWithoutTransaction { db in @@ -324,11 +300,10 @@ try dbPool.writeWithoutTransaction { db in } ``` -Both ``DatabaseWriter/concurrentRead(_:)`` and ``DatabasePool/asyncConcurrentRead(_:)`` block until they can guarantee their closure argument an isolated access to the database, in the exact state left by the last transaction. It then asynchronously executes this closure. +The ``DatabasePool/asyncConcurrentRead(_:)`` method blocks until it can guarantee its closure argument an isolated access to the database, in the exact state left by the last transaction. It then asynchronously executes the closure. In the illustration below, the striped band shows the delay needed for the reading thread to acquire isolation. Until then, no other thread can write: - ![DatabasePool Concurrent Read](DatabasePoolConcurrentRead.png) Types that conform to ``TransactionObserver`` can also use those methods in their ``TransactionObserver/databaseDidCommit(_:)`` method, in order to process database changes without blocking other threads that want to write into the database. diff --git a/TODO.md b/TODO.md index 2a18e0d11..31138af99 100644 --- a/TODO.md +++ b/TODO.md @@ -95,6 +95,7 @@ - [X] GRDB7: Raise the minimum watchOS target https://github.com/groue/GRDB.swift/issues/1472#issuecomment-1960696836 - [ ] GRDB7: Consider putting a Task cancellation handler on async methods. - [X] GRDB7: All writes should be immediate, right? https://github.com/groue/GRDB.swift/pull/1485#issuecomment-1953793553 +- [X] GRDB7: Remove concurrenRead and DatabaseFuture - [ ] GRDB7: Sendable conformances - [X] anydatabasecancellable - [ ] anydatabaseregionconvertible @@ -122,7 +123,6 @@ - [X] databasedatedecodingstrategy - [X] databasedateencodingstrategy - [ ] databasefunction - - [ ] databasefuture - [ ] databasemigrator - [ ] databasepublishers/databaseregion - [ ] databasepublishers/migrate diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 7a329c38c..93eaaae3e 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -1074,74 +1074,6 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { try test(qos: .userInitiated) } - // MARK: - ConcurrentRead - - func testConcurrentReadOpensATransaction() throws { - let dbPool = try makeDatabasePool() - let future = dbPool.writeWithoutTransaction { db in - dbPool.concurrentRead { db in - XCTAssertTrue(db.isInsideTransaction) - do { - try db.execute(sql: "BEGIN DEFERRED TRANSACTION") - XCTFail("Expected error") - } catch { - } - } - } - try future.wait() - } - - func testConcurrentReadOutsideOfTransaction() throws { - let dbPool = try makeDatabasePool() - try dbPool.write { db in - try db.create(table: "persons") { t in - t.primaryKey("id", .integer) - } - } - - // Writer Reader - // dbPool.writeWithoutTransaction { - // > - // dbPool.concurrentRead { - // < - // INSERT INTO items (id) VALUES (NULL) - // > - let s1 = DispatchSemaphore(value: 0) - // } SELECT COUNT(*) FROM persons -> 0 - // < - // } - - let future: DatabaseFuture = try dbPool.writeWithoutTransaction { db in - let future: DatabaseFuture = dbPool.concurrentRead { db in - _ = s1.wait(timeout: .distantFuture) - return try! Int.fetchOne(db, sql: "SELECT COUNT(*) FROM persons")! - } - try db.execute(sql: "INSERT INTO persons DEFAULT VALUES") - s1.signal() - return future - } - XCTAssertEqual(try future.wait(), 0) - } - - func testConcurrentReadError() throws { - // Necessary for this test to run as quickly as possible - dbConfiguration.readonlyBusyMode = .immediateError - let dbPool = try makeDatabasePool() - try dbPool.writeWithoutTransaction { db in - try db.execute(sql: "PRAGMA locking_mode=EXCLUSIVE") - try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") - let future = dbPool.concurrentRead { db in - fatalError("Should not run") - } - do { - try future.wait() - } catch let error as DatabaseError { - XCTAssertEqual(error.resultCode, .SQLITE_BUSY) - XCTAssertEqual(error.message!, "database is locked") - } - } - } - // MARK: - AsyncConcurrentRead func testAsyncConcurrentReadOpensATransaction() throws { @@ -1179,7 +1111,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { // Writer Reader // dbPool.writeWithoutTransaction { // > - // dbPool.concurrentRead { + // dbPool.asyncConcurrentRead { // < // INSERT INTO items (id) VALUES (NULL) // >