From bc7c3e5eb1129a9a39058ca858164a45729ca9a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 13 Jun 2019 08:45:49 +0200 Subject: [PATCH 1/9] DatabaseReader.asyncRead --- GRDB.xcodeproj/project.pbxproj | 16 +++--- GRDB/Core/DatabasePool.swift | 56 ++++++++++++++++++- GRDB/Core/DatabaseQueue.swift | 24 +++++++- GRDB/Core/DatabaseReader.swift | 54 ++++++++++++++---- GRDB/Core/DatabaseSnapshot.swift | 18 ++++++ GRDB/Core/DatabaseWriter.swift | 9 ++- GRDB/Record/FetchedRecordsController.swift | 2 +- .../{Result.swift => DatabaseResult.swift} | 6 +- .../ValueReducer/ValueReducer.swift | 2 +- GRDBCustom.xcodeproj/project.pbxproj | 12 ++-- 10 files changed, 166 insertions(+), 33 deletions(-) rename GRDB/Utils/{Result.swift => DatabaseResult.swift} (79%) diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index a0dd895ec..16546217c 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -372,9 +372,9 @@ 5659F4981EA8D989004A4992 /* Pool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F4971EA8D989004A4992 /* Pool.swift */; }; 5659F49B1EA8D989004A4992 /* Pool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F4971EA8D989004A4992 /* Pool.swift */; }; 5659F49E1EA8D989004A4992 /* Pool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F4971EA8D989004A4992 /* Pool.swift */; }; - 5659F4A01EA8D997004A4992 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F49F1EA8D997004A4992 /* Result.swift */; }; - 5659F4A31EA8D997004A4992 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F49F1EA8D997004A4992 /* Result.swift */; }; - 5659F4A61EA8D997004A4992 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F49F1EA8D997004A4992 /* Result.swift */; }; + 5659F4A01EA8D997004A4992 /* DatabaseResult.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F49F1EA8D997004A4992 /* DatabaseResult.swift */; }; + 5659F4A31EA8D997004A4992 /* DatabaseResult.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F49F1EA8D997004A4992 /* DatabaseResult.swift */; }; + 5659F4A61EA8D997004A4992 /* DatabaseResult.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F49F1EA8D997004A4992 /* DatabaseResult.swift */; }; 565B0FF01BBC7D980098DE03 /* FetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */; }; 565D5D721BBC694D00DC9BD4 /* Row+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */; }; 565D5D751BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */; }; @@ -1087,7 +1087,7 @@ 5659F4871EA8D94E004A4992 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = ""; }; 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadWriteBox.swift; sourceTree = ""; }; 5659F4971EA8D989004A4992 /* Pool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Pool.swift; sourceTree = ""; }; - 5659F49F1EA8D997004A4992 /* Result.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Result.swift; sourceTree = ""; }; + 5659F49F1EA8D997004A4992 /* DatabaseResult.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseResult.swift; sourceTree = ""; }; 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecordTests.swift; sourceTree = ""; }; 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = ""; }; 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+FoundationTests.swift"; sourceTree = ""; }; @@ -1740,12 +1740,12 @@ 5659F4861EA8D94E004A4992 /* Utils */ = { isa = PBXGroup; children = ( + 5659F49F1EA8D997004A4992 /* DatabaseResult.swift */, 563EF4492161F179007DAACD /* Inflections.swift */, 569BBA482291707D00478429 /* Inflections+English.swift */, 563EF414215F87EB007DAACD /* OrderedDictionary.swift */, 5659F4971EA8D989004A4992 /* Pool.swift */, 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */, - 5659F49F1EA8D997004A4992 /* Result.swift */, 5659F4871EA8D94E004A4992 /* Utils.swift */, ); path = Utils; @@ -2675,7 +2675,7 @@ 56D91AAB2205F2F100770D8D /* DatabasePromise.swift in Sources */, 566475A01D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 565490BB1D5AE236005622CB /* DatabaseReader.swift in Sources */, - 5659F4A61EA8D997004A4992 /* Result.swift in Sources */, + 5659F4A61EA8D997004A4992 /* DatabaseResult.swift in Sources */, 5674A6F81F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, 565490C31D5AE236005622CB /* RowAdapter.swift in Sources */, 5698AD3B1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, @@ -2840,7 +2840,7 @@ 5605F15E1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */, 5695962A222C462D002CB7C9 /* HasManyThroughAssociation.swift in Sources */, 563363C11C942C04000BE133 /* DatabaseReader.swift in Sources */, - 5659F4A31EA8D997004A4992 /* Result.swift in Sources */, + 5659F4A31EA8D997004A4992 /* DatabaseResult.swift in Sources */, 56B964BC1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 5605F1661C672E4000235C62 /* NSNull.swift in Sources */, 5656A8AE2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */, @@ -3323,7 +3323,7 @@ 5605F1591C672E4000235C62 /* CGFloat.swift in Sources */, 5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 564CE52021B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */, - 5659F4A01EA8D997004A4992 /* Result.swift in Sources */, + 5659F4A01EA8D997004A4992 /* DatabaseResult.swift in Sources */, 5605F1631C672E4000235C62 /* Date.swift in Sources */, 5605F1711C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */, diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index b1505f627..0221f8ba5 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -285,6 +285,58 @@ extension DatabasePool : DatabaseReader { } } + #if compiler(>=5.0) + /// Asynchronously executes a read-only block in a protected dispatch queue. + /// + /// let players = try dbQueue.asyncRead { result in + /// do { + /// let db = try result.get() + /// let count = try Player.fetchCount(db) + /// } catch { + /// // Handle error + /// } + /// } + /// + /// 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`. + /// + /// - parameter block: A block that accesses the database. + public func asyncRead(_ block: @escaping (Result) -> Void) { + // First async jump in order to grab a reader connection. + // Honor configuration dispatching (qos/targetQueue). + configuration + .makeDispatchQueue(defaultLabel: "GRDB.DatabasePool", purpose: "asyncRead") + .async { + do { + let (reader, releaseReader) = try self.readerPool.get() + + // Second async jump because sync could deadlock if + // configuration has a serial targetQueue. + reader.async { db in + defer { + try? db.commit() // Ignore commit error + releaseReader() + } + do { + // The block isolation comes from the DEFERRED transaction. + try db.beginTransaction(.deferred) + + // Reset the schema cache before running user code in snapshot isolation + db.schemaCache = SimpleDatabaseSchemaCache() + + block(.success(db)) + } catch { + block(.failure(error)) + } + } + } catch { + block(.failure(error)) + } + } + } + #endif + /// Synchronously executes a read-only block in a protected dispatch queue, /// and returns its result. /// @@ -381,7 +433,7 @@ extension DatabasePool : DatabaseReader { // The semaphore that blocks until futureResult is defined: let futureSemaphore = DispatchSemaphore(value: 0) - var futureResult: Result? = nil + var futureResult: DatabaseResult? = nil do { let (reader, releaseReader) = try readerPool.get() @@ -406,7 +458,7 @@ extension DatabasePool : DatabaseReader { db.schemaCache = SimpleDatabaseSchemaCache() // Fetch and release the future - futureResult = Result { try block(db) } + futureResult = DatabaseResult { try block(db) } futureSemaphore.signal() } } catch { diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 681ec901e..7d9d4a9a6 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -169,6 +169,28 @@ extension DatabaseQueue { } } + #if compiler(>=5.0) + /// Asynchronously executes a read-only block in a protected dispatch queue. + /// + /// let players = try dbQueue.asyncRead { result in + /// do { + /// let db = try result.get() + /// let count = try Player.fetchCount(db) + /// } catch { + /// // Handle error + /// } + /// } + /// + /// 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`. + /// + /// - parameter block: A block that accesses the database. + public func asyncRead(_ block: @escaping (Result) -> Void) { + writer.async { block(.success($0)) } + } + #endif + /// Synchronously executes a block in a protected dispatch queue, and /// returns its result. /// @@ -204,7 +226,7 @@ extension DatabaseQueue { public func concurrentRead(_ block: @escaping (Database) throws -> T) -> DatabaseFuture { // DatabaseQueue can't perform parallel reads. // Perform a blocking read instead. - return DatabaseFuture(Result { + return DatabaseFuture(DatabaseResult { // Check that we're on the writer queue... try writer.execute { db in // ... and that no transaction is opened. diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 2dcbc5413..f6ddf253a 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -33,14 +33,14 @@ public protocol DatabaseReader : class { /// /// try reader.read { db in /// // Those two values are guaranteed to be equal, even if the - /// // `wine` table is modified between the two requests: - /// let count1 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")! - /// let count2 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")! + /// // `player` table is modified between the two requests: + /// let count1 = try Player.fetchCount(db) + /// let count2 = try Player.fetchCount(db) /// } /// /// try reader.read { db in /// // Now this value may be different: - /// let count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")! + /// let count = try Player.fetchCount(db) /// } /// /// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds @@ -52,6 +52,33 @@ public protocol DatabaseReader : class { /// happen while establishing the read access to the database. func read(_ block: (Database) throws -> T) throws -> T + #if compiler(>=5.0) + /// Asynchronously executes a read-only block that takes a + /// database connection. + /// + /// Guarantee 1: the block argument is isolated. Eventual concurrent + /// database updates are not visible inside the block: + /// + /// try reader.asyncRead { result in + /// do ( + /// let db = try result.get() + /// // Those two values are guaranteed to be equal, even if the + /// // `player` table is modified between the two requests: + /// let count1 = try Player.fetchCount(db) + /// let count2 = try Player.fetchCount(db) + /// } catch { + /// // handle error + /// } + /// } + /// + /// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds + /// and SQLCipher, attempts to write in the database throw a DatabaseError + /// whose resultCode is `SQLITE_READONLY`. + /// + /// - parameter block: A block that accesses the database. + func asyncRead(_ block: @escaping (Result) -> Void) + #endif + /// Synchronously executes a read-only block that takes a database /// connection, and returns its result. /// @@ -62,9 +89,9 @@ public protocol DatabaseReader : class { /// /// try reader.unsafeRead { db in /// // Those two values may be different because some other thread - /// // may have inserted or deleted a wine between the two requests: - /// let count1 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")! - /// let count2 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")! + /// // may have inserted or deleted a player between the two requests: + /// let count1 = try Player.fetchCount(db) + /// let count2 = try Player.fetchCount(db) /// } /// /// Cursor iterations are isolated, though: @@ -93,9 +120,9 @@ public protocol DatabaseReader : class { /// /// try reader.unsafeReentrantRead { db in /// // Those two values may be different because some other thread - /// // may have inserted or deleted a wine between the two requests: - /// let count1 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")! - /// let count2 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")! + /// // may have inserted or deleted a player between the two requests: + /// let count1 = try Player.fetchCount(db) + /// let count2 = try Player.fetchCount(db) /// } /// /// Cursor iterations are isolated, though: @@ -218,6 +245,13 @@ public final class AnyDatabaseReader : DatabaseReader { return try base.read(block) } + #if compiler(>=5.0) + /// :nodoc: + public func asyncRead(_ block: @escaping (Result) -> Void) { + base.asyncRead(block) + } + #endif + /// :nodoc: public func unsafeRead(_ block: (Database) throws -> T) throws -> T { return try base.unsafeRead(block) diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index a7fa39557..52742752c 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -62,6 +62,24 @@ extension DatabaseSnapshot { return try serializedDatabase.sync(block) } + #if compiler(>=5.0) + /// Asynchronously executes a read-only block in a protected dispatch queue. + /// + /// let players = try snapshot.asyncRead { result in + /// do { + /// let db = try result.get() + /// let count = try Player.fetchCount(db) + /// } catch { + /// // Handle error + /// } + /// } + /// + /// - parameter block: A block that accesses the database. + public func asyncRead(_ block: @escaping (Result) -> Void) { + serializedDatabase.async { block(.success($0)) } + } + #endif + /// Alias for `read`. See `DatabaseReader.unsafeRead`. /// /// :nodoc: diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index e0b8b206d..c1f973b55 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -388,7 +388,7 @@ public class DatabaseFuture { _wait = wait } - init(_ result: Result) { + init(_ result: DatabaseResult) { _wait = result.get } @@ -429,6 +429,13 @@ public final class AnyDatabaseWriter : DatabaseWriter { return try base.read(block) } + #if compiler(>=5.0) + /// :nodoc: + public func asyncRead(_ block: @escaping (Result) -> Void) { + base.asyncRead(block) + } + #endif + /// :nodoc: public func unsafeRead(_ block: (Database) throws -> T) throws -> T { return try base.unsafeRead(block) diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 8238fc995..645783cb4 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -569,7 +569,7 @@ private func makeFetchFunction( controller: FetchedRecordsController, fetchAlongside: @escaping (Database) throws -> T, willProcessTransaction: @escaping () -> (), - completion: @escaping (Result<(fetchedItems: [Item], fetchedAlongside: T, observer: FetchedRecordsObserver)>) -> () + completion: @escaping (DatabaseResult<(fetchedItems: [Item], fetchedAlongside: T, observer: FetchedRecordsObserver)>) -> () ) -> (FetchedRecordsObserver) -> () { // Make sure we keep a weak reference to the fetched records controller, diff --git a/GRDB/Utils/Result.swift b/GRDB/Utils/DatabaseResult.swift similarity index 79% rename from GRDB/Utils/Result.swift rename to GRDB/Utils/DatabaseResult.swift index 028259c1a..9d142ef8d 100644 --- a/GRDB/Utils/Result.swift +++ b/GRDB/Utils/DatabaseResult.swift @@ -1,7 +1,7 @@ #if compiler(>=5.0) -typealias Result = Swift.Result +typealias DatabaseResult = Swift.Result #else -enum Result { +enum DatabaseResult { case success(Success) case failure(Error) @@ -13,7 +13,7 @@ enum Result { } } - func map(_ transform: (Success) -> T) -> Result { + func map(_ transform: (Success) -> T) -> DatabaseResult { switch self { case .success(let success): return .success(transform(success)) diff --git a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift index d480986b3..f77027198 100644 --- a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift +++ b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift @@ -40,7 +40,7 @@ extension ValueReducer { func fetchFuture(_ db: Database, writer: DatabaseWriter, requiringWriteAccess: Bool) -> DatabaseFuture { if requiringWriteAccess { // Synchronous fetch - return DatabaseFuture(Result { + return DatabaseFuture(DatabaseResult { var fetchedValue: Fetched! try db.inTransaction { fetchedValue = try fetch(db) diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 5321dc83d..ec118c411 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -249,8 +249,8 @@ 5659F4951EA8D964004A4992 /* ReadWriteBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */; }; 5659F49A1EA8D989004A4992 /* Pool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F4971EA8D989004A4992 /* Pool.swift */; }; 5659F49D1EA8D989004A4992 /* Pool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F4971EA8D989004A4992 /* Pool.swift */; }; - 5659F4A21EA8D997004A4992 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F49F1EA8D997004A4992 /* Result.swift */; }; - 5659F4A51EA8D997004A4992 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F49F1EA8D997004A4992 /* Result.swift */; }; + 5659F4A21EA8D997004A4992 /* DatabaseResult.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F49F1EA8D997004A4992 /* DatabaseResult.swift */; }; + 5659F4A51EA8D997004A4992 /* DatabaseResult.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F49F1EA8D997004A4992 /* DatabaseResult.swift */; }; 565EFAF11D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */; }; 565EFAF51D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */; }; 5665F868203EF4640084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F865203EF4590084C6C0 /* ColumnInfoTests.swift */; }; @@ -850,7 +850,7 @@ 5659F4871EA8D94E004A4992 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = ""; }; 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadWriteBox.swift; sourceTree = ""; }; 5659F4971EA8D989004A4992 /* Pool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Pool.swift; sourceTree = ""; }; - 5659F49F1EA8D997004A4992 /* Result.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Result.swift; sourceTree = ""; }; + 5659F49F1EA8D997004A4992 /* DatabaseResult.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseResult.swift; sourceTree = ""; }; 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecordTests.swift; sourceTree = ""; }; 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = ""; }; 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+FoundationTests.swift"; sourceTree = ""; }; @@ -1440,12 +1440,12 @@ 5659F4861EA8D94E004A4992 /* Utils */ = { isa = PBXGroup; children = ( + 5659F49F1EA8D997004A4992 /* DatabaseResult.swift */, 563EF44C2161F196007DAACD /* Inflections.swift */, 569BBA4B229170B300478429 /* Inflections+English.swift */, 563EF41E215F8A76007DAACD /* OrderedDictionary.swift */, 5659F4971EA8D989004A4992 /* Pool.swift */, 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */, - 5659F49F1EA8D997004A4992 /* Result.swift */, 5659F4871EA8D94E004A4992 /* Utils.swift */, ); path = Utils; @@ -2112,7 +2112,7 @@ 566B91181FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, F3BA80181CFB2876003DC1BA /* SerializedDatabase.swift in Sources */, 5674A7051F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, - 5659F4A51EA8D997004A4992 /* Result.swift in Sources */, + 5659F4A51EA8D997004A4992 /* DatabaseResult.swift in Sources */, 564CE52521B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */, F3BA800D1CFB2871003DC1BA /* DatabasePool.swift in Sources */, 5656A87C2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift in Sources */, @@ -2443,7 +2443,7 @@ 566B91151FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, F3BA80741CFB2E55003DC1BA /* SerializedDatabase.swift in Sources */, 5674A7041F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, - 5659F4A21EA8D997004A4992 /* Result.swift in Sources */, + 5659F4A21EA8D997004A4992 /* DatabaseResult.swift in Sources */, 564CE52421B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */, F3BA80691CFB2E55003DC1BA /* DatabasePool.swift in Sources */, 5656A87B2295BD56001FF3FF /* QueryInterfaceRequest+Association.swift in Sources */, From b715ca5eb8ccf4756ecde1be539d94fadde1fbaf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 13 Jun 2019 13:20:59 +0200 Subject: [PATCH 2/9] DatabaseWriter.asyncWrite --- GRDB/Core/DatabasePool.swift | 121 ++++++++--------------- GRDB/Core/DatabaseQueue.swift | 95 +++++++----------- GRDB/Core/DatabaseWriter.swift | 175 +++++++++++++++++++++++++-------- 3 files changed, 214 insertions(+), 177 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 0221f8ba5..65eb39910 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -499,116 +499,81 @@ extension DatabasePool : DatabaseReader { // MARK: - Writing in Database - /// Synchronously executes an update block in a protected dispatch queue, - /// wrapped inside a transaction, and returns the result of the block. + /// Synchronously executes database updates in a protected dispatch queue, + /// outside of any transaction, and returns the result. /// - /// Eventual concurrent database updates are postponed until the block - /// has executed. + /// Eventual concurrent database updates are postponed until the updates + /// are completed. /// - /// try dbPool.write { db in - /// try db.execute(...) - /// } - /// - /// Eventual concurrent reads are guaranteed not to see any changes - /// performed in the block until they are all saved in the database. + /// Eventual concurrent reads may see partial updates unless you wrap them + /// in a transaction. /// /// This method is *not* reentrant. /// - /// - parameters block: A block that executes SQL statements. - /// - throws: The error thrown by the block, or by the wrapping transaction. - public func write(_ block: (Database) throws -> T) throws -> T { - return try writer.sync { db in - var result: T? = nil - try db.inTransaction { - result = try block(db) - return .commit - } - return result! - } + /// - parameter updates: The updates to the database. + /// - throws: The error thrown by the updates. + public func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { + return try writer.sync(updates) } - /// Synchronously executes a block that takes a database connection, and - /// returns its result. + /// Synchronously executes database updates in a protected dispatch queue, + /// wrapped inside a transaction, and returns the result. /// - /// Eventual concurrent database updates are postponed until the block - /// has executed. - /// - /// Eventual concurrent reads may see changes performed in the block before - /// the block completes. - /// - /// The block is guaranteed to be executed outside of a transaction. - /// - /// This method is *not* reentrant. - /// - /// - parameters block: A block that executes SQL statements and return - /// either .commit or .rollback. - /// - throws: The error thrown by the block. - public func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T { - return try writer.sync(block) - } - - /// Synchronously executes a block in a protected dispatch queue, wrapped - /// inside a transaction. - /// - /// Eventual concurrent database updates are postponed until the block - /// has executed. - /// - /// If the block throws an error, the transaction is rollbacked and the - /// error is rethrown. If the block returns .rollback, the transaction is + /// If the updates throws an error, the transaction is rollbacked and the + /// error is rethrown. If the updates return .rollback, the transaction is /// also rollbacked, but no error is thrown. /// + /// Eventual concurrent database updates are postponed until the transaction + /// has completed. + /// + /// Eventual concurrent reads are guaranteed to not see any partial updates + /// of the database until the transaction has completed. + /// + /// This method is *not* reentrant. + /// /// try dbPool.writeInTransaction { db in /// db.execute(...) /// return .commit /// } /// - /// Eventual concurrent reads are guaranteed not to see any changes - /// performed in the block until they are all saved in the database. - /// - /// This method is *not* reentrant. - /// /// - parameters: /// - kind: The transaction type (default nil). If nil, the transaction /// type is configuration.defaultTransactionKind, which itself /// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html /// for more information. - /// - block: A block that executes SQL statements and return either - /// .commit or .rollback. - /// - throws: The error thrown by the block, or any error establishing the - /// transaction. - public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws { + /// - updates: The updates to the database. + /// - throws: The error thrown by the updates, or by the + /// wrapping transaction. + public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ updates: (Database) throws -> Database.TransactionCompletion) throws { try writer.sync { db in try db.inTransaction(kind) { - try block(db) + try updates(db) } } } - /// Synchronously executes an update block in a protected dispatch queue, - /// and returns its result. + /// Synchronously executes database updates in a protected dispatch queue, + /// outside of any transaction, and returns the result. /// - /// Eventual concurrent database updates are postponed until the block - /// has executed. + /// Eventual concurrent database updates are postponed until the updates + /// are completed. /// - /// try dbPool.unsafeReentrantWrite { db in - /// try db.execute(...) - /// } + /// Eventual concurrent reads may see partial updates unless you wrap them + /// in a transaction. /// - /// Eventual concurrent reads may see changes performed in the block before - /// the block completes. - /// - /// This method is reentrant. It is unsafe because it fosters dangerous - /// concurrency practices. - public func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T { - return try writer.reentrantSync(block) + /// This method is reentrant. It should be avoided because it fosters + /// dangerous concurrency practices. + public func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T { + return try writer.reentrantSync(updates) } - /// Asynchronously executes an update block in a protected dispatch queue. + /// Asynchronously executes database updates in a protected dispatch queue, + /// outside of any transaction. /// - /// Eventual concurrent reads may see changes performed in the block before - /// the block completes. - public func asyncWriteWithoutTransaction(_ block: @escaping (Database) -> Void) { - writer.async(block) + /// Eventual concurrent reads may see partial updates unless you wrap them + /// in a transaction. + public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { + writer.async(updates) } // MARK: - Functions diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 7d9d4a9a6..d620215b1 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -240,80 +240,55 @@ extension DatabaseQueue { // MARK: - Writing in Database - /// Synchronously executes a block in a protected dispatch queue, wrapped - /// inside a transaction. + /// Synchronously executes database updates in a protected dispatch queue, + /// wrapped inside a transaction, and returns the result. /// - /// If the block throws an error, the transaction is rollbacked and the - /// error is rethrown. - /// - /// try dbQueue.write { db in - /// try Player(...).insert(db) - /// } - /// - /// This method is *not* reentrant. - /// - /// - parameter block: A block that executes SQL statements. - /// - throws: An eventual database error, or the error thrown by the block. - public func write(_ block: (Database) throws -> T) throws -> T { - return try writer.sync { db in - var result: T? = nil - try db.inTransaction { - result = try block(db) - return .commit - } - return result! - } - } - - /// Synchronously executes a block in a protected dispatch queue, wrapped - /// inside a transaction. - /// - /// If the block throws an error, the transaction is rollbacked and the - /// error is rethrown. If the block returns .rollback, the transaction is + /// If the updates throws an error, the transaction is rollbacked and the + /// error is rethrown. If the updates return .rollback, the transaction is /// also rollbacked, but no error is thrown. /// - /// try dbQueue.inTransaction { db in - /// try Player(...).insert(db) - /// return .commit - /// } + /// Eventual concurrent database accesses are postponed until the + /// transaction has completed. /// /// This method is *not* reentrant. /// + /// try dbQueue.writeInTransaction { db in + /// db.execute(...) + /// return .commit + /// } + /// /// - parameters: /// - kind: The transaction type (default nil). If nil, the transaction /// type is configuration.defaultTransactionKind, which itself /// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html /// for more information. - /// - block: A block that executes SQL statements and return either - /// .commit or .rollback. - /// - throws: The error thrown by the block. - public func inTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws { + /// - updates: The updates to the database. + /// - throws: The error thrown by the updates, or by the + /// wrapping transaction. + public func inTransaction(_ kind: Database.TransactionKind? = nil, _ updates: (Database) throws -> Database.TransactionCompletion) throws { try writer.sync { db in try db.inTransaction(kind) { - try block(db) + try updates(db) } } } - /// Synchronously executes a block in a protected dispatch queue, and - /// returns its result. + /// Synchronously executes database updates in a protected dispatch queue, + /// outside of any transaction, and returns the result. /// - /// let players = try dbQueue.writeWithoutTransaction { db in - /// try Player(...).insert(db) - /// } + /// Eventual concurrent database accesses are postponed until the updates + /// are completed. /// /// This method is *not* reentrant. /// - /// - parameter block: A block that accesses the database. - /// - throws: The error thrown by the block. - /// - /// :nodoc: - public func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T { - return try writer.sync(block) + /// - parameter updates: The updates to the database. + /// - throws: The error thrown by the updates. + public func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { + return try writer.sync(updates) } - /// Synchronously executes a block in a protected dispatch queue, and - /// returns its result. + /// Synchronously executes database updates in a protected dispatch queue, + /// outside of any transaction, and returns the result. /// /// // INSERT INTO player ... /// let players = try dbQueue.inDatabase { db in @@ -324,12 +299,12 @@ extension DatabaseQueue { /// /// - parameter block: A block that accesses the database. /// - throws: The error thrown by the block. - public func inDatabase(_ block: (Database) throws -> T) rethrows -> T { - return try writer.sync(block) + public func inDatabase(_ updates: (Database) throws -> T) rethrows -> T { + return try writer.sync(updates) } - /// Synchronously executes a block in a protected dispatch queue, and - /// returns its result. + /// Synchronously executes database updates in a protected dispatch queue, and + /// returns the result. /// /// // INSERT INTO player ... /// try dbQueue.unsafeReentrantWrite { db in @@ -338,12 +313,14 @@ extension DatabaseQueue { /// /// This method is reentrant. It is unsafe because it fosters dangerous /// concurrency practices. - public func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T { - return try writer.reentrantSync(block) + public func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T { + return try writer.reentrantSync(updates) } - public func asyncWriteWithoutTransaction(_ block: @escaping (Database) -> Void) { - writer.async(block) + /// Asynchronously executes database updates in a protected dispatch queue, + /// outside of any transaction. + public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { + writer.async(updates) } // MARK: - Functions diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index c1f973b55..2d9eaf2c7 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -21,54 +21,82 @@ public protocol DatabaseWriter : DatabaseReader { var configuration: Configuration { get } // MARK: - Writing in Database - - /// Synchronously executes a block that takes a database connection, and - /// returns its result. + + /// Synchronously executes database updates in a protected dispatch queue, + /// wrapped inside a transaction, and returns the result. /// - /// Eventual concurrent database updates are postponed until the block - /// has executed. + /// If the updates throw an error, the transaction is rollbacked and the + /// error is rethrown. /// - /// Eventual concurrent reads are guaranteed not to see any changes - /// performed in the block until they are all saved in the database. + /// Eventual concurrent database updates are postponed until the transaction + /// has completed. /// - /// The block may, or may not, be wrapped inside a transaction. + /// Eventual concurrent reads are guaranteed to not see any partial updates + /// of the database until the transaction has completed. /// /// This method is *not* reentrant. - func write(_ block: (Database) throws -> T) throws -> T + /// + /// - parameter updates: The updates to the database. + /// - throws: The error thrown by the updates, or by the + /// wrapping transaction. + func write(_ updates: (Database) throws -> T) throws -> T - /// Synchronously executes a block that takes a database connection, and - /// returns its result. + /// Synchronously executes database updates in a protected dispatch queue, + /// outside of any transaction, and returns the result. /// - /// Eventual concurrent database updates are postponed until the block - /// has executed. + /// Eventual concurrent database updates are postponed until the updates + /// are completed. /// - /// Eventual concurrent reads may see changes performed in the block before - /// the block completes. - /// - /// The block is guaranteed to be executed outside of a transaction. + /// Eventual concurrent reads may see partial updates unless you wrap them + /// in a transaction. /// /// This method is *not* reentrant. - func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T + /// + /// - parameter updates: The updates to the database. + /// - throws: The error thrown by the updates. + func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T - /// Synchronously executes a block that takes a database connection, and - /// returns its result. + /// Asynchronously executes database updates in a protected dispatch queue, + /// wrapped inside a transaction. /// - /// Eventual concurrent database updates are postponed until the block - /// has executed. + /// If the updates throw an error, the transaction is rollbacked. /// - /// Eventual concurrent reads may see changes performed in the block before - /// the block completes. + /// The *completion* closure is always called. Its argument is an eventual + /// error if the transaction could not be committed. + /// + /// Eventual concurrent database updates are postponed until the transaction + /// and the *completion* closure have completed. + /// + /// Eventual concurrent reads are guaranteed to not see any partial updates + /// of the database until the transaction has completed. + /// + /// This method is *not* reentrant. + /// + /// - parameter updates: The updates to the database. + /// - parameter completion: A closure that is called with the eventual + /// transaction error. + /// - throws: The error thrown by the updates, or by the wrapping transaction. + func asyncWrite(_ updates: @escaping (Database) throws -> Void, completion: @escaping (Error?) -> Void) + + /// Asynchronously executes database updates in a protected dispatch queue, + /// outside of any transaction. + /// + /// Eventual concurrent reads may see partial updates unless you wrap them + /// in a transaction. + func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) + + /// Synchronously executes database updates in a protected dispatch queue, + /// outside of any transaction, and returns the result. + /// + /// Eventual concurrent database updates are postponed until the updates + /// are completed. + /// + /// Eventual concurrent reads may see partial updates unless you wrap them + /// in a transaction. /// /// This method is reentrant. It should be avoided because it fosters /// dangerous concurrency practices. - func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T - - /// Asynchronously executes a block that takes a database connection, and - /// returns its result. - /// - /// Eventual concurrent reads may see changes performed in the block before - /// the block completes. - func asyncWriteWithoutTransaction(_ block: @escaping (Database) -> Void) + func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T // MARK: - Reading from Database @@ -108,6 +136,68 @@ public protocol DatabaseWriter : DatabaseReader { } extension DatabaseWriter { + + /// Synchronously executes database updates in a protected dispatch queue, + /// wrapped inside a transaction, and returns the result. + /// + /// If the updates throw an error, the transaction is rollbacked and the + /// error is rethrown. + /// + /// Eventual concurrent database updates are postponed until the transaction + /// has completed. + /// + /// Eventual concurrent reads are guaranteed to not see any partial updates + /// of the database until the transaction has completed. + /// + /// This method is *not* reentrant. + /// + /// - parameter updates: The updates to the database. + /// - throws: The error thrown by the updates, or by the + /// wrapping transaction. + public func write(_ updates: (Database) throws -> T) throws -> T { + return try writeWithoutTransaction { db in + var result: T? = nil + try db.inTransaction { + result = try updates(db) + return .commit + } + return result! + } + } + + /// Asynchronously executes database updates in a protected dispatch queue, + /// wrapped inside a transaction. + /// + /// If the updates throw an error, the transaction is rollbacked. + /// + /// The *completion* closure is always called. Its argument is an eventual + /// error if the transaction could not be committed. + /// + /// Eventual concurrent database updates are postponed until the transaction + /// and the *completion* closure have completed. + /// + /// Eventual concurrent reads are guaranteed to not see any partial updates + /// of the database until the transaction has completed. + /// + /// This method is *not* reentrant. + /// + /// - parameter updates: The updates to the database. + /// - parameter completion: A closure that is called with the eventual + /// transaction error. + /// - throws: The error thrown by the updates, or by the wrapping transaction. + public func asyncWrite(_ updates: @escaping (Database) throws -> Void, completion: @escaping (Error?) -> Void) { + asyncWriteWithoutTransaction { db in + do { + try db.inTransaction { + try updates(db) + return .commit + } + completion(nil) + } catch { + completion(error) + } + } + } // MARK: - Transaction Observers @@ -454,23 +544,28 @@ public final class AnyDatabaseWriter : DatabaseWriter { // MARK: - Writing in Database /// :nodoc: - public func write(_ block: (Database) throws -> T) throws -> T { - return try base.write(block) + public func write(_ updates: (Database) throws -> T) throws -> T { + return try base.write(updates) } /// :nodoc: - public func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T { - return try base.writeWithoutTransaction(block) + public func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { + return try base.writeWithoutTransaction(updates) } /// :nodoc: - public func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T { - return try base.unsafeReentrantWrite(block) + public func asyncWrite(_ updates: @escaping (Database) throws -> Void, completion: @escaping (Error?) -> Void) { + base.asyncWrite(updates, completion: completion) } /// :nodoc: - public func asyncWriteWithoutTransaction(_ block: @escaping (Database) -> Void) { - base.asyncWriteWithoutTransaction(block) + public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { + base.asyncWriteWithoutTransaction(updates) + } + + /// :nodoc: + public func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T { + return try base.unsafeReentrantWrite(updates) } // MARK: - Functions From 0ad819902db498b47674cbcfc4ec7375dfea3845 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 13 Jun 2019 13:42:31 +0200 Subject: [PATCH 3/9] Tests for asyncRead, asyncWrite, asyncWriteWithoutTransaction --- GRDB/Core/DatabaseQueue.swift | 4 +- Tests/GRDBTests/DatabaseReaderTests.swift | 52 ++++++++++++ Tests/GRDBTests/DatabaseWriterTests.swift | 99 +++++++++++++++++++++++ 3 files changed, 154 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index d620215b1..3ce475757 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -187,7 +187,9 @@ extension DatabaseQueue { /// /// - parameter block: A block that accesses the database. public func asyncRead(_ block: @escaping (Result) -> Void) { - writer.async { block(.success($0)) } + writer.async { db in + db.readOnly { block(.success(db)) } + } } #endif diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index 7aac58fa6..6d2259949 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -72,4 +72,56 @@ class DatabaseReaderTests : GRDBTestCase { let reader: DatabaseReader = DatabaseQueue() let _: DatabaseReader = AnyDatabaseReader(reader) } + + func testAsyncRead() throws { + func test(_ dbReader: DatabaseReader) throws { + let expectation = self.expectation(description: "updates") + let semaphore = DispatchSemaphore(value: 0) + var count: Int? + dbReader.asyncRead { db in + // Make sure this block executes asynchronously + semaphore.wait() + do { + count = try Int.fetchOne(db.get(), sql: "SELECT COUNT(*) FROM sqlite_master") + } catch { + XCTFail("Unexpected error: \(error)") + } + expectation.fulfill() + } + semaphore.signal() + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertNotNil(count) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + try test(makeDatabasePool().makeSnapshot()) + } + + func testAsyncReadPreventsDatabaseModification() throws { + func test(_ dbReader: DatabaseReader) throws { + let expectation = self.expectation(description: "updates") + let semaphore = DispatchSemaphore(value: 0) + dbReader.asyncRead { db in + // Make sure this block executes asynchronously + semaphore.wait() + do { + try db.get().execute(sql: "CREATE TABLE testAsyncReadPreventsDatabaseModification (a)") + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_READONLY) + } catch { + XCTFail("Unexpected error: \(error)") + } + expectation.fulfill() + } + semaphore.signal() + waitForExpectations(timeout: 1, handler: nil) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + try test(makeDatabasePool().makeSnapshot()) + } } diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index 6357e6e08..0e29153fe 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -43,6 +43,105 @@ class DatabaseWriterTests : GRDBTestCase { } } + func testAsyncWriteWithoutTransactionSuccess() throws { + func test(_ dbWriter: DatabaseWriter) throws { + let expectation = self.expectation(description: "updates") + let semaphore = DispatchSemaphore(value: 0) + dbWriter.asyncWriteWithoutTransaction { db in + // Make sure this block executes asynchronously + semaphore.wait() + do { + try db.execute(sql: "CREATE TABLE testAsyncWriteWithoutTransaction (a)") + } catch { + XCTFail("Unexpected error: \(error)") + } + expectation.fulfill() + } + semaphore.signal() + + waitForExpectations(timeout: 1, handler: nil) + let tableExists = try dbWriter.read { try $0.tableExists("testAsyncWriteWithoutTransaction") } + XCTAssertTrue(tableExists) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func testAsyncWriteWithoutTransactionError() throws { + func test(_ dbWriter: DatabaseWriter) throws { + let expectation = self.expectation(description: "updates") + let semaphore = DispatchSemaphore(value: 0) + dbWriter.asyncWriteWithoutTransaction { db in + // Make sure this block executes asynchronously + semaphore.wait() + do { + try db.execute(sql: "This is not SQL") + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.sql, "This is not SQL") + } catch { + XCTFail("Unexpected error: \(error)") + } + expectation.fulfill() + } + semaphore.signal() + waitForExpectations(timeout: 1, handler: nil) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func testAsyncWriteSuccess() throws { + func test(_ dbWriter: DatabaseWriter) throws { + let expectation = self.expectation(description: "updates") + let semaphore = DispatchSemaphore(value: 0) + dbWriter.asyncWrite({ db in + // Make sure this block executes asynchronously + semaphore.wait() + try db.execute(sql: "CREATE TABLE testAsyncWrite (a)") + }, completion: { error in + if let error = error { + XCTFail("Unexpected error: \(error)") + } + expectation.fulfill() + }) + semaphore.signal() + + waitForExpectations(timeout: 1, handler: nil) + let tableExists = try dbWriter.read { try $0.tableExists("testAsyncWrite") } + XCTAssertTrue(tableExists) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func testAsyncWriteError() throws { + func test(_ dbWriter: DatabaseWriter) throws { + let expectation = self.expectation(description: "updates") + let semaphore = DispatchSemaphore(value: 0) + dbWriter.asyncWrite({ db in + // Make sure this block executes asynchronously + semaphore.wait() + try db.execute(sql: "This is not SQL") + }, completion: { error in + guard let error = error as? DatabaseError else { + XCTFail("Unexpected error") + return + } + XCTAssertEqual(error.sql, "This is not SQL") + expectation.fulfill() + }) + semaphore.signal() + waitForExpectations(timeout: 1, handler: nil) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + func testAnyDatabaseWriter() { // This test passes if this code compiles. let writer: DatabaseWriter = DatabaseQueue() From f7946834f19c19889ef226d70303b59f6b797465 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 13 Jun 2019 14:14:35 +0200 Subject: [PATCH 4/9] Fix compiler checks for async methods --- GRDB/Core/DatabaseWriter.swift | 31 +++++++++++++++-------- Tests/GRDBTests/DatabaseReaderTests.swift | 4 +++ Tests/GRDBTests/DatabaseWriterTests.swift | 26 ++++++++++++++----- 3 files changed, 43 insertions(+), 18 deletions(-) diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 2d9eaf2c7..156ecdcdc 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -56,13 +56,15 @@ public protocol DatabaseWriter : DatabaseReader { /// - throws: The error thrown by the updates. func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T + #if compiler(>=5.0) /// Asynchronously executes database updates in a protected dispatch queue, /// wrapped inside a transaction. /// /// If the updates throw an error, the transaction is rollbacked. /// - /// The *completion* closure is always called. Its argument is an eventual - /// error if the transaction could not be committed. + /// The *completion* closure is always called with the result of the + /// database updates. Its argument is a failure if the transaction could not + /// be committed. /// /// Eventual concurrent database updates are postponed until the transaction /// and the *completion* closure have completed. @@ -76,7 +78,8 @@ public protocol DatabaseWriter : DatabaseReader { /// - parameter completion: A closure that is called with the eventual /// transaction error. /// - throws: The error thrown by the updates, or by the wrapping transaction. - func asyncWrite(_ updates: @escaping (Database) throws -> Void, completion: @escaping (Error?) -> Void) + func asyncWrite(_ updates: @escaping (Database) throws -> T, completion: @escaping (Result) -> Void) + #endif /// Asynchronously executes database updates in a protected dispatch queue, /// outside of any transaction. @@ -156,7 +159,7 @@ extension DatabaseWriter { /// wrapping transaction. public func write(_ updates: (Database) throws -> T) throws -> T { return try writeWithoutTransaction { db in - var result: T? = nil + var result: T? try db.inTransaction { result = try updates(db) return .commit @@ -165,13 +168,15 @@ extension DatabaseWriter { } } + #if compiler(>=5.0) /// Asynchronously executes database updates in a protected dispatch queue, /// wrapped inside a transaction. /// /// If the updates throw an error, the transaction is rollbacked. /// - /// The *completion* closure is always called. Its argument is an eventual - /// error if the transaction could not be committed. + /// The *completion* closure is always called with the result of the + /// database updates. Its argument is a failure if the transaction could not + /// be committed. /// /// Eventual concurrent database updates are postponed until the transaction /// and the *completion* closure have completed. @@ -185,19 +190,21 @@ extension DatabaseWriter { /// - parameter completion: A closure that is called with the eventual /// transaction error. /// - throws: The error thrown by the updates, or by the wrapping transaction. - public func asyncWrite(_ updates: @escaping (Database) throws -> Void, completion: @escaping (Error?) -> Void) { + public func asyncWrite(_ updates: @escaping (Database) throws -> T, completion: @escaping (Result) -> Void) { asyncWriteWithoutTransaction { db in do { + var result: T? try db.inTransaction { - try updates(db) + result = try updates(db) return .commit } - completion(nil) + completion(.success(result!)) } catch { - completion(error) + completion(.failure(error)) } } } + #endif // MARK: - Transaction Observers @@ -553,10 +560,12 @@ public final class AnyDatabaseWriter : DatabaseWriter { return try base.writeWithoutTransaction(updates) } + #if compiler(>=5.0) /// :nodoc: - public func asyncWrite(_ updates: @escaping (Database) throws -> Void, completion: @escaping (Error?) -> Void) { + public func asyncWrite(_ updates: @escaping (Database) throws -> T, completion: @escaping (Result) -> Void) { base.asyncWrite(updates, completion: completion) } + #endif /// :nodoc: public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index 6d2259949..c8fdd1850 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -73,6 +73,7 @@ class DatabaseReaderTests : GRDBTestCase { let _: DatabaseReader = AnyDatabaseReader(reader) } + #if compiler(>=5.0) func testAsyncRead() throws { func test(_ dbReader: DatabaseReader) throws { let expectation = self.expectation(description: "updates") @@ -98,7 +99,9 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) } + #endif + #if compiler(>=5.0) func testAsyncReadPreventsDatabaseModification() throws { func test(_ dbReader: DatabaseReader) throws { let expectation = self.expectation(description: "updates") @@ -124,4 +127,5 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) } + #endif } diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index 0e29153fe..b11b8c2cf 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -93,6 +93,7 @@ class DatabaseWriterTests : GRDBTestCase { try test(makeDatabasePool()) } + #if compiler(>=5.0) func testAsyncWriteSuccess() throws { func test(_ dbWriter: DatabaseWriter) throws { let expectation = self.expectation(description: "updates") @@ -101,8 +102,11 @@ class DatabaseWriterTests : GRDBTestCase { // Make sure this block executes asynchronously semaphore.wait() try db.execute(sql: "CREATE TABLE testAsyncWrite (a)") - }, completion: { error in - if let error = error { + }, completion: { result in + switch result { + case .success: + break + case let .failure(error): XCTFail("Unexpected error: \(error)") } expectation.fulfill() @@ -117,7 +121,9 @@ class DatabaseWriterTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) } + #endif + #if compiler(>=5.0) func testAsyncWriteError() throws { func test(_ dbWriter: DatabaseWriter) throws { let expectation = self.expectation(description: "updates") @@ -126,12 +132,17 @@ class DatabaseWriterTests : GRDBTestCase { // Make sure this block executes asynchronously semaphore.wait() try db.execute(sql: "This is not SQL") - }, completion: { error in - guard let error = error as? DatabaseError else { - XCTFail("Unexpected error") - return + }, completion: { result in + switch result { + case .success: + XCTFail("Expected error") + case let .failure(error): + if let error = error as? DatabaseError { + XCTAssertEqual(error.sql, "This is not SQL") + } else { + XCTFail("Unexpected error: \(error)") + } } - XCTAssertEqual(error.sql, "This is not SQL") expectation.fulfill() }) semaphore.signal() @@ -141,6 +152,7 @@ class DatabaseWriterTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) } + #endif func testAnyDatabaseWriter() { // This test passes if this code compiles. From 3897e9824c0d63425e719f726825829ad8717689 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 13 Jun 2019 19:20:46 +0200 Subject: [PATCH 5/9] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fe4dbef6c..a19079a12 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -58,6 +58,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: - [#542](https://github.com/groue/GRDB.swift/pull/542): Move eager loading of hasMany associations to FetchRequest - [#546](https://github.com/groue/GRDB.swift/pull/546) by [@robcas3](https://github.com/robcas3): Fix SPM errors with Xcode 11 beta - [#549](https://github.com/groue/GRDB.swift/pull/549) Support for Combine +- [#550](https://github.com/groue/GRDB.swift/pull/550) Asynchronous Database Access Methods ### Documentation Diff From d18c65fbe5bbc392669bbca6f3146a1b1190e7da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 13 Jun 2019 20:06:58 +0200 Subject: [PATCH 6/9] Documentation for asynchronous APIs --- README.md | 88 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 87 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c45d1770e..ced16ab73 100644 --- a/README.md +++ b/README.md @@ -7970,6 +7970,7 @@ You can catch those errors and wait for [UIApplicationDelegate.applicationProtec - [Advanced DatabasePool](#advanced-databasepool) - [Database Snapshots](#database-snapshots) - [DatabaseWriter and DatabaseReader Protocols](#databasewriter-and-databasereader-protocols) +- [Asynchronous APIs](#asynchronous-apis) - [Unsafe Concurrency APIs](#unsafe-concurrency-apis) - [Dealing with External Connections](#dealing-with-external-connections) @@ -8294,9 +8295,94 @@ let component = MyReadOnlyComponent(reader: dbQueue) > ``` +### Asynchronous APIs + +**Database queues, pools, snapshots, as well as their common protocols `DatabaseReader` and `DatabaseWriter` provide asynchronous database access methods.** + +- **`asyncRead`** + + The `asyncRead` method can be used from any thread. It submits your database statements for asynchronous execution on a protected dispatch queue: + + ```swift + reader.asyncRead { result: Result in + try { + let db = try result.get() + let players = try Player.fetchAll(db) + } catch { + // handle error + } + } + ``` + + The argument function accepts a standard `Result` which may contain a failure if it was impossible to start a reading access to the database. + + Any attempt at modifying the database throws an error. + + When you use a [database queue](#database-queues) or a [database snapshot](#database-snapshots), the read has to wait for any eventual concurrent database access performed by this queue or snapshot to complete. + + When you use a [database pool](#database-pools), reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be [configured](#databasepool-configuration). + +- **`asyncWrite`** + + The `asyncWrite` method can be used from any thread. It submits your database statements for asynchronous execution on a protected dispatch queue, wrapped inside a [database transaction](#transactions-and-savepoints): + + ```swift + writer.asyncWrite({ db: Database in + try Player(...).insert(db) + }, completion: { result: Result in + switch result { + case let .success: + // handle transaction success + case let .failure(error): + // handle transaction error + } + }) + ``` + + `asyncWrite` accepts two function arguments. The first one executes your database updates. The second one is a completion function which accepts the result of the asynchronous transaction. + + On the first unhandled error during database updates, all changes are reverted, the whole transaction is rollbacked, and the error is passed to the completion function. + + When the transaction completes successfully, the result of the first function is contained in the standard `Result` passed to the completion function: + + ```swift + writer.asyncWrite({ db: Database in + try Player(...).insert(db) + return try Player.fetchCount(db) + }, completion: { result: Result in + switch result { + case let .success(newPlayerCount): + // handle value and transaction success + case let .failure(error): + // handle transaction error + } + }) + ``` + + The scheduled asynchronous transaction has to wait for any eventual concurrent database write to complete before it can start. + +- **`asyncWriteWithoutTransaction`** + + The `asyncWriteWithoutTransaction` method can be used from any thread. It submits your database statements for asynchronous execution on a protected dispatch queue, outside of any transaction: + + ```swift + reader.asyncWriteWithoutTransaction { db in + try { + try Player(...).insert(db) + } catch { + // handle error + } + } + ``` + + **Writing outside of any transaction is dangerous.** Please see [Transactions and Savepoints](#transactions-and-savepoints) for more information. + + The scheduled asynchronous updates have to wait for any eventual concurrent database write to complete before they can start. + + ### Unsafe Concurrency APIs -**Database queues, pools, snapshots, as well as their common protocols `DatabaseReader` and `DatabaseWriter` provide *unsafe* APIs.** Unsafe APIs lift [concurrency guarantees](#guarantees-and-rules), and allow advanced yet unsafe patterns. +**Database queues, pools, snapshots, as well as their common protocols `DatabaseReader` and `DatabaseWriter` provide *unsafe* database access methods.** Unsafe APIs lift [concurrency guarantees](#guarantees-and-rules), and allow advanced yet unsafe patterns. - **`unsafeRead`** From d0e839c2b4a7f718da06579e333771205376778e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 13 Jun 2019 20:13:19 +0200 Subject: [PATCH 7/9] Note about availability of asynchronous APIs --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ced16ab73..ce788270c 100644 --- a/README.md +++ b/README.md @@ -8321,6 +8321,8 @@ let component = MyReadOnlyComponent(reader: dbQueue) When you use a [database queue](#database-queues) or a [database snapshot](#database-snapshots), the read has to wait for any eventual concurrent database access performed by this queue or snapshot to complete. When you use a [database pool](#database-pools), reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be [configured](#databasepool-configuration). + + > :point_up: **Note**: because it uses the standard `Result` type, `asyncRead` is only available with a Swift 5+ compiler, starting Xcode 10.2. - **`asyncWrite`** @@ -8360,13 +8362,15 @@ let component = MyReadOnlyComponent(reader: dbQueue) ``` The scheduled asynchronous transaction has to wait for any eventual concurrent database write to complete before it can start. + + > :point_up: **Note**: because it uses the standard `Result` type, `asyncWrite` is only available with a Swift 5+ compiler, starting Xcode 10.2. - **`asyncWriteWithoutTransaction`** The `asyncWriteWithoutTransaction` method can be used from any thread. It submits your database statements for asynchronous execution on a protected dispatch queue, outside of any transaction: ```swift - reader.asyncWriteWithoutTransaction { db in + writer.asyncWriteWithoutTransaction { db in try { try Player(...).insert(db) } catch { From f03fd276f175eb27dbc20d27d349c915395bf1e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 14 Jun 2019 08:03:13 +0200 Subject: [PATCH 8/9] asyncWrite's completion handler accepts a database connection This guarantees that the asyncWrite method provides exclusive write access for the whole duration of (transaction + result handling). --- GRDB/Core/DatabaseWriter.swift | 21 ++++++++++++--------- README.md | 16 ++++++++-------- Tests/GRDBTests/DatabaseWriterTests.swift | 6 ++++-- 3 files changed, 24 insertions(+), 19 deletions(-) diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 156ecdcdc..89b75465b 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -63,8 +63,9 @@ public protocol DatabaseWriter : DatabaseReader { /// If the updates throw an error, the transaction is rollbacked. /// /// The *completion* closure is always called with the result of the - /// database updates. Its argument is a failure if the transaction could not - /// be committed. + /// database updates. Its arguments are a database connection and the + /// result of the transaction. This result is a failure if the transaction + /// could not be committed. /// /// Eventual concurrent database updates are postponed until the transaction /// and the *completion* closure have completed. @@ -78,7 +79,7 @@ public protocol DatabaseWriter : DatabaseReader { /// - parameter completion: A closure that is called with the eventual /// transaction error. /// - throws: The error thrown by the updates, or by the wrapping transaction. - func asyncWrite(_ updates: @escaping (Database) throws -> T, completion: @escaping (Result) -> Void) + func asyncWrite(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result) -> Void) #endif /// Asynchronously executes database updates in a protected dispatch queue, @@ -175,8 +176,10 @@ extension DatabaseWriter { /// If the updates throw an error, the transaction is rollbacked. /// /// The *completion* closure is always called with the result of the - /// database updates. Its argument is a failure if the transaction could not - /// be committed. + /// database updates. Its arguments are a database connection and the + /// result of the transaction. This result is a failure if the transaction + /// could not be committed. The completion closure is executed in a + /// protected dispatch queue, outside of any transaction. /// /// Eventual concurrent database updates are postponed until the transaction /// and the *completion* closure have completed. @@ -190,7 +193,7 @@ extension DatabaseWriter { /// - parameter completion: A closure that is called with the eventual /// transaction error. /// - throws: The error thrown by the updates, or by the wrapping transaction. - public func asyncWrite(_ updates: @escaping (Database) throws -> T, completion: @escaping (Result) -> Void) { + public func asyncWrite(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result) -> Void) { asyncWriteWithoutTransaction { db in do { var result: T? @@ -198,9 +201,9 @@ extension DatabaseWriter { result = try updates(db) return .commit } - completion(.success(result!)) + completion(db, .success(result!)) } catch { - completion(.failure(error)) + completion(db, .failure(error)) } } } @@ -562,7 +565,7 @@ public final class AnyDatabaseWriter : DatabaseWriter { #if compiler(>=5.0) /// :nodoc: - public func asyncWrite(_ updates: @escaping (Database) throws -> T, completion: @escaping (Result) -> Void) { + public func asyncWrite(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result) -> Void) { base.asyncWrite(updates, completion: completion) } #endif diff --git a/README.md b/README.md index ce788270c..7e6bf29b4 100644 --- a/README.md +++ b/README.md @@ -8304,7 +8304,7 @@ let component = MyReadOnlyComponent(reader: dbQueue) The `asyncRead` method can be used from any thread. It submits your database statements for asynchronous execution on a protected dispatch queue: ```swift - reader.asyncRead { result: Result in + reader.asyncRead { (result: Result) in try { let db = try result.get() let players = try Player.fetchAll(db) @@ -8329,9 +8329,9 @@ let component = MyReadOnlyComponent(reader: dbQueue) The `asyncWrite` method can be used from any thread. It submits your database statements for asynchronous execution on a protected dispatch queue, wrapped inside a [database transaction](#transactions-and-savepoints): ```swift - writer.asyncWrite({ db: Database in + writer.asyncWrite({ (db: Database) in try Player(...).insert(db) - }, completion: { result: Result in + }, completion: { (db: Database, result: Result) in switch result { case let .success: // handle transaction success @@ -8341,20 +8341,20 @@ let component = MyReadOnlyComponent(reader: dbQueue) }) ``` - `asyncWrite` accepts two function arguments. The first one executes your database updates. The second one is a completion function which accepts the result of the asynchronous transaction. + `asyncWrite` accepts two function arguments. The first one executes your database updates. The second one is a completion function which accepts a database connection and the result of the asynchronous transaction. On the first unhandled error during database updates, all changes are reverted, the whole transaction is rollbacked, and the error is passed to the completion function. When the transaction completes successfully, the result of the first function is contained in the standard `Result` passed to the completion function: ```swift - writer.asyncWrite({ db: Database in + writer.asyncWrite({ (db: Database) in try Player(...).insert(db) return try Player.fetchCount(db) - }, completion: { result: Result in + }, completion: { (db: Database, result: Result) in switch result { case let .success(newPlayerCount): - // handle value and transaction success + print("new player count: \(newPlayerCount)") case let .failure(error): // handle transaction error } @@ -8370,7 +8370,7 @@ let component = MyReadOnlyComponent(reader: dbQueue) The `asyncWriteWithoutTransaction` method can be used from any thread. It submits your database statements for asynchronous execution on a protected dispatch queue, outside of any transaction: ```swift - writer.asyncWriteWithoutTransaction { db in + writer.asyncWriteWithoutTransaction { (db: Database) in try { try Player(...).insert(db) } catch { diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index b11b8c2cf..0f13d9482 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -102,7 +102,8 @@ class DatabaseWriterTests : GRDBTestCase { // Make sure this block executes asynchronously semaphore.wait() try db.execute(sql: "CREATE TABLE testAsyncWrite (a)") - }, completion: { result in + }, completion: { db, result in + XCTAssertFalse(db.isInsideTransaction) switch result { case .success: break @@ -132,7 +133,8 @@ class DatabaseWriterTests : GRDBTestCase { // Make sure this block executes asynchronously semaphore.wait() try db.execute(sql: "This is not SQL") - }, completion: { result in + }, completion: { db, result in + XCTAssertFalse(db.isInsideTransaction) switch result { case .success: XCTFail("Expected error") From 4a79a20116ae1c36c8c8cec28659fa1d39a03ac6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 14 Jun 2019 08:10:16 +0200 Subject: [PATCH 9/9] Foster asyncWrite over asyncWriteWithoutTransaction --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7e6bf29b4..0991929c6 100644 --- a/README.md +++ b/README.md @@ -8379,7 +8379,7 @@ let component = MyReadOnlyComponent(reader: dbQueue) } ``` - **Writing outside of any transaction is dangerous.** Please see [Transactions and Savepoints](#transactions-and-savepoints) for more information. + **Writing outside of any transaction is dangerous.** You should almost always prefer the `asyncWrite` method described above. Please see [Transactions and Savepoints](#transactions-and-savepoints) for more information. The scheduled asynchronous updates have to wait for any eventual concurrent database write to complete before they can start.