From b8d924ab6f4560aa052c0dfd20dab094668e01db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 1 Dec 2016 19:17:19 +0100 Subject: [PATCH] Restore DatabasePool in a stable state --- GRDB/Core/DatabasePool.swift | 149 +++++------------- GRDB/Core/DatabaseQueue.swift | 7 - GRDB/Core/DatabaseReader.swift | 10 +- GRDB/Core/DatabaseWriter.swift | 96 ++--------- GRDB/FTS/FTS5CustomTokenizer.swift | 2 +- GRDB/Migrations/DatabaseMigrator.swift | 2 +- GRDB/Record/FetchedRecordsController.swift | 6 +- .../DatabasePoolSchemaCacheTests.swift | 4 +- .../DatabasePoolConcurrencyTests.swift | 34 ++-- 9 files changed, 77 insertions(+), 233 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 23add5be0..c63b87c16 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -281,42 +281,7 @@ extension DatabasePool : DatabaseReader { return try readerPool.get { reader in try reader.sync { db in var result: T? = nil - - // https://www.sqlite.org/isolation.html - // - // > In WAL mode, SQLite exhibits "snapshot isolation". When a - // > read transaction starts, that reader continues to see an - // > unchanging "snapshot" of the database file as it existed at - // > the moment in time when the read transaction started. - // > Any write transactions that commit while the read - // > transaction is active are still invisible to the read - // > transaction, because the reader is seeing a snapshot of - // > database file from a prior moment in time. - // - // This documentation is NOT accurate. SQLite actually defers - // isolation until the first SELECT: - // - // Reader Writer - // BEGIN DEFERRED TRANSACTION - // UPDATE ... (1) - // Here the change (1) is visible - // SELECT ... - // UPDATE ... (2) - // Here the change (2) is not visible - // - // This is very dangerous, because our reader may see an - // inconsistent database state. - // - // Workaround: perform an initial read before letting GRDB user - // perform her own reads: - // - // Reader Writer - // BEGIN DEFERRED TRANSACTION - // SELECT anything - // UPDATE ... - // Here the change is not visible by GRDB user try db.inTransaction(.deferred) { - try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").fetchCursor { }.next() // doesn't work with cached statement result = try block(db) return .commit } @@ -328,11 +293,8 @@ extension DatabasePool : DatabaseReader { /// Synchronously executes a read-only block in a protected dispatch queue, /// and returns its result. /// - /// let persons = try dbPool.unsafeRead { db in - /// try Person.fetchAll(...) - /// } - /// - /// The block is not isolated from eventual concurrent database updates: + /// The block argument is not isolated: eventual concurrent database updates + /// are visible inside the block: /// /// try dbPool.unsafeRead { db in /// // Those two values may be different because some other thread @@ -341,6 +303,14 @@ extension DatabasePool : DatabaseReader { /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! /// } /// + /// Cursor iteration is safe, though: + /// + /// try dbPool.unsafeRead { db in + /// // No concurrent update can mess with this iteration: + /// let rows = try Row.fetchCursor(db, "SELECT ...") + /// while let row = try rows.next() { ... } + /// } + /// /// This method is *not* reentrant. /// /// - parameter block: A block that accesses the database. @@ -417,64 +387,26 @@ extension DatabasePool : DatabaseWriter { // MARK: - Writing in Database - /// Synchronously executes a block in a protected dispatch queue, wrapped - /// inside a deferred transaction. + /// Synchronously executes an update block in a protected dispatch queue, + /// and returns its result. /// /// Eventual concurrent database updates are postponed until the block /// has executed. /// - /// Eventual concurrent readers do not see partial changes: + /// try dbPool.write { db in + /// try db.execute(...) + /// } /// - /// dbPool.write { db in - /// // Eventually preserve a zero balance - /// try db.execute(db, "INSERT INTO credits ...", arguments: [amount]) - /// try db.execute(db, "INSERT INTO debits ...", arguments: [amount]) - /// } - /// - /// dbPool.read { db in - /// // Here the balance is guaranteed to be zero - /// } + /// To maintain database integrity, and preserve eventual concurrent reads + /// from seeing an inconsistent database state, prefer the + /// writeInTransaction method. /// /// This method is *not* reentrant. - public func write(_ block: (Database) throws -> T) throws -> T { - var result: T! = nil - try writeInTransaction(.deferred) { db in - result = try block(db) - return .commit - } - return result! - } - - /// Synchronously executes a block that takes a database connection, without - /// opening any transaction, and returns its result. /// - /// Eventual concurrent database updates are postponed until the block - /// has executed. - /// - /// Eventual concurrent readers do not see partial changes: - /// - /// - warning: This method poses a threat to concurrent reads if it modifies - /// the database outside of a transaction. Readers may see the database - /// in an inconsistent state: - /// - /// dbPool.unsafeWrite { db in - /// // Eventually preserve a zero balance - /// try db.execute(db, "INSERT INTO credits ...", arguments: [amount]) - /// try db.execute(db, "INSERT INTO debits ...", arguments: [amount]) - /// } - /// - /// dbPool.read { db in - /// // Here the balance may not be zero - /// } - /// - /// To use this unsafe method safely, don't modify the database, or make - /// sure you wrap in a transaction changes that must occur together: - /// - /// // A safe usage of the unsafeWrite method - /// dbPool.unsafeWrite { db in - /// db.inTransaction { ... } - /// } - public func unsafeWrite(_ block: (Database) throws -> T) rethrows -> T { + /// - parameters block: A block that executes SQL statements and return + /// either .commit or .rollback. + /// - throws: The error thrown by the block. + public func write(_ block: (Database) throws -> T) rethrows -> T { return try writer.sync(block) } @@ -495,15 +427,15 @@ extension DatabasePool : DatabaseWriter { /// /// Eventual concurrent readers do not see partial changes: /// - /// dbPool.writeInTransaction { db in - /// // Eventually preserve a zero balance - /// try db.execute(db, "INSERT INTO credits ...", arguments: [amount]) - /// try db.execute(db, "INSERT INTO debits ...", arguments: [amount]) - /// } + /// dbPool.writeInTransaction { db in + /// // Eventually preserve a zero balance + /// try db.execute(db, "INSERT INTO credits ...", arguments: [amount]) + /// try db.execute(db, "INSERT INTO debits ...", arguments: [amount]) + /// } /// - /// dbPool.read { db in - /// // Here the balance is guaranteed to be zero - /// } + /// dbPool.read { db in + /// // Here the balance is guaranteed to be zero + /// } /// /// This method is *not* reentrant. /// @@ -514,7 +446,8 @@ extension DatabasePool : DatabaseWriter { /// for more information. /// - block: A block that executes SQL statements and return either /// .commit or .rollback. - /// - throws: The error thrown by the block. + /// - 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 { try writer.sync { db in try db.inTransaction(kind) { @@ -535,10 +468,11 @@ extension DatabasePool : DatabaseWriter { /// committed state at the moment this method is called. Eventual concurrent /// database updates are *not visible* inside the block. /// - /// TODO: THIS IS INACCURATE - /// /// try dbPool.write { db in - /// try db.execute("DELETE FROM persons") + /// try db.inTransaction { + /// try db.execute("DELETE FROM persons") + /// return .commit + /// } /// try dbPool.readFromCurrentState { db in /// // Guaranteed to be zero /// try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")! @@ -547,10 +481,7 @@ extension DatabasePool : DatabaseWriter { /// } /// /// This method blocks the current thread until the isolation guarantee has - /// been established. - /// - /// The database pool releases the writing dispatch queue early, before the - /// block has finished. + /// been established, and before the block argument has run. public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws { writer.preconditionValidQueue() @@ -582,12 +513,12 @@ extension DatabasePool : DatabaseWriter { // This is not the guarantee expected by this method: no change // at all should be visible. // - // Workaround: perform an initial read before letting GRDB user - // perform her own reads: + // Workaround: perform an initial read before releasing the + // writer queue: // // Reader Writer // BEGIN DEFERRED TRANSACTION - // SELECT anything + // SELECT anything -- the work around // UPDATE ... // Here the change is not visible by GRDB user try! db.inTransaction(.deferred) { // Assume deferred transactions are always possible in a read-only WAL database diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 59a406156..203069391 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -299,13 +299,6 @@ extension DatabaseQueue : DatabaseWriter { // MARK: - DatabaseWriter Protocol Adoption - /// Alias for inDatabase - /// - /// This method is part of the DatabaseWriter protocol adoption. - public func unsafeWrite(_ block: (Database) throws -> T) rethrows -> T { - return try inDatabase(block) - } - /// Alias for inDatabase /// /// This method is part of the DatabaseWriter protocol adoption. diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index e0d2ef80f..999456a30 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -65,10 +65,10 @@ public protocol DatabaseReader : class { /// are visible inside the block: /// /// try reader.unsafeRead { db in - /// // Those two ints may be different: - /// let sql = "SELECT ..." - /// let int1 = try Int.fetchOne(db, sql) - /// let int2 = try Int.fetchOne(db, sql) + /// // 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")! + /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! /// } /// /// Cursor iteration is safe, though: @@ -139,7 +139,7 @@ extension DatabaseReader { func backup(to writer: DatabaseWriter, afterBackupInit: (() -> ())?, afterBackupStep: (() -> ())?) throws { try read { dbFrom in - try writer.unsafeWrite { dbDest in // Maybe unsafe? We don't know (didn't test) if readers can see a partial backup. + try writer.write { dbDest in guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main") else { throw DatabaseError(code: dbDest.lastErrorCode, message: dbDest.lastErrorMessage) } diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index e940c2e8a..bc95c33e8 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -18,92 +18,13 @@ public protocol DatabaseWriter : DatabaseReader { // MARK: - Writing in Database /// Synchronously executes a block that takes a database connection, and - /// returns its result. The block may or may not be wrapped in a - /// transaction. + /// returns its result. /// /// Eventual concurrent database updates are postponed until the block /// has executed. /// - /// Eventual concurrent readers are isolated and do not see partial changes: - /// - /// writer.write { db in - /// // Eventually 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 is guaranteed to be zero - /// } - /// /// This method is *not* reentrant. - func write(_ block: (Database) throws -> T) throws -> T - - /// 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 - /// also rollbacked, but no error is thrown. - /// - /// try writer.writeInTransaction { db in - /// db.execute(...) - /// return .commit - /// } - /// - /// Eventual concurrent readers are isolated and do not see partial changes: - /// - /// writer.writeInTransaction { db in - /// // Eventually 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 is guaranteed to be zero - /// } - /// - /// 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, without - /// opening any transaction, and returns its result. - /// - /// Eventual concurrent database updates are postponed until the block - /// has executed. - /// - /// - warning: This method poses a threat to concurrent reads if it modifies - /// the database outside of a transaction. Readers may see the database - /// in constant but inconsistent state: - /// - /// writer.unsafeWrite { db in - /// // Eventually 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 - /// } - /// - /// To use this unsafe method safely, don't modify the database, or make - /// sure you wrap in a transaction changes that must occur together: - /// - /// // A safe usage of the unsafeWrite method - /// writer.unsafeWrite { db in - /// db.inTransaction { ... } - /// } - func unsafeWrite(_ block: (Database) throws -> T) rethrows -> T + func write(_ block: (Database) throws -> T) rethrows -> T // MARK: - Reading from Database @@ -122,10 +43,11 @@ public protocol DatabaseWriter : DatabaseReader { /// - When this method is called outside of any transaction, the current /// state is the last committed state. /// - /// TODO: THIS IS INACCURATE - /// /// try writer.write { db in - /// try db.execute("DELETE FROM persons") + /// try db.inTransaction { + /// try db.execute("DELETE FROM persons") + /// return .commit + /// } /// try writer.readFromCurrentState { db in /// // Guaranteed to be zero /// try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")! @@ -170,6 +92,8 @@ public protocol DatabaseWriter : DatabaseReader { /// return .commit /// } /// } + /// + /// This method is *not* reentrant. func readFromCurrentState(_ block: @escaping (Database) -> Void) throws } @@ -185,14 +109,14 @@ extension DatabaseWriter { /// /// - parameter transactionObserver: A transaction observer. public func add(transactionObserver: TransactionObserver) { - unsafeWrite { db in + write { db in db.add(transactionObserver: transactionObserver) } } /// Remove a transaction observer. public func remove(transactionObserver: TransactionObserver) { - unsafeWrite { db in + write { db in db.remove(transactionObserver: transactionObserver) } } diff --git a/GRDB/FTS/FTS5CustomTokenizer.swift b/GRDB/FTS/FTS5CustomTokenizer.swift index 772ab8eaf..083bbfa67 100644 --- a/GRDB/FTS/FTS5CustomTokenizer.swift +++ b/GRDB/FTS/FTS5CustomTokenizer.swift @@ -163,7 +163,7 @@ /// class MyTokenizer : FTS5CustomTokenizer { ... } /// dbPool.add(tokenizer: MyTokenizer.self) public func add(tokenizer: Tokenizer.Type) { - unsafeWrite { db in // Actually safe since we do not modify the database + write { db in db.add(tokenizer: Tokenizer.self) } } diff --git a/GRDB/Migrations/DatabaseMigrator.swift b/GRDB/Migrations/DatabaseMigrator.swift index 1d08099a1..71772ce7b 100644 --- a/GRDB/Migrations/DatabaseMigrator.swift +++ b/GRDB/Migrations/DatabaseMigrator.swift @@ -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.unsafeWrite { db in // Actually safe since all migrations run in transaction + try db.write { db in try setupMigrations(db) try runMigrations(db) } diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index a8a54ae87..c9ca5a783 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -144,7 +144,7 @@ public final class FetchedRecordsController { // Fetch items on the writing dispatch queue, so that the transaction // observer is added on the same serialized queue as transaction // callbacks. - try databaseWriter.unsafeWrite { db in // Actually safe since we do not modify the database + try databaseWriter.write { db in let initialItems = try Item.fetchAll(db, request) fetchedItems = initialItems if let fetchAndNotifyChanges = fetchAndNotifyChanges { @@ -188,7 +188,7 @@ public final class FetchedRecordsController { // Replace observer so that it tracks a new set of columns, // and notify eventual changes let initialItems = fetchedItems - databaseWriter.unsafeWrite { db in // Actually safe since we do not modify the database + databaseWriter.write { db in let observer = FetchedRecordsObserver(selectionInfo: self.request.selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges) self.observer = observer observer.items = initialItems @@ -271,7 +271,7 @@ public final class FetchedRecordsController { } let initialItems = fetchedItems - databaseWriter.unsafeWrite { db in // Actually safe since we do not modify the database + databaseWriter.write { db in 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 diff --git a/Tests/Private/DatabasePoolSchemaCacheTests.swift b/Tests/Private/DatabasePoolSchemaCacheTests.swift index e84ced893..c984cdeed 100644 --- a/Tests/Private/DatabasePoolSchemaCacheTests.swift +++ b/Tests/Private/DatabasePoolSchemaCacheTests.swift @@ -18,7 +18,7 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { try db.execute("CREATE INDEX foobar ON items(foo, bar)") } - try dbPool.write { db in + 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) } - try dbPool.write { db in + dbPool.write { db in // Assert that writer cache is warmed XCTAssertTrue(db.schemaCache.primaryKey("items") != nil) XCTAssertTrue(db.schemaCache.columns(in: "items") != nil) diff --git a/Tests/Public/Core/DatabasePool/DatabasePoolConcurrencyTests.swift b/Tests/Public/Core/DatabasePool/DatabasePoolConcurrencyTests.swift index 53766ed76..745a50526 100644 --- a/Tests/Public/Core/DatabasePool/DatabasePoolConcurrencyTests.swift +++ b/Tests/Public/Core/DatabasePool/DatabasePoolConcurrencyTests.swift @@ -11,11 +11,11 @@ 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. + // This test shows (if needed) that writes that are not wrapped in a + // transaction can not provide our guarantee, and that deferred + // transaction provide the immutable view of the database needed by + // dbPool.read(). // // Reader Writer // BEGIN DEFERRED TRANSACTION @@ -76,14 +76,12 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { 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. + // This test shows that deferred transactions play well with concurrent + // immediate transactions. // // Reader Writer - // BEGIN DEFERRED TRANSACTION + // BEGIN IMMEDIATE TRANSACTION let s1 = DispatchSemaphore(value: 0) // BEGIN DEFERRED TRANSACTION let s2 = DispatchSemaphore(value: 0) @@ -146,16 +144,14 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { 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. + // This test shows that deferred transactions play well with concurrent + // immediate transactions. // // Reader Writer // BEGIN DEFERRED TRANSACTION let s1 = DispatchSemaphore(value: 0) - // BEGIN DEFERRED TRANSACTION + // BEGIN IMMEDIATE TRANSACTION // INSERT INTO moves VALUES (1) let s2 = DispatchSemaphore(value: 0) // SELECT SUM(value) AS balance FROM moves @@ -428,10 +424,10 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { try! dbPool.read { db in s1.signal() _ = s2.wait(timeout: .distantFuture) - XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0) + XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1) // Not a bug. The writer did not start a transaction. s3.signal() _ = s4.wait(timeout: .distantFuture) - XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0) + XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1) } } let block2 = { () in @@ -545,13 +541,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")!, 0) + XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1) s2.signal() _ = s3.wait(timeout: .distantFuture) - XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0) + XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1) s4.signal() _ = s5.wait(timeout: .distantFuture) - XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0) + XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1) } } let blocks = [block1, block2]