diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 7fc3689fe..364edf986 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -447,21 +447,18 @@ extension DatabasePool: DatabaseReader { } public func concurrentRead(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture { - // The semaphore that blocks until futureResult is defined: - let futureSemaphore = DispatchSemaphore(value: 0) - var futureResult: Result? = nil + let builder = UnsafeDatabaseFutureBuilder() asyncConcurrentRead { dbResult in - // Fetch and release the future - futureResult = dbResult.flatMap { db in Result { try value(db) } } - futureSemaphore.signal() + let result = dbResult.flatMap { db in + Result { + try value(db) + } + } + builder.setResultAndReleaseFuture(result) } - return DatabaseFuture { - // Block the future until results are fetched - _ = futureSemaphore.wait(timeout: .distantFuture) - return try futureResult!.get() - } + return builder.makeFuture() } public func spawnConcurrentRead(_ value: @escaping @Sendable (Result) -> Void) { diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index 90e3ca557..e10327564 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -194,3 +194,25 @@ extension NSLocking { #if !canImport(ObjectiveC) @inlinable func autoreleasepool(invoking body: () throws -> Result) rethrows -> Result { try body() } #endif + +/// A helper class that builds a DatabaseFuture without compiler errors +/// regarding concurrency. +final class UnsafeDatabaseFutureBuilder: @unchecked Sendable { + let semaphore = DispatchSemaphore(value: 0) + var result: Result? = nil + + /// - precondition: MUST be called once. + func setResultAndReleaseFuture(_ result: Result) { + self.result = result + semaphore.signal() + } + + /// - precondition: MUST be called once. + func makeFuture() -> DatabaseFuture { + DatabaseFuture { [self] in + // Block the future until results are fetched + _ = semaphore.wait(timeout: .distantFuture) + return try result!.get() + } + } +}