mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-24 04:07:47 +00:00
Merge pull request #550 from groue/dev/async
Asynchronous Database Access Methods
This commit is contained in:
14 files changed
+655
-211
No files matched your search
@@ -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
|
||||
|
||||
|
||||
@@ -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 = "<group>"; };
|
||||
5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadWriteBox.swift; sourceTree = "<group>"; };
|
||||
5659F4971EA8D989004A4992 /* Pool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Pool.swift; sourceTree = "<group>"; };
|
||||
5659F49F1EA8D997004A4992 /* Result.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Result.swift; sourceTree = "<group>"; };
|
||||
5659F49F1EA8D997004A4992 /* DatabaseResult.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseResult.swift; sourceTree = "<group>"; };
|
||||
565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecordTests.swift; sourceTree = "<group>"; };
|
||||
565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = "<group>"; };
|
||||
565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+FoundationTests.swift"; sourceTree = "<group>"; };
|
||||
@@ -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 */,
|
||||
|
||||
@@ -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<Database, Error>) -> 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<T>? = nil
|
||||
var futureResult: DatabaseResult<T>? = 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<T>(_ 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<T>(_ 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<T>(_ 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<T>(_ 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<T>(_ 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
|
||||
|
||||
@@ -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<Database, Error>) -> 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<T>(_ block: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
// 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<T>(_ 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<T>(_ 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<T>(_ 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<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync(block)
|
||||
public func inDatabase<T>(_ 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<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.reentrantSync(block)
|
||||
public func unsafeReentrantWrite<T>(_ 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
|
||||
|
||||
@@ -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<T>(_ 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<Database, Error>) -> 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<Database, Error>) -> Void) {
|
||||
base.asyncRead(block)
|
||||
}
|
||||
#endif
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeRead(block)
|
||||
|
||||
@@ -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<Database, Error>) -> Void) {
|
||||
serializedDatabase.async { block(.success($0)) }
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Alias for `read`. See `DatabaseReader.unsafeRead`.
|
||||
///
|
||||
/// :nodoc:
|
||||
|
||||
+155
-41
@@ -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<T>(_ 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<T>(_ 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<T>(_ block: (Database) throws -> T) rethrows -> T
|
||||
///
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates.
|
||||
func writeWithoutTransaction<T>(_ 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<T>(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result<T, Error>) -> 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<T>(_ 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<T>(_ 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<T>(_ 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<T>(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result<T, Error>) -> 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<Value> {
|
||||
_wait = wait
|
||||
}
|
||||
|
||||
init(_ result: Result<Value>) {
|
||||
init(_ result: DatabaseResult<Value>) {
|
||||
_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<Database, Error>) -> Void) {
|
||||
base.asyncRead(block)
|
||||
}
|
||||
#endif
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeRead<T>(_ 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<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.write(block)
|
||||
public func write<T>(_ updates: (Database) throws -> T) throws -> T {
|
||||
return try base.write(updates)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func writeWithoutTransaction<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try base.writeWithoutTransaction(block)
|
||||
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
return try base.writeWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
#if compiler(>=5.0)
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try base.unsafeReentrantWrite(block)
|
||||
public func asyncWrite<T>(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result<T, Error>) -> 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<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
return try base.unsafeReentrantWrite(updates)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
@@ -569,7 +569,7 @@ private func makeFetchFunction<Record, T>(
|
||||
controller: FetchedRecordsController<Record>,
|
||||
fetchAlongside: @escaping (Database) throws -> T,
|
||||
willProcessTransaction: @escaping () -> (),
|
||||
completion: @escaping (Result<(fetchedItems: [Item<Record>], fetchedAlongside: T, observer: FetchedRecordsObserver<Record>)>) -> ()
|
||||
completion: @escaping (DatabaseResult<(fetchedItems: [Item<Record>], fetchedAlongside: T, observer: FetchedRecordsObserver<Record>)>) -> ()
|
||||
) -> (FetchedRecordsObserver<Record>) -> ()
|
||||
{
|
||||
// Make sure we keep a weak reference to the fetched records controller,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#if compiler(>=5.0)
|
||||
typealias Result<Success> = Swift.Result<Success, Error>
|
||||
typealias DatabaseResult<Success> = Swift.Result<Success, Error>
|
||||
#else
|
||||
enum Result<Success> {
|
||||
enum DatabaseResult<Success> {
|
||||
case success(Success)
|
||||
case failure(Error)
|
||||
|
||||
@@ -13,7 +13,7 @@ enum Result<Success> {
|
||||
}
|
||||
}
|
||||
|
||||
func map<T>(_ transform: (Success) -> T) -> Result<T> {
|
||||
func map<T>(_ transform: (Success) -> T) -> DatabaseResult<T> {
|
||||
switch self {
|
||||
case .success(let success):
|
||||
return .success(transform(success))
|
||||
@@ -40,7 +40,7 @@ extension ValueReducer {
|
||||
func fetchFuture(_ db: Database, writer: DatabaseWriter, requiringWriteAccess: Bool) -> DatabaseFuture<Fetched> {
|
||||
if requiringWriteAccess {
|
||||
// Synchronous fetch
|
||||
return DatabaseFuture(Result {
|
||||
return DatabaseFuture(DatabaseResult {
|
||||
var fetchedValue: Fetched!
|
||||
try db.inTransaction {
|
||||
fetchedValue = try fetch(db)
|
||||
|
||||
@@ -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 = "<group>"; };
|
||||
5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadWriteBox.swift; sourceTree = "<group>"; };
|
||||
5659F4971EA8D989004A4992 /* Pool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Pool.swift; sourceTree = "<group>"; };
|
||||
5659F49F1EA8D997004A4992 /* Result.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Result.swift; sourceTree = "<group>"; };
|
||||
5659F49F1EA8D997004A4992 /* DatabaseResult.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseResult.swift; sourceTree = "<group>"; };
|
||||
565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecordTests.swift; sourceTree = "<group>"; };
|
||||
565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = "<group>"; };
|
||||
565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+FoundationTests.swift"; sourceTree = "<group>"; };
|
||||
@@ -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 */,
|
||||
|
||||
@@ -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<Database>) in
|
||||
try {
|
||||
let db = try result.get()
|
||||
let players = try Player.fetchAll(db)
|
||||
} catch {
|
||||
// handle error
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The argument function accepts a standard `Result<Database, Error>` 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<Void, Error>) 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<Int, Error>) 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`**
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
Reference in new issue
Block a user