diff --git a/CHANGELOG.md b/CHANGELOG.md index 4cccd57f5..cf50412ea 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 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..65eb39910 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 { @@ -447,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 681ec901e..3ce475757 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -169,6 +169,30 @@ 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 { db in + db.readOnly { block(.success(db)) } + } + } + #endif + /// Synchronously executes a block in a protected dispatch queue, and /// returns its result. /// @@ -204,7 +228,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. @@ -218,80 +242,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 @@ -302,12 +301,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 @@ -316,12 +315,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/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..89b75465b 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -21,54 +21,86 @@ 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. + #if compiler(>=5.0) + /// 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 with the result of the + /// 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. + /// + /// 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 -> T, completion: @escaping (Database, Result) -> Void) + #endif + + /// 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 +140,74 @@ 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? + try db.inTransaction { + result = try updates(db) + return .commit + } + return result! + } + } + + #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 with the result of the + /// 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. + /// + /// 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 -> T, completion: @escaping (Database, Result) -> Void) { + asyncWriteWithoutTransaction { db in + do { + var result: T? + try db.inTransaction { + result = try updates(db) + return .commit + } + completion(db, .success(result!)) + } catch { + completion(db, .failure(error)) + } + } + } + #endif // MARK: - Transaction Observers @@ -388,7 +488,7 @@ public class DatabaseFuture { _wait = wait } - init(_ result: Result) { + init(_ result: DatabaseResult) { _wait = result.get } @@ -429,6 +529,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) @@ -447,23 +554,30 @@ 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) } + #if compiler(>=5.0) /// :nodoc: - public func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T { - return try base.unsafeReentrantWrite(block) + public func asyncWrite(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result) -> Void) { + base.asyncWrite(updates, completion: completion) } + #endif /// :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 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 */, diff --git a/README.md b/README.md index d3d165f1e..e623ad864 100644 --- a/README.md +++ b/README.md @@ -8050,6 +8050,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) @@ -8375,9 +8376,98 @@ 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). + + > :point_up: **Note**: because it uses the standard `Result` type, `asyncRead` is only available with a Swift 5+ compiler, starting Xcode 10.2. + +- **`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: { (db: Database, 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 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 + try Player(...).insert(db) + return try Player.fetchCount(db) + }, completion: { (db: Database, result: Result) in + switch result { + case let .success(newPlayerCount): + print("new player count: \(newPlayerCount)") + 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. + + > :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 + writer.asyncWriteWithoutTransaction { (db: Database) in + try { + try Player(...).insert(db) + } catch { + // handle error + } + } + ``` + + **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. + + ### 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`** diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index 7aac58fa6..c8fdd1850 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -72,4 +72,60 @@ class DatabaseReaderTests : GRDBTestCase { let reader: DatabaseReader = DatabaseQueue() let _: DatabaseReader = AnyDatabaseReader(reader) } + + #if compiler(>=5.0) + 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()) + } + #endif + + #if compiler(>=5.0) + 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()) + } + #endif } diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index 6357e6e08..0f13d9482 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -43,6 +43,119 @@ 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()) + } + + #if compiler(>=5.0) + 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: { db, result in + XCTAssertFalse(db.isInsideTransaction) + switch result { + case .success: + break + case let .failure(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()) + } + #endif + + #if compiler(>=5.0) + 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: { db, result in + XCTAssertFalse(db.isInsideTransaction) + 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)") + } + } + expectation.fulfill() + }) + semaphore.signal() + waitForExpectations(timeout: 1, handler: nil) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + #endif + func testAnyDatabaseWriter() { // This test passes if this code compiles. let writer: DatabaseWriter = DatabaseQueue()