From 49609ff08eda1d91b7ff3501be3952cdd270849b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 31 Oct 2017 08:17:48 +0100 Subject: [PATCH] Fix failing tests for observation of empty deferred transactions --- GRDB/Core/TransactionObserver.swift | 50 +++++++++++++++++++++++++---- 1 file changed, 44 insertions(+), 6 deletions(-) diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 9446525c7..4623c19bc 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -261,13 +261,33 @@ class DatabaseObservationBroker { case .commitTransaction: if case .none = self.transactionState { - // A COMMIT statement has ended a deferred transaction - // that did not open, and sqlite_commit_hook was not - // called. + // A COMMIT statement has ended an empty deferred + // transaction. For SQLite, no transaction has ever begun: // - // BEGIN DEFERRED TRANSACTION - // COMMIT - self.transactionState = .commit + // BEGIN DEFERRED TRANSACTION + // COMMIT + // + // We don't need to tell transaction observers about it. + // + // But we have to take care of the .nextTransaction + // observation extent. In the sample code below, the + // observer must not be notified of the second transaction, + // because this is the intent of the programmer: + // + // // Register an observer for next transaction only + // let observer = Observer() + // dbQueue.add(transactionObserver:observer, extent: .nextTransaction) + // + // try dbQueue.inTransaction(.deferred) { db in + // return .commit + // } + // + // // Must not notify observer + // try dbQueue.inTransaction(.deferred) { db in + // try db.execute("...") + // return .commit + // } + emptyDeferredTransactionDidCommit() } case .rollbackTransaction: @@ -365,6 +385,14 @@ class DatabaseObservationBroker { cleanupTransactionObservations() } + // Called from updateStatementDidExecute + private func emptyDeferredTransactionDidCommit() { + for observation in transactionObservations { + observation.emptyDeferredTransactionDidCommit(database) + } + cleanupTransactionObservations() + } + // Called from updateStatementDidExecute or updateStatementDidFails private func databaseDidRollback(notifyTransactionObservers: Bool) { savepointStack.clear() @@ -561,6 +589,16 @@ final class TransactionObservation { } } } + + func emptyDeferredTransactionDidCommit(_ db: Database) { + switch extent { + case .observerLifetime, .databaseLifetime: + break + case .nextTransaction: + // Observer most not get any further notification. + strongObserver = nil + } + } func databaseDidRollback(_ db: Database) { switch extent {