mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-29 04:24:21 +00:00
DatabaseWriter.concurrentRead replaces readFromCurrentState
This commit is contained in:
1 parent
03a781075e
commit
9bfe893908
7 files changed
+337
-51
No files matched your search
@@ -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<T>(_ block: @escaping (Database) throws -> T) -> Future<T> {
|
||||
// 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<T>? = 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? {
|
||||
|
||||
@@ -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<T>(_ block: @escaping (Database) throws -> T) -> Future<T> {
|
||||
// DatabaseQueue can't perform parallel reads.
|
||||
let result = Result<T> {
|
||||
// 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
|
||||
|
||||
@@ -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<T>(_ block: @escaping (Database) throws -> T) -> Future<T>
|
||||
}
|
||||
|
||||
extension DatabaseWriter {
|
||||
@@ -148,6 +185,37 @@ extension DatabaseWriter {
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// Default implementation, based on the deprecated readFromCurrentState.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> Future<T> {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Result<T>? = 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<T> {
|
||||
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<T>(_ block: @escaping (Database) throws -> T) -> Future<T> {
|
||||
return base.concurrentRead(block)
|
||||
}
|
||||
|
||||
// MARK: - Writing in Database
|
||||
|
||||
|
||||
@@ -580,62 +580,41 @@ private func makeFetchFunction<Record, T>(
|
||||
// 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<Record>], 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))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,4 +37,13 @@ enum Result<Value> {
|
||||
return .failure(error)
|
||||
}
|
||||
}
|
||||
|
||||
func unwrap() throws -> Value {
|
||||
switch self {
|
||||
case .success(let value):
|
||||
return value
|
||||
case .failure(let error):
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,6 +80,7 @@ private class UserDatabaseWriter : DatabaseWriter {
|
||||
func writeWithoutTransaction<T>(_ block: (Database) throws -> T) rethrows -> T { preconditionFailure() }
|
||||
func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T { preconditionFailure() }
|
||||
func readFromCurrentState(_ block: @escaping (Database) -> Void) throws { preconditionFailure() }
|
||||
func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> Future<T> { preconditionFailure() }
|
||||
}
|
||||
|
||||
// MARK: - FTS5Tokenizer
|
||||
|
||||
@@ -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<Int> = try dbPool.writeWithoutTransaction { db in
|
||||
let future: Future<Int> = 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"
|
||||
|
||||
Reference in new issue
Block a user