DatabaseReader and DatabaseWriter cleanup

This commit is contained in:
Gwendal Roué committed 2016-03-12 12:00:06 +01:00
1 parent 387e7bc2f5
commit e3ef424a41
10 files changed
+370 -342

No files matched your search

+3
View File
@@ -21,6 +21,9 @@ Release Notes
try person.insert(dbQueue)
```
- DatabaseQueue and DatabasePool both adopt the new [DatabaseReader](https://github.com/groue/GRDB.swift/tree/master/GRDB/Core/DatabaseReader.swift) and [DatabaseWriter](https://github.com/groue/GRDB.swift/tree/master/GRDB/Core/DatabaseWriter.swift) protocols.
**Breaking Changes**
- The following methods have changed their signatures:
@@ -53,6 +53,8 @@
562FF9EC1BCE903D00759400 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 562FF9EB1BCE903D00759400 /* libsqlite3.tbd */; };
562FF9EF1BCE912C00759400 /* PersonEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562FF9EE1BCE912C00759400 /* PersonEditionViewController.swift */; };
562FF9F21BCE914E00759400 /* Person.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562FF9F11BCE914E00759400 /* Person.swift */; };
563363C81C942CAE000BE133 /* DatabaseReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363C71C942CAE000BE133 /* DatabaseReader.swift */; };
563363CA1C942CB4000BE133 /* DatabaseWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363C91C942CB4000BE133 /* DatabaseWriter.swift */; };
566A20F31C58A4B300C5A218 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A20F21C58A4B300C5A218 /* AppDatabase.swift */; };
/* End PBXBuildFile section */
@@ -106,6 +108,8 @@
562FF9EE1BCE912C00759400 /* PersonEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonEditionViewController.swift; sourceTree = "<group>"; };
562FF9F11BCE914E00759400 /* Person.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Person.swift; sourceTree = "<group>"; };
562FF9F41BCE930C00759400 /* GRDBDemoiOS7-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBDemoiOS7-Bridging-Header.h"; sourceTree = "<group>"; };
563363C71C942CAE000BE133 /* DatabaseReader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReader.swift; sourceTree = "<group>"; };
563363C91C942CB4000BE133 /* DatabaseWriter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriter.swift; sourceTree = "<group>"; };
566A20F21C58A4B300C5A218 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
@@ -129,9 +133,11 @@
560A37B51C91391800949E71 /* DatabaseError.swift */,
560A37B61C91391800949E71 /* DatabasePool.swift */,
560A37B71C91391800949E71 /* DatabaseQueue.swift */,
563363C71C942CAE000BE133 /* DatabaseReader.swift */,
560A37B81C91391800949E71 /* DatabaseSchemaCache.swift */,
560A37B91C91391800949E71 /* DatabaseValue.swift */,
560A37BA1C91391800949E71 /* DatabaseValueConvertible.swift */,
563363C91C942CB4000BE133 /* DatabaseWriter.swift */,
560A37BB1C91391800949E71 /* Row.swift */,
560A37BC1C91391800949E71 /* SerializedDatabase.swift */,
560A37BD1C91391800949E71 /* Statement.swift */,
@@ -243,7 +249,7 @@
562FF9F01BCE913900759400 /* Controllers */,
562FF9F31BCE915B00759400 /* Models */,
562FF9A61BCE8FB000759400 /* Resources */,
562FF9ED1BCE904D00759400 /* Libraries */,
562FF9ED1BCE904D00759400 /* GRDB */,
562FF9A71BCE8FB600759400 /* Supporting Files */,
);
path = GRDBDemoiOS7;
@@ -268,13 +274,13 @@
name = "Supporting Files";
sourceTree = "<group>";
};
562FF9ED1BCE904D00759400 /* Libraries */ = {
562FF9ED1BCE904D00759400 /* GRDB */ = {
isa = PBXGroup;
children = (
562FF9EB1BCE903D00759400 /* libsqlite3.tbd */,
566A20F41C58A54F00C5A218 /* GRDB */,
);
name = Libraries;
name = GRDB;
sourceTree = "<group>";
};
562FF9F01BCE913900759400 /* Controllers */ = {
@@ -405,6 +411,7 @@
560A37E21C91391800949E71 /* DatabaseError.swift in Sources */,
560A38041C91391800949E71 /* RowConvertible.swift in Sources */,
560A37F91C91391800949E71 /* StandardLibrary.swift in Sources */,
563363CA1C942CB4000BE133 /* DatabaseWriter.swift in Sources */,
560A37FA1C91391800949E71 /* Utils.swift in Sources */,
560A37F61C91391800949E71 /* Row+Foundation.swift in Sources */,
560A37FD1C91391800949E71 /* SQLFunction.swift in Sources */,
@@ -419,6 +426,7 @@
566A20F31C58A4B300C5A218 /* AppDatabase.swift in Sources */,
560A37EA1C91391800949E71 /* Statement.swift in Sources */,
560A38031C91391800949E71 /* Record.swift in Sources */,
563363C81C942CAE000BE133 /* DatabaseReader.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
+16
View File
@@ -105,6 +105,12 @@
563363BA1C933FF8000BE133 /* DatabaseQueuePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AE1C933FF8000BE133 /* DatabaseQueuePersistableTests.swift */; };
563363BD1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */; };
563363BE1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */; };
563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BF1C942C04000BE133 /* DatabaseReader.swift */; };
563363C11C942C04000BE133 /* DatabaseReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BF1C942C04000BE133 /* DatabaseReader.swift */; };
563363C21C942C04000BE133 /* DatabaseReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BF1C942C04000BE133 /* DatabaseReader.swift */; };
563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363C31C942C37000BE133 /* DatabaseWriter.swift */; };
563363C51C942C37000BE133 /* DatabaseWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363C31C942C37000BE133 /* DatabaseWriter.swift */; };
563363C61C942C37000BE133 /* DatabaseWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363C31C942C37000BE133 /* DatabaseWriter.swift */; };
563445051C4A7FD7003D3DC6 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563445041C4A7FD7003D3DC6 /* Utils.swift */; };
563445061C4A7FD7003D3DC6 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563445041C4A7FD7003D3DC6 /* Utils.swift */; };
564A50C71BFF4B7F00B3A3A2 /* CollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */; };
@@ -381,6 +387,8 @@
563363AD1C933FF8000BE133 /* DatabaseQueueMutablePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueMutablePersistableTests.swift; sourceTree = "<group>"; };
563363AE1C933FF8000BE133 /* DatabaseQueuePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueuePersistableTests.swift; sourceTree = "<group>"; };
563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueConcurrencyTests.swift; sourceTree = "<group>"; };
563363BF1C942C04000BE133 /* DatabaseReader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReader.swift; sourceTree = "<group>"; };
563363C31C942C37000BE133 /* DatabaseWriter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriter.swift; sourceTree = "<group>"; };
563445041C4A7FD7003D3DC6 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = "<group>"; };
564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CollationTests.swift; sourceTree = "<group>"; };
56553C181C3E906C00522B5C /* GRDBOSXCrashTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXCrashTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -853,9 +861,11 @@
56A238731B9C75030082EB20 /* DatabaseError.swift */,
560A37A31C8F625000949E71 /* DatabasePool.swift */,
56A238741B9C75030082EB20 /* DatabaseQueue.swift */,
563363BF1C942C04000BE133 /* DatabaseReader.swift */,
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
56A238761B9C75030082EB20 /* Row.swift */,
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
56A238781B9C75030082EB20 /* Statement.swift */,
@@ -1392,6 +1402,7 @@
5605F1901C6B1A8700235C62 /* SQLFunction.swift in Sources */,
5605F1721C672E4000235C62 /* RawRepresentable.swift in Sources */,
563445061C4A7FD7003D3DC6 /* Utils.swift in Sources */,
563363C51C942C37000BE133 /* DatabaseWriter.swift in Sources */,
560A37A81C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
56A238941B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
5605F16A1C672E4000235C62 /* NSString.swift in Sources */,
@@ -1411,6 +1422,7 @@
56A238881B9C75030082EB20 /* Row.swift in Sources */,
569531201C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */,
5605F15E1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */,
563363C11C942C04000BE133 /* DatabaseReader.swift in Sources */,
5605F1661C672E4000235C62 /* NSNull.swift in Sources */,
56A238841B9C75030082EB20 /* DatabaseQueue.swift in Sources */,
56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */,
@@ -1447,6 +1459,7 @@
56A2385A1B9C74A90082EB20 /* PrimaryKeySingleTests.swift in Sources */,
56A238661B9C74A90082EB20 /* RecordFetchTests.swift in Sources */,
56EE573E1BB317B7007A6A95 /* SQLiteStatementConversionTests.swift in Sources */,
563363C21C942C04000BE133 /* DatabaseReader.swift in Sources */,
569531381C919DF700CF1A2B /* DatabasePoolFunctionTests.swift in Sources */,
563363B81C933FF8000BE133 /* DatabaseQueueMutablePersistableTests.swift in Sources */,
56A238481B9C74A90082EB20 /* DetachedRowTests.swift in Sources */,
@@ -1456,6 +1469,7 @@
563363B41C933FF8000BE133 /* DatabasePoolMutablePersistableTests.swift in Sources */,
56DE7B121C3D93ED00861EB8 /* StatementArgumentsTests.swift in Sources */,
56A238681B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */,
563363C61C942C37000BE133 /* DatabaseWriter.swift in Sources */,
563363B01C933FF8000BE133 /* DatabaseMutablePersistableTests.swift in Sources */,
56300B621C53C42C005A543B /* RowConvertible+FetchRequestTests.swift in Sources */,
56EA869F1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */,
@@ -1587,6 +1601,7 @@
5605F18F1C6B1A8700235C62 /* SQLFunction.swift in Sources */,
5605F1711C672E4000235C62 /* RawRepresentable.swift in Sources */,
56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */,
563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */,
560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
5605F1691C672E4000235C62 /* NSString.swift in Sources */,
5605F16D1C672E4000235C62 /* Row+Foundation.swift in Sources */,
@@ -1606,6 +1621,7 @@
56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */,
5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */,
563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */,
5605F1651C672E4000235C62 /* NSNull.swift in Sources */,
56A2387D1B9C75030082EB20 /* Database.swift in Sources */,
56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */,
+27 -93
View File
@@ -394,7 +394,7 @@ extension Database {
/// }
/// db.addFunction(fn)
/// Int.fetchOne(db, "SELECT succ(1)")! // 2
func addFunction(function: DatabaseFunction) {
public func addFunction(function: DatabaseFunction) {
functions.remove(function)
functions.insert(function)
let functionPointer = unsafeBitCast(function, UnsafeMutablePointer<Void>.self)
@@ -436,7 +436,7 @@ extension Database {
}
/// Remove an SQL function.
func removeFunction(function: DatabaseFunction) {
public func removeFunction(function: DatabaseFunction) {
functions.remove(function)
let code = sqlite3_create_function_v2(
sqliteConnection,
@@ -519,8 +519,8 @@ extension Database {
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// db.addCollation(collation)
/// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD")
func addCollation(collation: DatabaseCollation) {
/// try db.execute("CREATE TABLE files (name TEXT COLLATE localized_standard")
public func addCollation(collation: DatabaseCollation) {
collations.remove(collation)
collations.insert(collation)
let collationPointer = unsafeBitCast(collation, UnsafeMutablePointer<Void>.self)
@@ -539,7 +539,7 @@ extension Database {
}
/// Remove a collation.
func removeCollation(collation: DatabaseCollation) {
public func removeCollation(collation: DatabaseCollation) {
collations.remove(collation)
sqlite3_create_collation_v2(
sqliteConnection,
@@ -560,7 +560,7 @@ public final class DatabaseCollation {
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// db.addCollation(collation)
/// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD")
/// try db.execute("CREATE TABLE files (name TEXT COLLATE localized_standard")
///
/// - parameters:
/// - name: The function name.
@@ -927,9 +927,9 @@ extension Database {
/// Add a transaction observer, so that it gets notified of all
/// database changes.
///
/// Database holds weak references to its transaction observers: they are
/// not retained, and stop getting notifications after they are deallocated.
func addTransactionObserver(transactionObserver: TransactionObserverType) {
/// The transaction observer is weakly referenced: it is not retained, and
/// stops getting notifications after it is deallocated.
public func addTransactionObserver(transactionObserver: TransactionObserverType) {
preconditionValidQueue()
transactionObservers.append(WeakTransactionObserver(transactionObserver))
if transactionObservers.count == 1 {
@@ -938,7 +938,7 @@ extension Database {
}
/// Remove a transaction observer.
func removeTransactionObserver(transactionObserver: TransactionObserverType) {
public func removeTransactionObserver(transactionObserver: TransactionObserverType) {
preconditionValidQueue()
transactionObservers.removeFirst { $0.observer === transactionObserver }
if transactionObservers.isEmpty {
@@ -1155,48 +1155,20 @@ public struct DatabaseEvent {
// =========================================================================
// MARK: - DatabaseReader
/// The protocol for all types that can fetch values from a database.
///
/// It is adopted by DatabaseQueue, DatabasePool, and Database.
///
/// You typically provide a DatabaseReader to fetching methods:
///
/// let persons = Person.fetchAll(dbQueue)
/// let persons = Person.fetchAll(dbPool)
/// dbQueue.inDatabase { db in
/// let persons = Person.fetchAll(db)
/// }
public protocol DatabaseReader {
/// Executes a block that takes a database connection, and returns
/// its result.
///
/// All statements executed in the block argument can be fully executed
/// in isolation of eventual concurrent updates:
///
/// reader.nonIsolatedRead { db in
/// // no external update can mess with this iteration:
/// for row in Row.fetch(db, ...) { }
/// }
///
/// However, there is no guarantee that consecutive statements have the
/// same results:
///
/// reader.nonIsolatedRead { db in
/// // Those two ints may be different
/// let sql = "SELECT ..."
/// let int1 = Int.fetchOne(db, sql)
/// let int2 = Int.fetchOne(db, sql)
/// }
///
/// Adopting types can provide stronger guarantees.
func nonIsolatedRead<T>(block: (db: Database) throws -> T) rethrows -> T
}
extension Database : DatabaseReader {
/// This method is part of the DatabaseReader protocol adoption.
// MARK: - Read From Database
/// Evalutes the *block* argument and returns its result.
///
/// It evaluates the *block* argument and returns its result.
/// This method is part of the DatabaseReader protocol adoption.
public func read<T>(block: (db: Database) throws -> T) rethrows -> T {
return try block(db: self)
}
/// Evalutes the *block* argument and returns its result.
///
/// This method is part of the DatabaseReader protocol adoption.
public func nonIsolatedRead<T>(block: (db: Database) throws -> T) rethrows -> T {
return try block(db: self)
}
@@ -1206,51 +1178,13 @@ extension Database : DatabaseReader {
// =========================================================================
// MARK: - DatabaseWriter
/// The protocol for all types that can update a database.
///
/// It is adopted by DatabaseQueue, DatabasePool, and Database.
///
/// let person = Person(...)
/// try person.insert(dbQueue)
/// try person.insert(dbPool)
/// try dbQueue.inDatabase { db in
/// try person.insert(db)
/// }
public protocol DatabaseWriter {
/// Executes one or several SQL statements, separated by semi-colons.
///
/// try db.execute(
/// "INSERT INTO persons (name) VALUES (:name)",
/// arguments: ["name": "Arthur"])
///
/// try db.execute(
/// "INSERT INTO persons (name) VALUES (?);" +
/// "INSERT INTO persons (name) VALUES (?);" +
/// "INSERT INTO persons (name) VALUES (?);",
/// arguments; ['Arthur', 'Barbara', 'Craig'])
///
/// This method may throw a DatabaseError.
///
/// - parameters:
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - returns: A DatabaseChanges.
/// - throws: A DatabaseError whenever an SQLite error occurs.
func execute(sql: String, arguments: StatementArguments?) throws -> DatabaseChanges
/// Executes a block that takes a database connection, and returns
/// its result.
///
/// The block argument can be fully executed in isolation of eventual
/// concurrent updates.
func write<T>(block: (db: Database) throws -> T) rethrows -> T
}
extension Database : DatabaseWriter {
/// This method is part of the DatabaseWriter protocol adoption.
// MARK: - Writing in Database
/// Evalutes the *block* argument and returns its result.
///
/// It evaluates the *block* argument and returns its result.
/// This method is part of the DatabaseWriter protocol adoption.
public func write<T>(block: (db: Database) throws -> T) rethrows -> T {
return try block(db: self)
}
+113 -172
View File
@@ -40,94 +40,6 @@ public final class DatabasePool {
}
// MARK: - Database access
/// Synchronously executes a read-only block in a protected dispatch queue,
/// and returns its result.
///
/// let persons = dbPool.read { db in
/// Person.fetchAll(...)
/// }
///
/// This method is *not* reentrant.
///
/// The block is completely isolated. Eventual database updates are *not
/// visible* inside the block:
///
/// dbPool.read { db in
/// // Those two values are guaranteed to be equal, even if the `wines`
/// // tables is modified between the two requests:
/// let count1 = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count2 = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// }
///
/// dbPool.read { db in
/// // Now this value may be different:
/// let count = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// }
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func read<T>(block: (db: Database) throws -> T) rethrows -> T {
// The block isolation comes from the DEFERRED transaction.
// See DatabasePoolTests.testReadMethodIsolationOfBlock().
return try readerPool.get { reader in
try reader.inDatabase { db in
var result: T? = nil
try db.inTransaction(.Deferred) {
result = try block(db: db)
return .Commit
}
return result!
}
}
}
/// Synchronously executes an update block in a protected dispatch queue,
/// and returns its result.
///
/// dbPool.write { db in
/// db.execute(...)
/// }
///
/// This method is *not* reentrant.
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func write<T>(block: (db: Database) throws -> T) rethrows -> T {
return try writer.inDatabase(block)
}
/// 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.
///
/// try dbPool.writeInTransaction { db in
/// db.execute(...)
/// return .Commit
/// }
///
/// This method is *not* reentrant.
///
/// - parameters:
/// - kind: The transaction type (default nil). If nil, the transaction
/// type is configuration.defaultTransactionKind, which itself
/// defaults to .Immediate. 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 writeInTransaction(kind: TransactionKind? = nil, _ block: (db: Database) throws -> TransactionCompletion) rethrows {
try writer.inDatabase { db in
try db.inTransaction(kind) {
try block(db: db)
}
}
}
// MARK: - WAL Management
/// Runs a WAL checkpoint
@@ -217,9 +129,83 @@ public enum CheckpointMode: Int32 {
// =========================================================================
// MARK: - Functions
// MARK: - DatabaseReader
extension DatabasePool {
extension DatabasePool : DatabaseReader {
// MARK: - Read From Database
/// Synchronously executes a read-only block in a protected dispatch queue,
/// and returns its result.
///
/// let persons = dbPool.read { db in
/// Person.fetchAll(...)
/// }
///
/// The block is completely isolated. Eventual concurrent database updates
/// are *not visible* inside the block:
///
/// dbPool.read { db in
/// // Those two values are guaranteed to be equal, even if the
/// // `wines` table is modified between the two requests:
/// let count1 = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count2 = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// }
///
/// dbPool.read { db in
/// // Now this value may be different:
/// let count = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// }
///
/// This method is *not* reentrant.
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func read<T>(block: (db: Database) throws -> T) rethrows -> T {
// The block isolation comes from the DEFERRED transaction.
// See DatabasePoolTests.testReadMethodIsolationOfBlock().
return try readerPool.get { reader in
try reader.inDatabase { db in
var result: T? = nil
try db.inTransaction(.Deferred) {
result = try block(db: db)
return .Commit
}
return result!
}
}
}
/// Synchronously executes a read-only block in a protected dispatch queue,
/// and returns its result.
///
/// let persons = dbPool.nonIsolatedRead { db in
/// Person.fetchAll(...)
/// }
///
/// The block is not isolated from eventual concurrent database updates:
///
/// dbPool.nonIsolatedRead { 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 = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count2 = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// }
///
/// This method is *not* reentrant.
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func nonIsolatedRead<T>(block: (db: Database) throws -> T) rethrows -> T {
return try readerPool.get { reader in
try reader.inDatabase { db in
try block(db: db)
}
}
}
// MARK: - Functions
/// Add or redefine an SQL function.
///
@@ -263,13 +249,9 @@ extension DatabasePool {
}
}
}
}
// =========================================================================
// MARK: - Collations
extension DatabasePool {
// MARK: - Collations
/// Add or redefine a collation.
///
@@ -313,94 +295,53 @@ extension DatabasePool {
// =========================================================================
// MARK: - Transaction Observers
// MARK: - DatabaseWriter
extension DatabasePool {
extension DatabasePool : DatabaseWriter {
/// Add a transaction observer, so that it gets notified of all
/// database changes.
///
/// Database holds weak references to its transaction observers: they are
/// not retained, and stop getting notifications after they are deallocated.
public func addTransactionObserver(transactionObserver: TransactionObserverType) {
writer.inDatabase { db in
db.addTransactionObserver(transactionObserver)
}
}
// MARK: - Writing in Database
/// Remove a transaction observer.
public func removeTransactionObserver(transactionObserver: TransactionObserverType) {
writer.inDatabase { db in
db.removeTransactionObserver(transactionObserver)
}
}
}
// =========================================================================
// MARK: - DatabaseReader
extension DatabasePool : DatabaseReader {
/// Synchronously executes a read-only block in a protected dispatch queue,
/// Synchronously executes an update block in a protected dispatch queue,
/// and returns its result.
///
/// let persons = dbPool.nonIsolatedRead { db in
/// Person.fetchAll(...)
/// dbPool.write { db in
/// db.execute(...)
/// }
///
/// This method is *not* reentrant.
///
/// The block is not isolated from eventual concurrent database updates:
///
/// dbPool.nonIsolatedRead { 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 = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count2 = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// }
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func nonIsolatedRead<T>(block: (db: Database) throws -> T) rethrows -> T {
return try readerPool.get { reader in
try reader.inDatabase { db in
public func write<T>(block: (db: Database) throws -> T) rethrows -> T {
return try writer.inDatabase(block)
}
/// 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.
///
/// try dbPool.writeInTransaction { db in
/// db.execute(...)
/// return .Commit
/// }
///
/// This method is *not* reentrant.
///
/// - parameters:
/// - kind: The transaction type (default nil). If nil, the transaction
/// type is configuration.defaultTransactionKind, which itself
/// defaults to .Immediate. 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 writeInTransaction(kind: TransactionKind? = nil, _ block: (db: Database) throws -> TransactionCompletion) rethrows {
try writer.inDatabase { db in
try db.inTransaction(kind) {
try block(db: db)
}
}
}
}
// =========================================================================
// MARK: - DatabaseWriter
extension DatabasePool : DatabaseWriter {
/// Executes one or several SQL statements, separated by semi-colons.
///
/// try dbPool.execute(
/// "INSERT INTO persons (name) VALUES (:name)",
/// arguments: ["name": "Arthur"])
///
/// try dbPool.execute(
/// "INSERT INTO persons (name) VALUES (?);" +
/// "INSERT INTO persons (name) VALUES (?);" +
/// "INSERT INTO persons (name) VALUES (?);",
/// arguments; ['Arthur', 'Barbara', 'Craig'])
///
/// This method may throw a DatabaseError.
///
/// - parameters:
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - returns: A DatabaseChanges.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func execute(sql: String, arguments: StatementArguments? = nil) throws -> DatabaseChanges {
return try writer.inDatabase { db in
try db.execute(sql, arguments: arguments)
}
}
}
+30 -73
View File
@@ -132,9 +132,29 @@ public final class DatabaseQueue {
// =========================================================================
// MARK: - Functions
// MARK: - DatabaseReader
extension DatabaseQueue {
extension DatabaseQueue : DatabaseReader {
// MARK: - Read From Database
/// Alias for inDatabase
///
/// This method is part of the DatabaseReader protocol adoption.
public func read<T>(block: (db: Database) throws -> T) rethrows -> T {
return try inDatabase(block)
}
/// Alias for inDatabase
///
/// This method is part of the DatabaseReader protocol adoption.
public func nonIsolatedRead<T>(block: (db: Database) throws -> T) rethrows -> T {
return try inDatabase(block)
}
// MARK: - Functions
/// Add or redefine an SQL function.
///
@@ -150,50 +170,20 @@ extension DatabaseQueue {
/// Int.fetchOne(db, "SELECT succ(1)") // 2
/// }
public func addFunction(function: DatabaseFunction) {
serializedDatabase.inDatabase { db in
inDatabase { db in
db.addFunction(function)
}
}
/// Remove an SQL function.
public func removeFunction(function: DatabaseFunction) {
serializedDatabase.inDatabase { db in
inDatabase { db in
db.removeFunction(function)
}
}
}
// =========================================================================
// MARK: - Transaction Observers
extension DatabaseQueue {
/// Add a transaction observer, so that it gets notified of all
/// database changes.
///
/// Database holds weak references to its transaction observers: they are
/// not retained, and stop getting notifications after they are deallocated.
public func addTransactionObserver(transactionObserver: TransactionObserverType) {
serializedDatabase.inDatabase { db in
db.addTransactionObserver(transactionObserver)
}
}
/// Remove a transaction observer.
public func removeTransactionObserver(transactionObserver: TransactionObserverType) {
serializedDatabase.inDatabase { db in
db.removeTransactionObserver(transactionObserver)
}
}
}
// =========================================================================
// MARK: - Collations
extension DatabaseQueue {
// MARK: - Collations
/// Add or redefine a collation.
///
@@ -205,63 +195,30 @@ extension DatabaseQueue {
/// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD")
/// }
public func addCollation(collation: DatabaseCollation) {
serializedDatabase.inDatabase { db in
inDatabase { db in
db.addCollation(collation)
}
}
/// Remove a collation.
public func removeCollation(collation: DatabaseCollation) {
serializedDatabase.inDatabase { db in
inDatabase { db in
db.removeCollation(collation)
}
}
}
// =========================================================================
// MARK: - DatabaseReader
extension DatabaseQueue : DatabaseReader {
/// Alias for inDatabase
public func nonIsolatedRead<T>(block: (db: Database) throws -> T) rethrows -> T {
return try inDatabase(block)
}
}
// =========================================================================
// MARK: - DatabaseWriter
extension DatabaseQueue : DatabaseWriter {
/// Executes one or several SQL statements, separated by semi-colons.
///
/// try dbQueue.execute(
/// "INSERT INTO persons (name) VALUES (:name)",
/// arguments: ["name": "Arthur"])
///
/// try dbQueue.execute(
/// "INSERT INTO persons (name) VALUES (?);" +
/// "INSERT INTO persons (name) VALUES (?);" +
/// "INSERT INTO persons (name) VALUES (?);",
/// arguments; ['Arthur', 'Barbara', 'Craig'])
///
/// This method may throw a DatabaseError.
///
/// - parameters:
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - returns: A DatabaseChanges.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func execute(sql: String, arguments: StatementArguments? = nil) throws -> DatabaseChanges {
return try serializedDatabase.inDatabase { db in
try db.execute(sql, arguments: arguments)
}
}
// MARK: - Writing in Database
/// Alias for inDatabase
///
/// This method is part of the DatabaseWriter protocol adoption.
public func write<T>(block: (db: Database) throws -> T) rethrows -> T {
return try inDatabase(block)
}
+95
View File
@@ -0,0 +1,95 @@
/// The protocol for all types that can fetch values from a database.
///
/// It is adopted by DatabaseQueue, DatabasePool, and Database.
///
/// You typically provide a DatabaseReader to fetching methods:
///
/// let persons = Person.fetchAll(dbQueue)
/// let persons = Person.fetchAll(dbPool)
/// dbQueue.inDatabase { db in
/// let persons = Person.fetchAll(db)
/// }
public protocol DatabaseReader {
// MARK: - Read From Database
/// Synchronously executes a read-only block that takes a database
/// connection, and returns its result.
///
/// The block is completely isolated. Eventual concurrent database updates
/// are *not visible* inside the block:
///
/// reader.read { db in
/// // Those two values are guaranteed to be equal, even if the
/// // `wines` table is modified between the two requests:
/// let count1 = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count2 = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// }
///
/// reader.read { db in
/// // Now this value may be different:
/// let count = Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// }
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
func read<T>(block: (db: Database) throws -> T) rethrows -> T
/// Synchronously executes a read-only block that takes a database
/// connection, and returns its result.
///
/// All statements executed in the block argument can be fully executed
/// in isolation of eventual concurrent updates:
///
/// reader.nonIsolatedRead { db in
/// // no external update can mess with this iteration:
/// for row in Row.fetch(db, ...) { }
/// }
///
/// However, there is no guarantee that consecutive statements have the
/// same results:
///
/// reader.nonIsolatedRead { db in
/// // Those two ints may be different
/// let sql = "SELECT ..."
/// let int1 = Int.fetchOne(db, sql)
/// let int2 = Int.fetchOne(db, sql)
/// }
///
/// Adopting types can provide stronger guarantees.
func nonIsolatedRead<T>(block: (db: Database) throws -> T) rethrows -> T
// MARK: - Functions
/// Add or redefine an SQL function.
///
/// let fn = DatabaseFunction("succ", argumentCount: 1) { databaseValues in
/// let dbv = databaseValues.first!
/// guard let int = dbv.value() as Int? else {
/// return nil
/// }
/// return int + 1
/// }
/// reader.addFunction(fn)
/// Int.fetchOne(reader, "SELECT succ(1)")! // 2
func addFunction(function: DatabaseFunction)
/// Remove an SQL function.
func removeFunction(function: DatabaseFunction)
// MARK: - Collations
/// Add or redefine a collation.
///
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// reader.addCollation(collation)
/// try reader.execute("SELECT * FROM files ORDER BY name COLLATE localized_standard")
func addCollation(collation: DatabaseCollation)
/// Remove a collation.
func removeCollation(collation: DatabaseCollation)
}
+72
View File
@@ -0,0 +1,72 @@
/// The protocol for all types that can update a database.
///
/// It is adopted by DatabaseQueue, DatabasePool, and Database.
///
/// let person = Person(...)
/// try person.insert(dbQueue)
/// try person.insert(dbPool)
/// try dbQueue.inDatabase { db in
/// try person.insert(db)
/// }
public protocol DatabaseWriter : DatabaseReader {
// MARK: - Writing in Database
/// Synchronously executes a block that takes a database connection, and
/// returns its result.
///
/// The block argument can be fully executed in isolation of eventual
/// concurrent updates.
func write<T>(block: (db: Database) throws -> T) rethrows -> T
}
extension DatabaseWriter {
// MARK: - Writing in Database
/// Executes one or several SQL statements, separated by semi-colons.
///
/// try writer.execute(
/// "INSERT INTO persons (name) VALUES (:name)",
/// arguments: ["name": "Arthur"])
///
/// try writer.execute(
/// "INSERT INTO persons (name) VALUES (?);" +
/// "INSERT INTO persons (name) VALUES (?);" +
/// "INSERT INTO persons (name) VALUES (?);",
/// arguments; ['Arthur', 'Barbara', 'Craig'])
///
/// This method may throw a DatabaseError.
///
/// - parameters:
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - returns: A DatabaseChanges.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func execute(sql: String, arguments: StatementArguments? = nil) throws -> DatabaseChanges {
return try write { db in
try db.execute(sql, arguments: arguments)
}
}
// MARK: - Transaction Observers
/// Add a transaction observer, so that it gets notified of all
/// database changes.
///
/// The transaction observer is weakly referenced: it is not retained, and
/// stops getting notifications after it is deallocated.
public func addTransactionObserver(transactionObserver: TransactionObserverType) {
write { db in
db.addTransactionObserver(transactionObserver)
}
}
/// Remove a transaction observer.
public func removeTransactionObserver(transactionObserver: TransactionObserverType) {
write { db in
db.removeTransactionObserver(transactionObserver)
}
}
}
@@ -44,7 +44,7 @@ public class UserDefaults {
private func createTableIfNeeded() {
guard needsTable else { return }
needsTable = false
try! db.execute("CREATE TABLE IF NOT EXISTS \(UserDefaultsItemTableName) (key TEXT NOT NULL PRIMARY KEY, value BLOB)", arguments: nil)
try! db.execute("CREATE TABLE IF NOT EXISTS \(UserDefaultsItemTableName) (key TEXT NOT NULL PRIMARY KEY, value BLOB)")
}
+2
View File
@@ -186,6 +186,8 @@ The differences are:
> :point_up: **Note**: your application should have a unique instance of DatabaseQueue or DatabasePool connected to a given database file. You may experience concurrency trouble if you do otherwise.
Finally, DatabaseQueue and DatabasePool adopt the [DatabaseReader](GRDB/Core/DatabaseReader.swift) and [DatabaseWriter](GRDB/Core/DatabaseWriter.swift) protocols, so that you write code that accepts both classes.
- [Database Queues](#database-queues)
- [Database Pools](#database-pools)