WIP: the recent failing tests of DatabasePool.readFromCurrentState, a paramount brick of FetchedRecordsController, have led to a refactoring of the DatabaseWriter protocol, and DatabasePool.write { ... } always executing a transaction.

This commit is contained in:
Gwendal Roué committed 2016-12-01 14:12:20 +01:00
1 parent c0695e80a8
commit f781da41a4
10 files changed
+317 -34

No files matched your search

+1
View File
@@ -6,6 +6,7 @@ Release Notes
**Breaking Change**
- `DatabaseWriter.readFromWrite` has been renamed `DatabaseWriter.readFromCurrentState`
- `DatabaseReader.nonIsolatedRead` has been renamed `DatabaseReader.unsafeRead`
## 0.91.0
+10 -5
View File
@@ -119,6 +119,7 @@ public final class DatabasePool {
return store.path
}
// MARK: - WAL Management
/// Runs a WAL checkpoint
@@ -327,13 +328,13 @@ extension DatabasePool : DatabaseReader {
/// Synchronously executes a read-only block in a protected dispatch queue,
/// and returns its result.
///
/// let persons = try dbPool.nonIsolatedRead { db in
/// let persons = try dbPool.unsafeRead { db in
/// try Person.fetchAll(...)
/// }
///
/// The block is not isolated from eventual concurrent database updates:
///
/// try try dbPool.nonIsolatedRead { db in
/// try dbPool.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, "SELECT COUNT(*) FROM wines")!
@@ -345,7 +346,7 @@ extension DatabasePool : DatabaseReader {
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block, or any DatabaseError that would
/// happen while establishing the read access to the database.
public func nonIsolatedRead<T>(_ block: (Database) throws -> T) throws -> T {
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
return try readerPool.get { reader in
try reader.sync { db in
try block(db)
@@ -419,15 +420,19 @@ extension DatabasePool : DatabaseWriter {
/// Synchronously executes an update block in a protected dispatch queue,
/// and returns its result.
///
/// try dbPool.write { db in
/// try dbPool.unsafeWrite { db in
/// try db.execute(...)
/// }
///
/// This method is *not* reentrant.
///
/// - warning: As soon as you execute several update statements, readers may
/// see the database in an inconsistent state. To preserve readers
/// integrity, do not perform more than one database modification with
/// this method, or use write() or writeInTransaction().
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
public func unsafeWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
return try writer.sync(block)
}
+10 -3
View File
@@ -231,7 +231,7 @@ extension DatabaseQueue : DatabaseReader {
/// Alias for inDatabase
///
/// This method is part of the DatabaseReader protocol adoption.
public func nonIsolatedRead<T>(_ block: (Database) throws -> T) rethrows -> T {
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
return try serializedDatabase.sync(block)
}
@@ -301,8 +301,15 @@ extension DatabaseQueue : DatabaseWriter {
/// Alias for inDatabase
///
/// This method is part of the DatabaseWriter protocol adoption.
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
return try serializedDatabase.sync(block)
public func unsafeWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
return try inDatabase(block)
}
/// Alias for inTransaction
///
/// This method is part of the DatabaseWriter protocol adoption.
public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
try inTransaction(kind, block)
}
/// Synchronously executes *block*.
+4 -4
View File
@@ -64,7 +64,7 @@ public protocol DatabaseReader : class {
/// Individual statements executed in the *block* argument are executed
/// in isolation from eventual concurrent updates:
///
/// try reader.nonIsolatedRead { db in
/// try reader.unsafeRead { db in
/// // no external update can mess with this iteration:
/// let rows = try Row.fetchCursor(db, ...)
/// while let row = try rows.next() { ... }
@@ -73,7 +73,7 @@ public protocol DatabaseReader : class {
/// However, there is no guarantee that consecutive statements have the
/// same results:
///
/// try reader.nonIsolatedRead { db in
/// try reader.unsafeRead { db in
/// // Those two ints may be different:
/// let sql = "SELECT ..."
/// let int1 = try Int.fetchOne(db, sql)
@@ -83,7 +83,7 @@ public protocol DatabaseReader : class {
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block, or any DatabaseError that would
/// happen while establishing the read access to the database.
func nonIsolatedRead<T>(_ block: (Database) throws -> T) throws -> T
func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T
// MARK: - Functions
@@ -140,7 +140,7 @@ extension DatabaseReader {
func backup(to writer: DatabaseWriter, afterBackupInit: (() -> ())?, afterBackupStep: (() -> ())?) throws {
try read { dbFrom in
try writer.write { dbDest in
try writer.unsafeWrite { dbDest in // Maybe unsafe? We don't know (didn't test) if readers can see a partial backup.
guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main") else {
throw DatabaseError(code: dbDest.lastErrorCode, message: dbDest.lastErrorMessage)
}
+71 -3
View File
@@ -22,7 +22,51 @@ public protocol DatabaseWriter : DatabaseReader {
///
/// The *block* argument is completely isolated. Eventual concurrent
/// database updates are postponed until the block has executed.
func write<T>(_ block: (Database) throws -> T) rethrows -> T
func write<T>(_ block: (Database) throws -> T) throws -> T
/// 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 writer.writeInTransaction { db in
/// db.execute(...)
/// return .commit
/// }
///
/// This method is *not* reentrant.
///
/// - parameters:
/// - kind: The transaction type.
/// 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.
func writeInTransaction(_ kind: Database.TransactionKind?, _ block: (Database) throws -> Database.TransactionCompletion) throws
/// Synchronously executes a block that takes a database connection, and
/// returns its result.
///
/// The *block* argument is completely isolated: eventual concurrent
/// database updates are postponed until the block has executed.
///
/// However, this method poses a threat to concurrent reads if it modifies
/// the database. Readers may seen the database in a constant, but
/// inconsistent state:
///
/// writer.unsafeWrite { db in
/// // Preserve a zero balance
/// try db.execute(db, "INSERT INTO credits ...", arguments: [amount])
/// try db.execute(db, "INSERT INTO debits ...", arguments: [amount])
/// }
///
/// writer.read { db in
/// // Here the balance may not be zero
/// }
///
func unsafeWrite<T>(_ block: (Database) throws -> T) rethrows -> T
// MARK: - Reading from Database
@@ -90,6 +134,30 @@ public protocol DatabaseWriter : DatabaseReader {
func readFromCurrentState(_ block: @escaping (Database) -> Void) throws
}
extension DatabaseWriter {
/// Default implementation for DatabaseWriter.write(). Synchronously
/// executes an update block in a protected dispatch queue,
/// wrapped inside a deferred transaction, and returns its result.
///
/// try dbPool.write { db in
/// try 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: (Database) throws -> T) throws -> T {
var result: T! = nil
try writeInTransaction(.deferred) { db in
result = try block(db)
return .commit
}
return result!
}
}
extension DatabaseWriter {
// MARK: - Transaction Observers
@@ -102,14 +170,14 @@ extension DatabaseWriter {
///
/// - parameter transactionObserver: A transaction observer.
public func add(transactionObserver: TransactionObserver) {
write { db in
unsafeWrite { db in
db.add(transactionObserver: transactionObserver)
}
}
/// Remove a transaction observer.
public func remove(transactionObserver: TransactionObserver) {
write { db in
unsafeWrite { db in
db.remove(transactionObserver: transactionObserver)
}
}
+1 -1
View File
@@ -163,7 +163,7 @@
/// class MyTokenizer : FTS5CustomTokenizer { ... }
/// dbPool.add(tokenizer: MyTokenizer.self)
public func add<Tokenizer: FTS5CustomTokenizer>(tokenizer: Tokenizer.Type) {
write { db in
unsafeWrite { db in // Actually safe since we do not modify the database
db.add(tokenizer: Tokenizer.self)
}
}
+1 -1
View File
@@ -93,7 +93,7 @@ public struct DatabaseMigrator {
/// migrations should apply.
/// - throws: An eventual error thrown by the registered migration blocks.
public func migrate(_ db: DatabaseWriter) throws {
try db.write { db in
try db.unsafeWrite { db in // Actually safe since all migrations run in transaction
try setupMigrations(db)
try runMigrations(db)
}
+3 -3
View File
@@ -144,7 +144,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
// Fetch items on the writing dispatch queue, so that the transaction
// observer is added on the same serialized queue as transaction
// callbacks.
try databaseWriter.write { db in
try databaseWriter.unsafeWrite { db in // Actually safe since we do not modify the database
let initialItems = try Item<Record>.fetchAll(db, request)
fetchedItems = initialItems
if let fetchAndNotifyChanges = fetchAndNotifyChanges {
@@ -188,7 +188,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
// Replace observer so that it tracks a new set of columns,
// and notify eventual changes
let initialItems = fetchedItems
databaseWriter.write { db in
databaseWriter.unsafeWrite { db in // Actually safe since we do not modify the database
let observer = FetchedRecordsObserver(selectionInfo: self.request.selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
self.observer = observer
observer.items = initialItems
@@ -271,7 +271,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
}
let initialItems = fetchedItems
databaseWriter.write { db in
databaseWriter.unsafeWrite { db in // Actually safe since we do not modify the database
let fetchAndNotifyChanges = makeFetchAndNotifyChangesFunction(controller: self, fetchAlongside: fetchAlongside, itemsAreIdentical: itemsAreIdentical!, recordsWillChange: recordsWillChange, tableViewEvent: tableViewEvent, recordsDidChange: recordsDidChange)
let observer = FetchedRecordsObserver(selectionInfo: request.selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
self.observer = observer
@@ -18,7 +18,7 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
try db.execute("CREATE INDEX foobar ON items(foo, bar)")
}
dbPool.write { db in
try dbPool.write { db in
// Assert that the writer cache is empty
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
XCTAssertTrue(db.schemaCache.columns(in: "items") == nil)
@@ -64,7 +64,7 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
XCTAssertTrue(db.schemaCache.indexes(on: "items") != nil)
}
dbPool.write { db in
try dbPool.write { db in
// Assert that writer cache is warmed
XCTAssertTrue(db.schemaCache.primaryKey("items") != nil)
XCTAssertTrue(db.schemaCache.columns(in: "items") != nil)
@@ -9,6 +9,208 @@ import XCTest
class DatabasePoolConcurrencyTests: GRDBTestCase {
func testDatabasePoolFundamental1() {
// Constraint: the sum of values, the balance, must remain zero.
// DatabasePool aims at providing this guarantee, that is to say:
// no reader should ever see a non-zero balance.
//
// This test shows that writes that are not wrapped in a transaction
// can not provide our guarantee.
//
// Reader Writer
// BEGIN DEFERRED TRANSACTION
let s1 = DispatchSemaphore(value: 0)
// INSERT INTO moves VALUES (1)
let s2 = DispatchSemaphore(value: 0)
// SELECT SUM(value) AS balance FROM moves
let s3 = DispatchSemaphore(value: 0)
// INSERT INTO moves VALUES (-1)
let s4 = DispatchSemaphore(value: 0)
// SELECT SUM(value) AS balance FROM moves
// END
assertNoError {
dbConfiguration.trace = { print($0) }
do {
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
let journalMode = try String.fetchOne(db, "PRAGMA journal_mode = wal")
XCTAssertEqual(journalMode, "wal")
try db.create(table: "moves") { $0.column("value", .integer) }
try db.execute("INSERT INTO moves VALUES (0)")
}
}
let s0 = DispatchSemaphore(value: 0)
let block1 = { () in
let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite")
s0.signal() // Avoid "database is locked" error: don't open the two databases at the same time
try! dbQueue.inDatabase { db in
try db.execute("BEGIN DEFERRED TRANSACTION")
s1.signal()
_ = s2.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT SUM(value) AS balance FROM moves"), 1) // Non-zero balance
s3.signal()
_ = s4.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT SUM(value) AS balance FROM moves"), 1) // Non-zero balance
try db.execute("END")
}
}
let block2 = { () in
_ = s0.wait(timeout: .distantFuture) // Avoid "database is locked" error: don't open the two databases at the same time
let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite")
try! dbQueue.inDatabase { db in
_ = s1.wait(timeout: .distantFuture)
try db.execute("INSERT INTO moves VALUES (1)")
s2.signal()
_ = s3.wait(timeout: .distantFuture)
try db.execute("INSERT INTO moves VALUES (-1)")
s4.signal()
}
}
let blocks = [block1, block2]
DispatchQueue.concurrentPerform(iterations: blocks.count) { index in
blocks[index]()
}
}
}
func testDatabasePoolFundamental2() {
// Constraint: the sum of values, the balance, must remain zero.
// DatabasePool aims at providing this guarantee, that is to say:
// no reader should ever see a non-zero balance.
//
// This test shows that writes that happen in a transaction are not
// visible from the reader.
//
// Reader Writer
// BEGIN DEFERRED TRANSACTION
let s1 = DispatchSemaphore(value: 0)
// BEGIN DEFERRED TRANSACTION
let s2 = DispatchSemaphore(value: 0)
// INSERT INTO moves VALUES (1)
let s3 = DispatchSemaphore(value: 0)
// SELECT SUM(value) AS balance FROM moves
let s4 = DispatchSemaphore(value: 0)
// INSERT INTO moves VALUES (-1)
let s5 = DispatchSemaphore(value: 0)
// SELECT SUM(value) AS balance FROM moves
// END END
assertNoError {
do {
let dbQueue = try! makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
let journalMode = try String.fetchOne(db, "PRAGMA journal_mode = wal")
XCTAssertEqual(journalMode, "wal")
try db.create(table: "moves") { $0.column("value", .integer) }
try db.execute("INSERT INTO moves VALUES (0)")
}
}
let s0 = DispatchSemaphore(value: 0)
let block1 = { () in
let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite")
s0.signal() // Avoid "database is locked" error: don't open the two databases at the same time
try! dbQueue.inDatabase { db in
_ = s1.wait(timeout: .distantFuture)
try db.execute("BEGIN DEFERRED TRANSACTION")
s2.signal()
_ = s3.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT SUM(value) AS balance FROM moves"), 0) // Zero balance
s4.signal()
_ = s5.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT SUM(value) AS balance FROM moves"), 0) // Zero balance
try db.execute("END")
}
}
let block2 = { () in
_ = s0.wait(timeout: .distantFuture) // Avoid "database is locked" error: don't open the two databases at the same time
let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite")
try! dbQueue.inDatabase { db in
try db.execute("BEGIN DEFERRED TRANSACTION")
s1.signal()
_ = s2.wait(timeout: .distantFuture)
try db.execute("INSERT INTO moves VALUES (1)")
s3.signal()
_ = s4.wait(timeout: .distantFuture)
try db.execute("INSERT INTO moves VALUES (-1)")
s5.signal()
try db.execute("END")
}
}
let blocks = [block1, block2]
DispatchQueue.concurrentPerform(iterations: blocks.count) { index in
blocks[index]()
}
}
}
func testDatabasePoolFundamental3() {
// Constraint: the sum of values, the balance, must remain zero.
// DatabasePool aims at providing this guarantee, that is to say:
// no reader should ever see a non-zero balance.
//
// This test shows that writes that happen in a transaction are not
// visible from the reader.
//
// Reader Writer
// BEGIN DEFERRED TRANSACTION
let s1 = DispatchSemaphore(value: 0)
// BEGIN DEFERRED TRANSACTION
// INSERT INTO moves VALUES (1)
let s2 = DispatchSemaphore(value: 0)
// SELECT SUM(value) AS balance FROM moves
let s3 = DispatchSemaphore(value: 0)
// INSERT INTO moves VALUES (-1)
let s4 = DispatchSemaphore(value: 0)
// SELECT SUM(value) AS balance FROM moves END
// END
assertNoError {
do {
let dbQueue = try! makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.inDatabase { db in
let journalMode = try String.fetchOne(db, "PRAGMA journal_mode = wal")
XCTAssertEqual(journalMode, "wal")
try db.create(table: "moves") { $0.column("value", .integer) }
try db.execute("INSERT INTO moves VALUES (0)")
}
}
let s0 = DispatchSemaphore(value: 0)
let block1 = { () in
let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite")
s0.signal() // Avoid "database is locked" error: don't open the two databases at the same time
try! dbQueue.inDatabase { db in
try db.execute("BEGIN DEFERRED TRANSACTION")
s1.signal()
_ = s2.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT SUM(value) AS balance FROM moves"), 0) // Zero balance
s3.signal()
_ = s4.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT SUM(value) AS balance FROM moves"), 0) // Zero balance
try db.execute("END")
}
}
let block2 = { () in
_ = s0.wait(timeout: .distantFuture) // Avoid "database is locked" error: don't open the two databases at the same time
let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite")
try! dbQueue.inDatabase { db in
_ = s1.wait(timeout: .distantFuture)
try db.execute("BEGIN DEFERRED TRANSACTION")
try db.execute("INSERT INTO moves VALUES (1)")
s2.signal()
_ = s3.wait(timeout: .distantFuture)
try db.execute("INSERT INTO moves VALUES (-1)")
s4.signal()
try db.execute("END")
}
}
let blocks = [block1, block2]
DispatchQueue.concurrentPerform(iterations: blocks.count) { index in
blocks[index]()
}
}
}
func testWrappedReadWrite() {
assertNoError {
let dbPool = try makeDatabasePool()
@@ -343,13 +545,13 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
let block2 = { () in
try! dbPool.read { db in
_ = s1.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0)
s2.signal()
_ = s3.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0)
s4.signal()
_ = s5.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0)
}
}
let blocks = [block1, block2]
@@ -422,7 +624,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
}
}
func testNonIsolatedReadMethodIsolationOfStatement() {
func testUnsafeReadMethodIsolationOfStatement() {
assertNoError {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
@@ -433,7 +635,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
}
// Block 1 Block 2
// dbPool.nonIsolatedRead {
// dbPool.unsafeRead {
// SELECT * FROM items
// step
// >
@@ -447,7 +649,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// }
let block1 = { () in
try! dbPool.nonIsolatedRead { db in
try! dbPool.unsafeRead { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
s1.signal()
@@ -475,7 +677,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
}
}
func testNonIsolatedReadMethodIsolationOfStatementWithCheckpoint() {
func testUnsafeReadMethodIsolationOfStatementWithCheckpoint() {
assertNoError {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
@@ -486,7 +688,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
}
// Block 1 Block 2
// dbPool.nonIsolatedRead {
// dbPool.unsafeRead {
// SELECT * FROM items
// step
// >
@@ -500,7 +702,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// }
let block1 = { () in
try! dbPool.nonIsolatedRead { db in
try! dbPool.unsafeRead { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
s1.signal()
@@ -528,7 +730,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
}
}
func testNonIsolatedReadMethodIsolationOfBlock() {
func testUnsafeReadMethodIsolationOfBlock() {
assertNoError {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
@@ -536,7 +738,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
}
// Block 1 Block 2
// dbPool.nonIsolatedRead {
// dbPool.unsafeRead {
// SELECT COUNT(*) FROM items -> 0
// >
let s1 = DispatchSemaphore(value: 0)
@@ -548,7 +750,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// }
let block1 = { () in
try! dbPool.nonIsolatedRead { db in
try! dbPool.unsafeRead { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0)
s1.signal()
_ = s2.wait(timeout: .distantFuture)