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 01/12] 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" From da58e228c074192a15161069559fa22f09ded009 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Sep 2018 13:18:15 +0200 Subject: [PATCH 02/12] Document Future --- GRDB/Core/DatabaseWriter.swift | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 2d5926d9b..bb972f850 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -227,14 +227,17 @@ extension DatabaseWriter { } } -public struct Future { - private let _wait: () throws -> T +/// A future value. +public struct Future { + private let _wait: () throws -> Value - init(_ wait: @escaping () throws -> T) { + init(_ wait: @escaping () throws -> Value) { _wait = wait } - public func wait() throws -> T { + /// Blocks the current thread until the future value is available. + /// Throws an error if the value could not be computed. + public func wait() throws -> Value { return try _wait() } } From 106812c02c933026190c047499d840f509a7c8ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Sep 2018 13:42:35 +0200 Subject: [PATCH 03/12] Fix SPM --- GRDB/Core/DatabasePool.swift | 1 + GRDB/Core/DatabaseWriter.swift | 2 ++ 2 files changed, 3 insertions(+) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 8a46f7723..fadddcb60 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -1,4 +1,5 @@ import Foundation +import Dispatch #if SWIFT_PACKAGE import CSQLite #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index bb972f850..1dd2317d9 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -1,3 +1,5 @@ +import Dispatch + /// The protocol for all types that can update a database. /// /// It is adopted by DatabaseQueue and DatabasePool. From 21209fb107ddde1345a626c0050eb09d03ac420c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Sep 2018 13:46:13 +0200 Subject: [PATCH 04/12] CHANGELOG.md --- CHANGELOG.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 97c9eabaf..b40492e1d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,9 +3,20 @@ Release Notes ## Next Version +### New + +- [#409](https://github.com/groue/GRDB.swift/pull/409): DatabaseWriter.concurrentRead + + ### API diff ```diff + protocol DatabaseWriter : DatabaseReader { ++ func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future ++ @available(*, deprecated) + func readFromCurrentState(_ block: @escaping (Database) -> Void) throws + } + extension Cursor { + func isEmpty() throws -> Bool } From 47b42f38e3c116b86f4f9f2120780172e013ec64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Sep 2018 15:46:36 +0200 Subject: [PATCH 05/12] CHANGELOG.md --- CHANGELOG.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b40492e1d..8363ca492 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,11 @@ Release Notes + @available(*, deprecated) func readFromCurrentState(_ block: @escaping (Database) -> Void) throws } - + ++struct Future { ++ func wait() throws -> Value ++} + extension Cursor { + func isEmpty() throws -> Bool } From 41629ec9aa4a33ece0d5e0b5adc42a6bb98f8c0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Sep 2018 16:00:01 +0200 Subject: [PATCH 06/12] Future.wait() must be called only once --- GRDB/Core/DatabaseWriter.swift | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 1dd2317d9..ba94d6b2d 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -230,7 +230,8 @@ extension DatabaseWriter { } /// A future value. -public struct Future { +public class Future { + private var consumed = false private let _wait: () throws -> Value init(_ wait: @escaping () throws -> Value) { @@ -239,7 +240,11 @@ public struct Future { /// Blocks the current thread until the future value is available. /// Throws an error if the value could not be computed. + /// + /// It is a programmer error to call this method several times. public func wait() throws -> Value { + GRDBPrecondition(consumed == false, "Future.wait() must be called only once") + consumed = true return try _wait() } } From df406341c1d043a10969eb8759babe90f53286d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Sep 2018 16:00:53 +0200 Subject: [PATCH 07/12] CHANGELOG.md --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8363ca492..f65ec7838 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,7 @@ Release Notes func readFromCurrentState(_ block: @escaping (Database) -> Void) throws } -+struct Future { ++class Future { + func wait() throws -> Value +} From 2e6ed9d8f93bb95667ee85da73546ef5b0c5cbcb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Sep 2018 16:03:00 +0200 Subject: [PATCH 08/12] TODO --- TODO.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/TODO.md b/TODO.md index f4452b765..73e38da04 100644 --- a/TODO.md +++ b/TODO.md @@ -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 From 58a48b73aea0b4d979393ef95956521d63a19d9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Sep 2018 19:55:07 +0200 Subject: [PATCH 09/12] concurrentRead documentation --- GRDB/Core/DatabaseSnapshot.swift | 2 +- GRDB/Core/DatabaseWriter.swift | 7 +++-- README.md | 47 +++++++++++++++----------------- 3 files changed, 28 insertions(+), 28 deletions(-) diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 6beb4d5ed..423822fcf 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -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() } } diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index ba94d6b2d..44e26c778 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -238,11 +238,14 @@ public class Future { _wait = wait } - /// Blocks the current thread until the future value is available. - /// Throws an error if the value could not be computed. + /// 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() diff --git a/README.md b/README.md index a144077a7..df14634d2 100644 --- a/README.md +++ b/README.md @@ -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 = 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 From 8c479a863a2b43a181611aaac90b18c6b11abe70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Sep 2018 20:00:03 +0200 Subject: [PATCH 10/12] Documentation --- GRDB/Core/DatabaseWriter.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 44e26c778..e03446ba6 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -98,8 +98,8 @@ public protocol DatabaseWriter : DatabaseReader { /// 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. + /// 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: From b9a878bb2078b934479f1abadc47b293b4ba342c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 11 Sep 2018 08:56:29 +0200 Subject: [PATCH 11/12] Cleanup --- GRDB/Core/DatabasePool.swift | 9 +++------ GRDB/Core/DatabaseQueue.swift | 11 +++-------- GRDB/Core/DatabaseWriter.swift | 8 ++++---- 3 files changed, 10 insertions(+), 18 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index fadddcb60..6a5df7bb8 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -350,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. /// @@ -375,9 +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. - /// - /// :nodoc: - @available(*, deprecated) + @available(*, deprecated, message: "Use concurrentRead instead") public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws { // https://www.sqlite.org/isolation.html // @@ -466,9 +466,6 @@ extension DatabasePool : DatabaseReader { } } - /// See `DatabaseWriter.concurrentRead`. - /// - /// :nodoc: public func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future { // https://www.sqlite.org/isolation.html // diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 33a231b28..06148a0ba 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -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,11 +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) + @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 @@ -225,9 +223,6 @@ extension DatabaseQueue { } } - /// See `DatabaseWriter.concurrentRead`. - /// - /// :nodoc: public func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future { // DatabaseQueue can't perform parallel reads. let result = Result { diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index e03446ba6..c1b77e010 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -62,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. /// @@ -82,9 +84,7 @@ public protocol DatabaseWriter : DatabaseReader { /// } /// try db.execute("INSERT INTO player ...") /// } - /// - /// :nodoc: - @available(*, deprecated) + @available(*, deprecated, message: "Use concurrentRead instead") func readFromCurrentState(_ block: @escaping (Database) -> Void) throws /// Concurrently executes a read-only block that takes a @@ -282,7 +282,7 @@ public final class AnyDatabaseWriter : DatabaseWriter { } /// :nodoc: - @available(*, deprecated) + @available(*, deprecated, message: "Use concurrentRead instead") public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws { try base.readFromCurrentState(block) } From 7186cd98c8f69a0b2802970c51541093e4341998 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 13 Sep 2018 07:31:35 +0200 Subject: [PATCH 12/12] (more diff algorithms) --- CONTRIBUTING.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 38110ecfd..719804c45 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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