Merge pull request #409 from groue/feature/concurrentRead

DatabaseWriter.concurrentRead
This commit is contained in:
Gwendal Roué authored and GitHub committed 2018-09-13 08:56:38 +02:00
commit 3bf32564a4
12 files changed
+389 -81

No files matched your search

+15
View File
@@ -3,9 +3,24 @@ Release Notes
## Next Version
### New
- [#409](https://github.com/groue/GRDB.swift/pull/409): DatabaseWriter.concurrentRead
### API diff
```diff
protocol DatabaseWriter : DatabaseReader {
+ func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> Future<T>
+ @available(*, deprecated)
func readFromCurrentState(_ block: @escaping (Database) -> Void) throws
}
+class Future<Value> {
+ func wait() throws -> Value
+}
extension Cursor {
+ func isEmpty() throws -> Bool
}
+2
View File
@@ -233,6 +233,8 @@ Starting points:
- [RxSwiftCommunity/RxDataSources](https://github.com/RxSwiftCommunity/RxDataSources)
- [ra1028/DifferenceKit](https://github.com/ra1028/DifferenceKit)
- [tonyarnold/Differ](https://github.com/tonyarnold/Differ)
- [onmyway133/DeepDiff](https://github.com/onmyway133/DeepDiff)
- [mcudich/HeckelDiff](https://github.com/mcudich/HeckelDiff)
### FetchedRecordsController Support for Any Request
+123 -2
View File
@@ -1,4 +1,5 @@
import Foundation
import Dispatch
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
@@ -349,6 +350,8 @@ extension DatabasePool : DatabaseReader {
}
}
/// This method is deprecated. Use concurrentRead instead.
///
/// Asynchronously executes a read-only block in a protected dispatch queue,
/// wrapped in a deferred transaction.
///
@@ -374,6 +377,7 @@ 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.
@available(*, deprecated, message: "Use concurrentRead instead")
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
// https://www.sqlite.org/isolation.html
//
@@ -422,7 +426,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 +465,119 @@ extension DatabasePool : DatabaseReader {
throw readError
}
}
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? {
+20 -4
View File
@@ -203,6 +203,8 @@ extension DatabaseQueue {
return try writer.reentrantSync(block)
}
/// This method is deprecated. Use concurrentRead instead.
///
/// Synchronously executes *block*.
///
/// This method must be called from the protected database dispatch queue,
@@ -211,10 +213,7 @@ extension DatabaseQueue {
/// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
/// SQLCipher), attempts to write in the database from this meethod throw a
/// DatabaseError of resultCode `SQLITE_READONLY`.
///
/// See `DatabaseWriter.readFromCurrentState`.
///
/// :nodoc:
@available(*, deprecated, message: "Use concurrentRead instead")
public func readFromCurrentState(_ block: @escaping (Database) -> Void) {
// Check that we're on the correct queue...
writer.execute { db in
@@ -224,6 +223,23 @@ extension DatabaseQueue {
}
}
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
+1 -1
View File
@@ -34,7 +34,7 @@ public class DatabaseSnapshot : DatabaseReader {
try db.beginTransaction(.deferred)
// Take snapshot
// See DatabasePool.readFromCurrentState for a complete discussion
// See DatabasePool.concurrentRead for a complete discussion
try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").makeCursor().next()
}
}
+99
View File
@@ -1,3 +1,5 @@
import Dispatch
/// The protocol for all types that can update a database.
///
/// It is adopted by DatabaseQueue and DatabasePool.
@@ -60,6 +62,8 @@ public protocol DatabaseWriter : DatabaseReader {
// MARK: - Reading from Database
/// This method is deprecated. Use concurrentRead instead.
///
/// Synchronously or asynchronously executes a read-only block that takes a
/// database connection.
///
@@ -80,7 +84,42 @@ public protocol DatabaseWriter : DatabaseReader {
/// }
/// try db.execute("INSERT INTO player ...")
/// }
@available(*, deprecated, message: "Use concurrentRead instead")
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 call the 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:
///
/// 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 +187,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 +229,29 @@ extension DatabaseWriter {
}
}
/// A future value.
public class Future<Value> {
private var consumed = false
private let _wait: () throws -> Value
init(_ wait: @escaping () throws -> Value) {
_wait = wait
}
/// 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, "Future.wait() must be called only once")
consumed = true
return try _wait()
}
}
/// A type-erased DatabaseWriter
///
/// Instances of AnyDatabaseWriter forward their methods to an arbitrary
@@ -189,9 +282,15 @@ public final class AnyDatabaseWriter : DatabaseWriter {
}
/// :nodoc:
@available(*, deprecated, message: "Use concurrentRead instead")
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
+28 -49
View File
@@ -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))
}
}
}
}
+9
View File
@@ -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
}
}
}
+22 -25
View File
@@ -7197,50 +7197,54 @@ try dbPool.write { db in
// Increment the number of players
try Player(...).insert(db)
}
// <- other threads can write in the database here
try dbPool.read { db in
// Read some random value :-(
let count = try Player.fetchCount(db)
}
```
The correct solution is the `readFromCurrentState` method, which must be called from within a write block, outside of any transaction:
The correct solution is the `concurrentRead` method, which must be called from within a write block, outside of any transaction.
`concurrentRead` returns a **future value** which you consume on any dispatch queue, with the `wait()` method:
```swift
// CORRECT
try dbPool.writeWithoutTransaction { db in
try db.inTransaction {
// increment the number of players
try Player(...).insert(db)
return .commit
}
let futureCount: Future<Int> = try dbPool.writeWithoutTransaction { db in
// increment the number of players
try Player(...).insert(db)
// <- not in a transaction here
try dbPool.readFromCurrentState { db
// Read the number of players. The writer queue has been unlocked :-)
let count = try Player.fetchCount(db)
let futureCount = dbPool.concurrentRead { db
return try Player.fetchCount(db)
}
return futureCount
}
// <- The writer queue has been unlocked :-)
// Wait for the player count
let count = try futureCount.wait()
```
`readFromCurrentState` blocks until it can guarantee its closure argument an isolated access to the last committed state of the database. It then asynchronously executes the closure. If the isolated access can't be established, `readFromCurrentState` throws an error, and the closure is not executed.
`concurrentRead` blocks until it can guarantee its closure argument an isolated access to the last committed state of the database. It then asynchronously executes the closure.
The closure can run concurrently with eventual updates performed after `readFromCurrentState`: those updates won't be visible from within the closure. In the example below, the number of players is guaranteed to be non-zero, even though it is fetched concurrently with the player deletion:
The closure can run concurrently with eventual updates performed after `concurrentRead`: those updates won't be visible from within the closure. In the example below, the number of players is guaranteed to be non-zero, even though it is fetched concurrently with the player deletion:
```swift
try dbPool.writeWithoutTransaction { db in
// Increment the number of players
try Player(...).insert(db)
try dbPool.readFromCurrentState { db
let futureCount = dbPool.concurrentRead { db
// Guaranteed to be non-zero
let count = try Player.fetchCount(db)
return try Player.fetchCount(db)
}
try Player.deleteAll(db)
}
```
[Transaction Observers](#transactionobserver-protocol) can also use `readFromCurrentState` in their `databaseDidCommit` method in order to process database changes without blocking other threads that want to write into the database.
[Transaction Observers](#transactionobserver-protocol) can also use `concurrentRead` in their `databaseDidCommit` method in order to process database changes without blocking other threads that want to write into the database.
### Database Snapshots
@@ -7306,21 +7310,14 @@ try snapshot2.read { db in
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/3.3/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/3.3/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only.
These protocols provide a unified API that lets you write safe concurrent code that targets all three concurrency modes.
However, queues are not pools which are different from snapshots, and DatabaseReader and DatabaseWriter provide the *smallest* common guarantees. They require more discipline:
- Pools are less forgiving than queues when one overlooks a transaction (see [concurrency rule 3](#guarantees-and-rules)).
- DatabaseWriter.readFromCurrentState is synchronous, or asynchronous, depending on whether it is run by a queue or a pool (see [advanced DatabasePool](#advanced-databasepool)). It thus requires higher libDispatch skills, and more complex synchronization code.
DatabaseReader and DatabaseWriter are not a tool for applications that hesitate between DatabaseQueue and DatabasePool, and look for a common API. As seen above, the protocols actually make applications harder to write correctly. Instead, they target generic code that has *both* queues and pools in mind. The built-in AnyDatabaseReader and AnyDatabaseWriter type erasers serve the same purpose.
DatabaseWriter and DatabaseReader fuel, for example:
These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example:
- [Migrations](#migrations)
- [FetchedRecordsController](#fetchedrecordscontroller)
- [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB)
Caution: DatabaseQueue and DatabasePool only provide the *smallest* common guarantees. They don't erase the differences between queues, pools, and snapshots. See for example [Differences between Database Queues and Pools](#differences-between-database-queues-and-pools).
### Unsafe Concurrency APIs
+2
View File
@@ -22,6 +22,8 @@
- [ ] https://github.com/apple/swift-evolution/blob/master/proposals/0075-import-test.md
- [ ] Avoid code duplication: https://forums.swift.org/t/c-interoperability-combinations-of-library-and-os-versions/14029/4
- [ ] Allow joining methods on DerivableRequest
- [ ] DatabaseWriter.assertWriteAccess()
- [ ] Configuration.crashOnError = true
- [ ] Support for "INSERT INTO ... SELECT ...". For example:
```swift
@@ -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"