mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-28 04:24:20 +00:00
TransactionObserver.ignoreDatabaseChangesUntilNextTransaction()
This commit is contained in:
1 parent
2c8f9dffdd
commit
a1e508b1df
5 files changed
+157
-105
No files matched your search
@@ -270,7 +270,7 @@ extension Database {
|
||||
setupBusyMode()
|
||||
setupDefaultFunctions()
|
||||
setupDefaultCollations()
|
||||
observationBroker.setup()
|
||||
observationBroker.installCommitAndRollbackHooks()
|
||||
}
|
||||
|
||||
private func setupTrace() {
|
||||
|
||||
@@ -16,14 +16,15 @@ import Dispatch
|
||||
/// of the dispatch queue, a SchedulingWatchdog that allows that database only.
|
||||
///
|
||||
/// Later on, the queue can be shared by several databases with the method
|
||||
/// allowing(databases:execute:). See SerializedDatabase.sync() for
|
||||
/// an example.
|
||||
/// inheritingAllowedDatabases(from:execute:). See SerializedDatabase.sync()
|
||||
/// for an example.
|
||||
///
|
||||
/// - preconditionValidQueue() crashes whenever a database is used in an invalid
|
||||
/// dispatch queue.
|
||||
final class SchedulingWatchdog {
|
||||
private static let specificKey = DispatchSpecificKey<SchedulingWatchdog>()
|
||||
private(set) var allowedDatabases: [Database]
|
||||
private var databaseObservationBroker: DatabaseObservationBroker?
|
||||
|
||||
private init(allowedDatabase database: Database) {
|
||||
allowedDatabases = [database]
|
||||
@@ -36,27 +37,28 @@ final class SchedulingWatchdog {
|
||||
return queue
|
||||
}
|
||||
|
||||
// Temporarily allows `databases` while executing `body`
|
||||
func allowing<T>(databases: [Database], execute body: () throws -> T) rethrows -> T {
|
||||
func inheritingAllowedDatabases<T>(from other: SchedulingWatchdog, execute body: () throws -> T) rethrows -> T {
|
||||
let backup = allowedDatabases
|
||||
allowedDatabases.append(contentsOf: databases)
|
||||
allowedDatabases.append(contentsOf: other.allowedDatabases)
|
||||
defer { allowedDatabases = backup }
|
||||
return try body()
|
||||
}
|
||||
|
||||
static func preconditionValidQueue(_ db: Database, _ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
|
||||
GRDBPrecondition(allows(db), message, file: file, line: line)
|
||||
}
|
||||
|
||||
static func allows(_ db: Database) -> Bool {
|
||||
return current?.allows(db) ?? false
|
||||
}
|
||||
|
||||
func allows(_ db: Database) -> Bool {
|
||||
return allowedDatabases.contains { $0 === db }
|
||||
GRDBPrecondition(current?.allows(db) ?? false, message, file: file, line: line)
|
||||
}
|
||||
|
||||
static var current: SchedulingWatchdog? {
|
||||
return DispatchQueue.getSpecific(key: specificKey)
|
||||
}
|
||||
|
||||
static var currentDatabaseObservationBroker: DatabaseObservationBroker? {
|
||||
get { return current?.databaseObservationBroker }
|
||||
set { current!.databaseObservationBroker = newValue }
|
||||
}
|
||||
|
||||
func allows(_ db: Database) -> Bool {
|
||||
return allowedDatabases.contains { $0 === db }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ final class SerializedDatabase {
|
||||
|
||||
// Case 3
|
||||
return try queue.sync {
|
||||
try SchedulingWatchdog.current!.allowing(databases: watchdog.allowedDatabases) {
|
||||
try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) {
|
||||
try block(db)
|
||||
}
|
||||
}
|
||||
@@ -136,7 +136,7 @@ final class SerializedDatabase {
|
||||
|
||||
// Case 3
|
||||
return try queue.sync {
|
||||
try SchedulingWatchdog.current!.allowing(databases: watchdog.allowedDatabases) {
|
||||
try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) {
|
||||
try block(db)
|
||||
}
|
||||
}
|
||||
@@ -151,7 +151,7 @@ final class SerializedDatabase {
|
||||
|
||||
/// Returns true if any only if the current dispatch queue is valid.
|
||||
var onValidQueue: Bool {
|
||||
return SchedulingWatchdog.allows(db)
|
||||
return SchedulingWatchdog.current?.allows(db) ?? false
|
||||
}
|
||||
|
||||
/// Executes the block in the current queue.
|
||||
|
||||
@@ -80,6 +80,8 @@ extension Database {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - DatabaseObservationBroker
|
||||
|
||||
/// This class provides support for transaction observers.
|
||||
///
|
||||
/// Let's have a detailed look at how a transaction observer is notified:
|
||||
@@ -173,36 +175,7 @@ class DatabaseObservationBroker {
|
||||
self.database = database
|
||||
}
|
||||
|
||||
func setup() {
|
||||
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
|
||||
sqlite3_commit_hook(database.sqliteConnection, { brokerPointer in
|
||||
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
|
||||
do {
|
||||
try broker.databaseWillCommit()
|
||||
broker.transactionState = .commit
|
||||
// Next step: updateStatementDidExecute()
|
||||
return 0
|
||||
} catch {
|
||||
broker.transactionState = .cancelledCommit(error)
|
||||
// Next step: sqlite3_rollback_hook callback
|
||||
return 1
|
||||
}
|
||||
}, brokerPointer)
|
||||
|
||||
|
||||
sqlite3_rollback_hook(database.sqliteConnection, { brokerPointer in
|
||||
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
|
||||
switch broker.transactionState {
|
||||
case .cancelledCommit:
|
||||
// Next step: updateStatementDidFail()
|
||||
break
|
||||
default:
|
||||
broker.transactionState = .rollback
|
||||
// Next step: updateStatementDidExecute()
|
||||
}
|
||||
}, brokerPointer)
|
||||
}
|
||||
// MARK: - Transaction observers
|
||||
|
||||
func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent) {
|
||||
transactionObservations.append(TransactionObservation(observer: transactionObserver, extent: extent))
|
||||
@@ -218,7 +191,24 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
}
|
||||
|
||||
func disableUntilNextTransaction(transactionObserver: TransactionObserver) {
|
||||
if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver)}) {
|
||||
observation.isDisabledUntilNextTransaction = true
|
||||
statementObservations.removeFirst { $0.0 === observation }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Statement execution
|
||||
|
||||
func updateStatementWillExecute(_ statement: UpdateStatement) {
|
||||
// Transaction observers may disable themselves during statement
|
||||
// execution: see TransactionObserver.ignoreDatabaseChangesUntilNextTransaction()
|
||||
//
|
||||
// This convenient method uses cooperation from SchedulingWatchdog in
|
||||
// order to access the broker that is executing a database statement in
|
||||
// the current thread.
|
||||
SchedulingWatchdog.currentDatabaseObservationBroker = self
|
||||
|
||||
// Fill statementObservations with observations that are interested in
|
||||
// the kind of events performed by the statement.
|
||||
//
|
||||
@@ -272,6 +262,7 @@ class DatabaseObservationBroker {
|
||||
func updateStatementDidFail(_ statement: UpdateStatement) throws {
|
||||
// Wait for next statement
|
||||
statementObservations = []
|
||||
SchedulingWatchdog.currentDatabaseObservationBroker = nil
|
||||
|
||||
// Reset transactionState before databaseDidRollback eventually
|
||||
// executes other statements.
|
||||
@@ -295,6 +286,7 @@ class DatabaseObservationBroker {
|
||||
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
|
||||
// Wait for next statement
|
||||
statementObservations = []
|
||||
SchedulingWatchdog.currentDatabaseObservationBroker = nil
|
||||
|
||||
// Has statement any effect on transaction/savepoints?
|
||||
if let transactionEffect = statement.transactionEffect {
|
||||
@@ -309,7 +301,7 @@ class DatabaseObservationBroker {
|
||||
// BEGIN DEFERRED TRANSACTION; COMMIT
|
||||
//
|
||||
// This special case has a dedicated handling:
|
||||
return try emptyDeferredTransactionDidCommit()
|
||||
return try databaseDidCommitEmptyDeferredTransaction()
|
||||
}
|
||||
|
||||
case .rollbackTransaction:
|
||||
@@ -329,7 +321,7 @@ class DatabaseObservationBroker {
|
||||
// SAVEPOINT foo; RELEASE SAVEPOINT foo
|
||||
//
|
||||
// This special case has a dedicated handling:
|
||||
return try emptyDeferredTransactionDidCommit()
|
||||
return try databaseDidCommitEmptyDeferredTransaction()
|
||||
}
|
||||
|
||||
if savepointStack.isEmpty {
|
||||
@@ -384,7 +376,9 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
}
|
||||
|
||||
// Called from sqlite3_commit_hook and emptyDeferredTransactionDidCommit()
|
||||
// MARK: - End of transaction
|
||||
|
||||
// Called from sqlite3_commit_hook and databaseDidCommitEmptyDeferredTransaction()
|
||||
private func databaseWillCommit() throws {
|
||||
notifyBufferedEvents()
|
||||
for observation in transactionObservations {
|
||||
@@ -392,17 +386,6 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
}
|
||||
|
||||
private func notifyBufferedEvents() {
|
||||
let eventsBuffer = savepointStack.eventsBuffer
|
||||
savepointStack.clear()
|
||||
|
||||
for (event, statementObservations) in eventsBuffer {
|
||||
for (observation, predicate) in statementObservations where predicate.evaluate(event) {
|
||||
event.send(to: observation)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Called from updateStatementDidExecute
|
||||
private func databaseDidCommit() {
|
||||
savepointStack.clear()
|
||||
@@ -410,11 +393,11 @@ class DatabaseObservationBroker {
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidCommit(database)
|
||||
}
|
||||
cleanupTransactionObservations()
|
||||
databaseDidEndTransaction()
|
||||
}
|
||||
|
||||
// Called from updateStatementDidExecute
|
||||
private func emptyDeferredTransactionDidCommit() throws {
|
||||
private func databaseDidCommitEmptyDeferredTransaction() throws {
|
||||
// A statement that ends a transaction has been executed. But for
|
||||
// SQLite, no transaction at all has started, and sqlite3_commit_hook
|
||||
// was not triggered:
|
||||
@@ -464,11 +447,69 @@ class DatabaseObservationBroker {
|
||||
observation.databaseDidRollback(database)
|
||||
}
|
||||
}
|
||||
cleanupTransactionObservations()
|
||||
databaseDidEndTransaction()
|
||||
}
|
||||
|
||||
/// Remove transaction observers that have stopped observing transaction,
|
||||
/// and uninstall SQLite update hooks if there is no remaining observers.
|
||||
private func databaseDidEndTransaction() {
|
||||
transactionObservations = transactionObservations.filter { $0.isObserving }
|
||||
|
||||
if transactionObservations.isEmpty {
|
||||
uninstallUpdateHook()
|
||||
}
|
||||
|
||||
for observation in transactionObservations {
|
||||
observation.isDisabledUntilNextTransaction = false
|
||||
}
|
||||
}
|
||||
|
||||
private func notifyBufferedEvents() {
|
||||
let eventsBuffer = savepointStack.eventsBuffer
|
||||
savepointStack.clear()
|
||||
|
||||
for (event, statementObservations) in eventsBuffer {
|
||||
for (observation, predicate) in statementObservations where predicate.evaluate(event) {
|
||||
event.send(to: observation)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLite hooks
|
||||
|
||||
func installCommitAndRollbackHooks() {
|
||||
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
|
||||
sqlite3_commit_hook(database.sqliteConnection, { brokerPointer in
|
||||
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
|
||||
do {
|
||||
try broker.databaseWillCommit()
|
||||
broker.transactionState = .commit
|
||||
// Next step: updateStatementDidExecute()
|
||||
return 0
|
||||
} catch {
|
||||
broker.transactionState = .cancelledCommit(error)
|
||||
// Next step: sqlite3_rollback_hook callback
|
||||
return 1
|
||||
}
|
||||
}, brokerPointer)
|
||||
|
||||
sqlite3_rollback_hook(database.sqliteConnection, { brokerPointer in
|
||||
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
|
||||
switch broker.transactionState {
|
||||
case .cancelledCommit:
|
||||
// Next step: updateStatementDidFail()
|
||||
break
|
||||
default:
|
||||
broker.transactionState = .rollback
|
||||
// Next step: updateStatementDidExecute()
|
||||
}
|
||||
}, brokerPointer)
|
||||
}
|
||||
|
||||
private func installUpdateHook() {
|
||||
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
|
||||
sqlite3_update_hook(database.sqliteConnection, { (brokerPointer, updateKind, databaseNameCString, tableNameCString, rowID) in
|
||||
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
|
||||
broker.databaseDidChange(with: DatabaseEvent(
|
||||
@@ -499,16 +540,7 @@ class DatabaseObservationBroker {
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Remove transaction observers that have stopped observing transaction,
|
||||
/// and uninstall SQLite update hooks if there is no remaining observers.
|
||||
private func cleanupTransactionObservations() {
|
||||
transactionObservations = transactionObservations.filter { $0.isObserving }
|
||||
if transactionObservations.isEmpty {
|
||||
uninstallUpdateHook()
|
||||
}
|
||||
}
|
||||
|
||||
/// The states that keep track of transaction completions
|
||||
/// The various states of SQLite transactions
|
||||
enum TransactionState {
|
||||
case none
|
||||
case commit
|
||||
@@ -517,6 +549,8 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - TransactionObserver
|
||||
|
||||
/// A transaction observer is notified of all changes and transactions committed
|
||||
/// or rollbacked on a database.
|
||||
///
|
||||
@@ -597,9 +631,21 @@ public protocol TransactionObserver : class {
|
||||
#endif
|
||||
}
|
||||
|
||||
extension TransactionObserver {
|
||||
func ignoreDatabaseChangesUntilNextTransaction() {
|
||||
guard let broker = SchedulingWatchdog.currentDatabaseObservationBroker else {
|
||||
fatalError("ignoreDatabaseChangesUntilNextTransaction must be called from the databaseDidChange method")
|
||||
}
|
||||
broker.disableUntilNextTransaction(transactionObserver: self)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - TransactionObservation
|
||||
|
||||
/// This class manages the observation extent of a transaction observer
|
||||
final class TransactionObservation {
|
||||
let extent: Database.TransactionObservationExtent
|
||||
var isDisabledUntilNextTransaction: Bool = false
|
||||
private weak var weakObserver: TransactionObserver?
|
||||
private var strongObserver: TransactionObserver?
|
||||
private var observer: TransactionObserver? { return strongObserver ?? weakObserver }
|
||||
@@ -626,10 +672,19 @@ final class TransactionObservation {
|
||||
}
|
||||
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
if isDisabledUntilNextTransaction { return false }
|
||||
return observer?.observes(eventsOfKind: eventKind) ?? false
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
func databaseWillChange(with event: DatabasePreUpdateEvent) {
|
||||
if isDisabledUntilNextTransaction { return }
|
||||
observer?.databaseWillChange(with: event)
|
||||
}
|
||||
#endif
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
if isDisabledUntilNextTransaction { return }
|
||||
observer?.databaseDidChange(with: event)
|
||||
}
|
||||
|
||||
@@ -643,7 +698,7 @@ final class TransactionObservation {
|
||||
observer?.databaseDidCommit(db)
|
||||
case .nextTransaction:
|
||||
if let observer = self.observer {
|
||||
// Observer most not get any further notification.
|
||||
// Observer must not get any further notification.
|
||||
// So we "forget" the observer before its `databaseDidCommit`
|
||||
// implementation eventually triggers another database change.
|
||||
strongObserver = nil
|
||||
@@ -658,7 +713,7 @@ final class TransactionObservation {
|
||||
observer?.databaseDidRollback(db)
|
||||
case .nextTransaction:
|
||||
if let observer = self.observer {
|
||||
// Observer most not get any further notification.
|
||||
// Observer must not get any further notification.
|
||||
// So we "forget" the observer before its `databaseDidRollback`
|
||||
// implementation eventually triggers another database change.
|
||||
strongObserver = nil
|
||||
@@ -666,14 +721,12 @@ final class TransactionObservation {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
func databaseWillChange(with event: DatabasePreUpdateEvent) {
|
||||
observer?.databaseWillChange(with: event)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
typealias StatementObservation = (TransactionObservation, DatabaseEventPredicate)
|
||||
|
||||
// MARK: - Database events
|
||||
|
||||
/// A kind of database event. See Database.add(transactionObserver:)
|
||||
/// and DatabaseWriter.add(transactionObserver:).
|
||||
public enum DatabaseEventKind {
|
||||
@@ -1087,7 +1140,7 @@ enum DatabaseEventPredicate {
|
||||
}
|
||||
}
|
||||
|
||||
typealias StatementObservation = (TransactionObservation, DatabaseEventPredicate)
|
||||
// MARK: - SavepointStack
|
||||
|
||||
/// The SQLite savepoint stack is described at
|
||||
/// https://www.sqlite.org/lang_savepoint.html
|
||||
@@ -1153,3 +1206,4 @@ class SavepointStack {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,33 +21,29 @@ class SchedulingWatchdogTests: GRDBTestCase {
|
||||
dbQueue2.inDatabase { db2 = $0 }
|
||||
dbQueue3.inDatabase { db3 = $0 }
|
||||
|
||||
XCTAssertFalse(SchedulingWatchdog.allows(db1))
|
||||
XCTAssertFalse(SchedulingWatchdog.allows(db2))
|
||||
XCTAssertFalse(SchedulingWatchdog.allows(db3))
|
||||
XCTAssertNil(SchedulingWatchdog.current)
|
||||
dbQueue1.inDatabase { _ in
|
||||
XCTAssertTrue(SchedulingWatchdog.allows(db1))
|
||||
XCTAssertFalse(SchedulingWatchdog.allows(db2))
|
||||
XCTAssertFalse(SchedulingWatchdog.allows(db3))
|
||||
XCTAssertTrue(SchedulingWatchdog.current!.allows(db1))
|
||||
XCTAssertFalse(SchedulingWatchdog.current!.allows(db2))
|
||||
XCTAssertFalse(SchedulingWatchdog.current!.allows(db3))
|
||||
dbQueue2.inDatabase { _ in
|
||||
XCTAssertTrue(SchedulingWatchdog.allows(db1))
|
||||
XCTAssertTrue(SchedulingWatchdog.allows(db2))
|
||||
XCTAssertFalse(SchedulingWatchdog.allows(db3))
|
||||
XCTAssertTrue(SchedulingWatchdog.current!.allows(db1))
|
||||
XCTAssertTrue(SchedulingWatchdog.current!.allows(db2))
|
||||
XCTAssertFalse(SchedulingWatchdog.current!.allows(db3))
|
||||
dbQueue3.inDatabase { _ in
|
||||
XCTAssertTrue(SchedulingWatchdog.allows(db1))
|
||||
XCTAssertTrue(SchedulingWatchdog.allows(db2))
|
||||
XCTAssertTrue(SchedulingWatchdog.allows(db3))
|
||||
XCTAssertTrue(SchedulingWatchdog.current!.allows(db1))
|
||||
XCTAssertTrue(SchedulingWatchdog.current!.allows(db2))
|
||||
XCTAssertTrue(SchedulingWatchdog.current!.allows(db3))
|
||||
}
|
||||
XCTAssertTrue(SchedulingWatchdog.allows(db1))
|
||||
XCTAssertTrue(SchedulingWatchdog.allows(db2))
|
||||
XCTAssertFalse(SchedulingWatchdog.allows(db3))
|
||||
XCTAssertTrue(SchedulingWatchdog.current!.allows(db1))
|
||||
XCTAssertTrue(SchedulingWatchdog.current!.allows(db2))
|
||||
XCTAssertFalse(SchedulingWatchdog.current!.allows(db3))
|
||||
}
|
||||
XCTAssertTrue(SchedulingWatchdog.allows(db1))
|
||||
XCTAssertFalse(SchedulingWatchdog.allows(db3))
|
||||
XCTAssertFalse(SchedulingWatchdog.allows(db2))
|
||||
XCTAssertTrue(SchedulingWatchdog.current!.allows(db1))
|
||||
XCTAssertFalse(SchedulingWatchdog.current!.allows(db3))
|
||||
XCTAssertFalse(SchedulingWatchdog.current!.allows(db2))
|
||||
}
|
||||
XCTAssertFalse(SchedulingWatchdog.allows(db1))
|
||||
XCTAssertFalse(SchedulingWatchdog.allows(db2))
|
||||
XCTAssertFalse(SchedulingWatchdog.allows(db3))
|
||||
XCTAssertNil(SchedulingWatchdog.current)
|
||||
}
|
||||
|
||||
func testDatabaseQueueFromDatabaseQueue() throws {
|
||||
|
||||
Reference in new issue
Block a user