From e934c428b4bf796855d38d0392156a38d16ffdc9 Mon Sep 17 00:00:00 2001 From: Simon Binder Date: Tue, 5 May 2026 22:05:07 +0200 Subject: [PATCH 1/3] Add `observe(statement:)` to `TransactionObserver` --- GRDB/Core/TransactionObserver.swift | 135 ++++++++++-------- ...sactionObserverObserveStatementTests.swift | 60 ++++++++ 2 files changed, 138 insertions(+), 57 deletions(-) create mode 100644 Tests/GRDBTests/TransactionObserverObserveStatementTests.swift diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 80289983e..da033b840 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -334,65 +334,14 @@ class DatabaseObservationBroker { SchedulingWatchdog.current!.databaseObservationBroker = self // Fill statementObservations with observations that are interested - // in the kind of database events performed by the statement, as - // reported by `sqlite3_set_authorizer`. - // + // in the kind of database events performed by the statement. // Those statementObservations will be notified of individual changes // in databaseWillChange() and databaseDidChange(). - let authorizerEventKinds = statement.authorizerEventKinds - - switch authorizerEventKinds.count { - case 0: - // Statement has no effect on any database table. - // - // For example: PRAGMA foreign_keys = ON - statementObservations = [] - case 1: - // We'll execute a simple statement without any side effect. - // Eventual database events will thus all have the same kind. All - // detabase events can be notified to interested observations. - // - // For example, if one observes all deletions in the table T, then - // all individual deletions of DELETE FROM T are notified: - let eventKind = authorizerEventKinds[0] - statementObservations = transactionObservations.compactMap { observation in - guard observation.observes(eventsOfKind: eventKind) else { - // observation is not interested - return nil - } - - // Observation will be notified of all individual events - return StatementObservation( - transactionObservation: observation, - trackingEvents: .all) - } - default: - // We'll execute a complex statement with side effects performed by - // an SQL trigger or a foreign key action. Eventual database events - // may not all have the same kind: we need to filter them before - // notifying interested observations. - // - // For example, if DELETE FROM T1 generates deletions in T1 and T2 - // by the mean of a foreign key action, then when one only observes - // deletions in T1, one must not be notified of deletions in T2: - statementObservations = transactionObservations.compactMap { observation in - let observedEventKinds = authorizerEventKinds.filter(observation.observes) - if observedEventKinds.isEmpty { - // observation is not interested - return nil - } - - // Observation will only be notified of individual events - // it is interested into. - return StatementObservation( - transactionObservation: observation, - trackingEvents: .matching( - observedEventKinds: observedEventKinds, - authorizerEventKinds: authorizerEventKinds)) - } + statementObservations = transactionObservations.compactMap { observation in + observation.observations(for: statement) } } - + transactionCompletion = .none } @@ -805,8 +754,8 @@ public protocol TransactionObserver: AnyObject { /// Returns whether specific kinds of database changes should be notified /// to the observer. /// - /// When this method returns false, database events of this kind are not - /// notified to the ``databaseDidChange(with:)`` method. + /// When this method and ``observes(statement:)`` return false, database + /// events are not notified to the ``databaseDidChange(with:)`` method. /// /// For example: /// @@ -825,6 +774,14 @@ public protocol TransactionObserver: AnyObject { /// from being applied on the observed tables. func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool + /// Returns whether statements made by the statement should be notified to the observer. + /// + /// This method can be used to observe indirect writes from statements (e.g. a statement invoking + /// a custom SQL function which internally runs its own statements). ``observes(eventsOfKind:)`` + /// would not be called for such statements because potential writes can't be inferred from the syntax of + /// these statements. + func observes(statement: Statement) -> Bool + /// Called when the database was modified in some unspecified way. /// /// This method allows a transaction observer to handle changes that are @@ -902,6 +859,11 @@ public protocol TransactionObserver: AnyObject { } extension TransactionObserver { + /// The default implementation does not observe statements. + public func observes(statement: Statement) -> Bool { + return false + } + /// The default implementation does nothing. public func databaseWillCommit() throws { } @@ -999,6 +961,65 @@ final class TransactionObservation { observer?.observes(eventsOfKind: eventKind) ?? false } + func observations(for statement: Statement) -> StatementObservation? { + guard let observer else { + return nil + } + + if observer.observes(statement: statement) { + return StatementObservation( + transactionObservation: self, + trackingEvents: .all) + } + + let authorizerEventKinds = statement.authorizerEventKinds + + switch authorizerEventKinds.count { + case 0: + // Statement has no effect on any database table. + // + // For example: PRAGMA foreign_keys = ON + return nil + case 1: + // We'll execute a simple statement without any side effect. + // Eventual database events will thus all have the same kind. All + // detabase events can be notified to interested observations. + // + // For example, if one observes all deletions in the table T, then + // all individual deletions of DELETE FROM T are notified: + guard observer.observes(eventsOfKind: authorizerEventKinds[0]) else { + // observation is not interested + return nil + } + + // Observation will be notified of all individual events + return StatementObservation( + transactionObservation: self, + trackingEvents: .all) + default: + // We'll execute a complex statement with side effects performed by + // an SQL trigger or a foreign key action. Eventual database events + // may not all have the same kind: we need to filter them before + // notifying interested observations. + // + // For example, if DELETE FROM T1 generates deletions in T1 and T2 + // by the mean of a foreign key action, then when one only observes + // deletions in T1, one must not be notified of deletions in T2: + let observedEventKinds = authorizerEventKinds.filter(observer.observes) + if observedEventKinds.isEmpty { + // observation is not interested + return nil + } + // Observation will only be notified of individual events + // it is interested into. + return StatementObservation( + transactionObservation: self, + trackingEvents: .matching( + observedEventKinds: observedEventKinds, + authorizerEventKinds: authorizerEventKinds)) + } + } + #if SQLITE_ENABLE_PREUPDATE_HOOK func databaseWillChange(with event: DatabasePreUpdateEvent) { guard isEnabled else { return } diff --git a/Tests/GRDBTests/TransactionObserverObserveStatementTests.swift b/Tests/GRDBTests/TransactionObserverObserveStatementTests.swift new file mode 100644 index 000000000..b764ce82a --- /dev/null +++ b/Tests/GRDBTests/TransactionObserverObserveStatementTests.swift @@ -0,0 +1,60 @@ +import XCTest +import GRDB +import SQLite3 + +private class EverythingObserver: TransactionObserver { + var changedTables = Set() + + func databaseDidChange(with event: GRDB.DatabaseEvent) { + changedTables.insert(event.tableName) + } + + func observes(eventsOfKind eventKind: GRDB.DatabaseEventKind) -> Bool { + return true + } + + func observes(statement: Statement) -> Bool { + return true + } + + func databaseDidCommit(_ db: GRDB.Database) {} + + func databaseDidRollback(_ db: GRDB.Database) {} +} + +private struct SendablePtr: @unchecked Sendable { + let ptr: OpaquePointer +} + +class TransactionObserverObserveStatementTests: GRDBTestCase { + func testIndirectWrite() throws { + var config = Configuration() + config.prepareDatabase{ database in + // Replicate what a native SQLite extension might do, running statements in a user-defined functions + let ptr = SendablePtr(ptr: database.sqliteConnection!) + + database.add(function: DatabaseFunction("custom_clear_function", function: { values in + var err: UnsafeMutablePointer? + let rc = sqlite3_exec(ptr.ptr, "DELETE FROM foo", nil, nil, &err) + if rc != 0 { + let msg = String(cString: err!) + fatalError(msg) + } + return rc + })) + } + let db = try makeDatabaseQueue(configuration: config) + try db.writeWithoutTransaction { db in + try db.execute(sql: "CREATE TABLE foo (bar TEXT)") + try db.execute(sql: "INSERT INTO foo DEFAULT VALUES") + } + + let observer = EverythingObserver() + db.add(transactionObserver: observer) + try db.writeWithoutTransaction { db in + try db.execute(sql: "SELECT custom_clear_function()") + } + + XCTAssert(observer.changedTables == ["foo"]) + } +} From 253cdfec8c6fe985229e9debb70697e011fda3ea Mon Sep 17 00:00:00 2001 From: Simon Binder Date: Mon, 11 May 2026 20:47:20 +0200 Subject: [PATCH 2/3] Review feedback --- GRDB/Core/TransactionObserver.swift | 17 +++++++----- .../Extension/DatabaseRegionObservation.md | 2 +- .../Extension/TransactionObserver.md | 5 +++- .../Extension/ValueObservation.md | 2 +- ...actionObserverObserveEverythingTest.swift} | 26 +++++++++++++++---- 5 files changed, 38 insertions(+), 14 deletions(-) rename Tests/GRDBTests/{TransactionObserverObserveStatementTests.swift => TransactionObserverObserveEverythingTest.swift} (67%) diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index da033b840..3bd438075 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -774,13 +774,14 @@ public protocol TransactionObserver: AnyObject { /// from being applied on the observed tables. func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool - /// Returns whether statements made by the statement should be notified to the observer. + /// Returns whether this observer should unconditionally be notified for all database changes, regardless of + /// ``observes(eventsOfKind:)``. /// /// This method can be used to observe indirect writes from statements (e.g. a statement invoking /// a custom SQL function which internally runs its own statements). ``observes(eventsOfKind:)`` /// would not be called for such statements because potential writes can't be inferred from the syntax of /// these statements. - func observes(statement: Statement) -> Bool + var observesAllDatabaseChanges: Bool { get } /// Called when the database was modified in some unspecified way. /// @@ -860,8 +861,8 @@ public protocol TransactionObserver: AnyObject { extension TransactionObserver { /// The default implementation does not observe statements. - public func observes(statement: Statement) -> Bool { - return false + public var observesAllDatabaseChanges: Bool { + false } /// The default implementation does nothing. @@ -958,7 +959,11 @@ final class TransactionObservation { } func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - observer?.observes(eventsOfKind: eventKind) ?? false + guard let observer else { + return false + } + return observer.observesAllDatabaseChanges || observer + .observes(eventsOfKind: eventKind) } func observations(for statement: Statement) -> StatementObservation? { @@ -966,7 +971,7 @@ final class TransactionObservation { return nil } - if observer.observes(statement: statement) { + if observer.observesAllDatabaseChanges { return StatementObservation( transactionObservation: self, trackingEvents: .all) diff --git a/GRDB/Documentation.docc/Extension/DatabaseRegionObservation.md b/GRDB/Documentation.docc/Extension/DatabaseRegionObservation.md index 172cc169b..947018909 100644 --- a/GRDB/Documentation.docc/Extension/DatabaseRegionObservation.md +++ b/GRDB/Documentation.docc/Extension/DatabaseRegionObservation.md @@ -79,7 +79,7 @@ let observation = DatabaseRegionObservation( `DatabaseRegionObservation` will not notify impactful transactions whenever the database is modified in an undetectable way: - Changes performed by external database connections. -- Changes performed by SQLite statements that are not compiled and executed by GRDB. +- Changes performed by SQLite statements that are not compiled and executed by GRDB, including statements ran from a custom SQL function that is itself invoked with GRDB APIs. - Changes to the database schema, changes to internal system tables such as `sqlite_master`. - Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables. diff --git a/GRDB/Documentation.docc/Extension/TransactionObserver.md b/GRDB/Documentation.docc/Extension/TransactionObserver.md index 72acd5e51..02128fa74 100644 --- a/GRDB/Documentation.docc/Extension/TransactionObserver.md +++ b/GRDB/Documentation.docc/Extension/TransactionObserver.md @@ -125,6 +125,9 @@ class PlayerObserver: TransactionObserver { When the `observes(eventsOfKind:)` method returns false for all event kinds, the observer is still notified of transactions. +In addition to ``observes(eventsOfKind:)``, transaction observers can implement the `observesAllDatabaseChanges` getter. When set to `true`, the observer will +observe all changes to the database. + ## Observation Extent **You can specify how long an observer is notified of database changes and transactions.** @@ -232,7 +235,7 @@ The changes and transactions that are not automatically notified to transaction - Read-only transactions. - Changes and transactions performed by external database connections. -- Changes performed by SQLite statements that are not both compiled and executed through GRDB APIs. +- Changes performed by SQLite statements that are not both compiled and executed through GRDB APIs, including statements ran from a custom SQL function that is itself invoked with GRDB APIs. - Changes to the database schema, changes to internal system tables such as `sqlite_master`. - Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables. - The deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite). diff --git a/GRDB/Documentation.docc/Extension/ValueObservation.md b/GRDB/Documentation.docc/Extension/ValueObservation.md index a1d192e23..9d4fa6a38 100644 --- a/GRDB/Documentation.docc/Extension/ValueObservation.md +++ b/GRDB/Documentation.docc/Extension/ValueObservation.md @@ -228,7 +228,7 @@ This ``tracking(region:_:fetch:)`` method lets you entirely separate the **obser `ValueObservation` will not fetch and notify a fresh value whenever the database is modified in an undetectable way: - Changes performed by external database connections. -- Changes performed by SQLite statements that are not compiled and executed by GRDB. +- Changes performed by SQLite statements that are not compiled and executed by GRDB, including statements ran from a custom SQL function that is itself invoked with GRDB APIs. - Changes to the database schema, changes to internal system tables such as `sqlite_master`. - Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables. diff --git a/Tests/GRDBTests/TransactionObserverObserveStatementTests.swift b/Tests/GRDBTests/TransactionObserverObserveEverythingTest.swift similarity index 67% rename from Tests/GRDBTests/TransactionObserverObserveStatementTests.swift rename to Tests/GRDBTests/TransactionObserverObserveEverythingTest.swift index b764ce82a..f5b3f7932 100644 --- a/Tests/GRDBTests/TransactionObserverObserveStatementTests.swift +++ b/Tests/GRDBTests/TransactionObserverObserveEverythingTest.swift @@ -9,12 +9,12 @@ private class EverythingObserver: TransactionObserver { changedTables.insert(event.tableName) } - func observes(eventsOfKind eventKind: GRDB.DatabaseEventKind) -> Bool { - return true + var observesAllDatabaseChanges: Bool { + true } - func observes(statement: Statement) -> Bool { - return true + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { + fatalError("Should not be called since observesAllDatbaaseChanges is true") } func databaseDidCommit(_ db: GRDB.Database) {} @@ -26,7 +26,7 @@ private struct SendablePtr: @unchecked Sendable { let ptr: OpaquePointer } -class TransactionObserverObserveStatementTests: GRDBTestCase { +class TransactionObserverObserveEverythingTests: GRDBTestCase { func testIndirectWrite() throws { var config = Configuration() config.prepareDatabase{ database in @@ -57,4 +57,20 @@ class TransactionObserverObserveStatementTests: GRDBTestCase { XCTAssert(observer.changedTables == ["foo"]) } + + func testDisablesTruncateOptimization() throws { + let db = try makeDatabaseQueue() + try db.writeWithoutTransaction { db in + try db.execute(sql: "CREATE TABLE foo (bar TEXT)") + try db.execute(sql: "INSERT INTO foo DEFAULT VALUES") + } + + let observer = EverythingObserver() + db.add(transactionObserver: observer) + try db.writeWithoutTransaction { db in + try db.execute(sql: "DELETE FROM foo") + } + + XCTAssert(observer.changedTables == ["foo"]) + } } From 27c7bda0e9c020468616abe5fc5da98900e74404 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 31 May 2026 13:50:11 +0200 Subject: [PATCH 3/3] Refactor with DatabaseEventObservationStrategy The issue with `observesAllDatabaseChanges` is that this was a misleading name: transaction observers are not notified of changes that are performed in a save point that is eventually rollbacked. By exposing the DatabaseEventObservationStrategy type, we allow for a future extra flag that ignores save points, trading observation precision for a reduced memory footprint. --- GRDB/Core/TransactionObserver.swift | 109 ++++++++++++++---- .../Extension/DatabaseRegionObservation.md | 2 +- .../Extension/TransactionObserver.md | 9 +- .../Extension/ValueObservation.md | 2 +- ...atabaseEventObservationStrategyTest.swift} | 14 ++- 5 files changed, 102 insertions(+), 34 deletions(-) rename Tests/GRDBTests/{TransactionObserverObserveEverythingTest.swift => DatabaseEventObservationStrategyTest.swift} (86%) diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 3bd438075..aa3cb8f85 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -297,6 +297,10 @@ class DatabaseObservationBroker { } } + /// Notifies that some changes were performed in the provided + /// database region. + /// + /// Support for the public ``Database/notifyChanges(in:)`` method. func notifyChanges(withEventsOfKind eventKinds: [DatabaseEventKind]) throws { // Support for stopObservingDatabaseChangesUntilNextTransaction() SchedulingWatchdog.current!.databaseObservationBroker = self @@ -338,7 +342,7 @@ class DatabaseObservationBroker { // Those statementObservations will be notified of individual changes // in databaseWillChange() and databaseDidChange(). statementObservations = transactionObservations.compactMap { observation in - observation.observations(for: statement) + observation.statementObservation(for: statement) } } @@ -747,16 +751,78 @@ class DatabaseObservationBroker { } } +// MARK: - DatabaseEventObservationStrategy + +/// Controls which database changes are notified to a `TransactionObserver`. +public struct DatabaseEventObservationStrategy: Sendable { + /// A boolean value indicating whether a ``TransactionObserver`` focuses + /// on database changes filtered by its + /// ``TransactionObserver/observes(eventsOfKind:)`` method. + /// + /// When this flag is true (the default), the only notified changes are + /// those performed by `DELETE`, `INSERT` and `UPDATE` statements that + /// are compiled and executed by GRDB. Other changes are not: changes + /// performed by `SELECT` statements (through a database function), + /// changes performed by statements compiled or executed with the SQLite + /// C API. + /// + /// Set this flag to false in order to be notified of all database events. + /// + /// When this flag is false, an observer prevents the + /// [truncate optimization](https://www.sqlite.org/lang_delete.html#the_truncate_optimization) + /// from being applied on all database tables. + public var requiresDatabaseEventKind: Bool + + /// The default strategy for observing database change events. + /// + /// In this default strategy, only the `DELETE`, `INSERT` and `UPDATE` + /// statements that are compiled and executed by GRDB are observed. + public static let `default` = DatabaseEventObservationStrategy(requiresDatabaseEventKind: true) +} + // MARK: - TransactionObserver public protocol TransactionObserver: AnyObject { + /// Controls which database changes should be notified to the observer. + /// + /// The default value is ``DatabaseEventObservationStrategy/default``, + /// which only detects changes performed by `DELETE`, `INSERT` and + /// `UPDATE` statements that are compiled and executed by GRDB. + /// + /// You can define a universal observer that observes changes performed + /// by `SELECT` statements (through a database function), changes + /// performed by statements compiled or executed with the SQLite C API, + /// as below: + /// + /// ```swift + /// // An observer that observes all database changes. + /// class UniversalObserver: TransactionObserver { + /// var databaseEventObservationStrategy: DatabaseEventObservationStrategy { + /// var strategy = DatabaseEventObservationStrategy.default + /// // Don't filter on database event kind, so that we are + /// // notified of changes performed through the SQLite C API: + /// strategy.requiresDatabaseEventKind = false + /// return strategy + /// } + /// + /// // You still have to provide an implementation for this method, + /// // but it will never be called since `requiresDatabaseEventKind` + /// // is false. + /// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { + /// false // ignored + /// } + /// + /// func databaseDidChange(with event: DatabaseEvent) { + /// // Handle the change + /// } + /// } + /// ``` + var databaseEventObservationStrategy: DatabaseEventObservationStrategy { get } + /// Returns whether specific kinds of database changes should be notified /// to the observer. /// - /// When this method and ``observes(statement:)`` return false, database - /// events are not notified to the ``databaseDidChange(with:)`` method. - /// /// For example: /// /// ```swift @@ -772,16 +838,12 @@ public protocol TransactionObserver: AnyObject { /// prevents the /// [truncate optimization](https://www.sqlite.org/lang_delete.html#the_truncate_optimization) /// from being applied on the observed tables. - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool - - /// Returns whether this observer should unconditionally be notified for all database changes, regardless of - /// ``observes(eventsOfKind:)``. /// - /// This method can be used to observe indirect writes from statements (e.g. a statement invoking - /// a custom SQL function which internally runs its own statements). ``observes(eventsOfKind:)`` - /// would not be called for such statements because potential writes can't be inferred from the syntax of - /// these statements. - var observesAllDatabaseChanges: Bool { get } + /// - Note: This method is not called when the result of + /// ``databaseEventObservationStrategy`` has the + /// ``DatabaseEventObservationStrategy/requiresDatabaseEventKind`` + /// flag set to false. + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool /// Called when the database was modified in some unspecified way. /// @@ -796,8 +858,12 @@ public protocol TransactionObserver: AnyObject { /// Called when the database is changed by an insert, update, or /// delete event. /// - /// The change is pending until the current transaction ends. See - /// ``databaseWillCommit()-7mksu``, ``databaseDidCommit(_:)`` and + /// Whether this method is called or not for any given change is + /// controlled by ``databaseEventObservationStrategy`` and + /// ``observes(eventsOfKind:)``. + /// + /// The notified change is pending until the current transaction ends. + /// See ``databaseWillCommit()-7mksu``, ``databaseDidCommit(_:)`` and /// ``databaseDidRollback(_:)``. /// /// The observer has an opportunity to stop receiving further change events @@ -861,10 +927,10 @@ public protocol TransactionObserver: AnyObject { extension TransactionObserver { /// The default implementation does not observe statements. - public var observesAllDatabaseChanges: Bool { - false + public var databaseEventObservationStrategy: DatabaseEventObservationStrategy { + .default } - + /// The default implementation does nothing. public func databaseWillCommit() throws { } @@ -962,16 +1028,15 @@ final class TransactionObservation { guard let observer else { return false } - return observer.observesAllDatabaseChanges || observer - .observes(eventsOfKind: eventKind) + return !observer.databaseEventObservationStrategy.requiresDatabaseEventKind || observer.observes(eventsOfKind: eventKind) } - func observations(for statement: Statement) -> StatementObservation? { + func statementObservation(for statement: Statement) -> StatementObservation? { guard let observer else { return nil } - if observer.observesAllDatabaseChanges { + if !observer.databaseEventObservationStrategy.requiresDatabaseEventKind { return StatementObservation( transactionObservation: self, trackingEvents: .all) diff --git a/GRDB/Documentation.docc/Extension/DatabaseRegionObservation.md b/GRDB/Documentation.docc/Extension/DatabaseRegionObservation.md index 947018909..83a366e8d 100644 --- a/GRDB/Documentation.docc/Extension/DatabaseRegionObservation.md +++ b/GRDB/Documentation.docc/Extension/DatabaseRegionObservation.md @@ -79,7 +79,7 @@ let observation = DatabaseRegionObservation( `DatabaseRegionObservation` will not notify impactful transactions whenever the database is modified in an undetectable way: - Changes performed by external database connections. -- Changes performed by SQLite statements that are not compiled and executed by GRDB, including statements ran from a custom SQL function that is itself invoked with GRDB APIs. +- Changes performed by SQLite statements that are not a `DELETE`, `INSERT` or `UPDATE` statement compiled and executed by GRDB. - Changes to the database schema, changes to internal system tables such as `sqlite_master`. - Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables. diff --git a/GRDB/Documentation.docc/Extension/TransactionObserver.md b/GRDB/Documentation.docc/Extension/TransactionObserver.md index 02128fa74..7b54c93e5 100644 --- a/GRDB/Documentation.docc/Extension/TransactionObserver.md +++ b/GRDB/Documentation.docc/Extension/TransactionObserver.md @@ -97,7 +97,7 @@ do { **Transaction observers can choose the database changes they are interested in.** -The ``observes(eventsOfKind:)`` method filters events that are notified to ``databaseDidChange(with:)``. It is the most efficient and recommended change filtering technique, because it is only called once before a database query is executed, and can completely disable change tracking: +By default, the ``observes(eventsOfKind:)`` method filters events that are notified to ``databaseDidChange(with:)``. It is the most efficient and recommended change filtering technique, because it is only called once before a database query is executed, and can completely disable change tracking: ```swift // Calls `observes(eventsOfKind:)` once. @@ -125,8 +125,7 @@ class PlayerObserver: TransactionObserver { When the `observes(eventsOfKind:)` method returns false for all event kinds, the observer is still notified of transactions. -In addition to ``observes(eventsOfKind:)``, transaction observers can implement the `observesAllDatabaseChanges` getter. When set to `true`, the observer will -observe all changes to the database. +The filtering performed by ``observes(eventsOfKind:)`` makes a transaction observer unaware of changes performed by SQLite statements that are not a `DELETE`, `INSERT` or `UPDATE` statement compiled and executed by GRDB. You can lift this limitation with the ``TransactionObserver/databaseEventObservationStrategy``. ## Observation Extent @@ -235,7 +234,7 @@ The changes and transactions that are not automatically notified to transaction - Read-only transactions. - Changes and transactions performed by external database connections. -- Changes performed by SQLite statements that are not both compiled and executed through GRDB APIs, including statements ran from a custom SQL function that is itself invoked with GRDB APIs. +- Changes performed by SQLite statements that are not a `DELETE`, `INSERT` or `UPDATE` statement compiled and executed by GRDB (this limitation can be lifted, in your custom `TransactionObserver` type, with ``TransactionObserver/databaseEventObservationStrategy``). - Changes to the database schema, changes to internal system tables such as `sqlite_master`. - Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables. - The deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite). @@ -268,8 +267,10 @@ try dbQueue.write { db in ### Filtering Database Changes +- ``databaseEventObservationStrategy`` - ``observes(eventsOfKind:)`` - ``DatabaseEventKind`` +- ``DatabaseEventObservationStrategy`` ### Handling Database Changes diff --git a/GRDB/Documentation.docc/Extension/ValueObservation.md b/GRDB/Documentation.docc/Extension/ValueObservation.md index 9d4fa6a38..aacbb8bc2 100644 --- a/GRDB/Documentation.docc/Extension/ValueObservation.md +++ b/GRDB/Documentation.docc/Extension/ValueObservation.md @@ -228,7 +228,7 @@ This ``tracking(region:_:fetch:)`` method lets you entirely separate the **obser `ValueObservation` will not fetch and notify a fresh value whenever the database is modified in an undetectable way: - Changes performed by external database connections. -- Changes performed by SQLite statements that are not compiled and executed by GRDB, including statements ran from a custom SQL function that is itself invoked with GRDB APIs. +- Changes performed by SQLite statements that are not a `DELETE`, `INSERT` or `UPDATE` statement compiled and executed by GRDB. - Changes to the database schema, changes to internal system tables such as `sqlite_master`. - Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables. diff --git a/Tests/GRDBTests/TransactionObserverObserveEverythingTest.swift b/Tests/GRDBTests/DatabaseEventObservationStrategyTest.swift similarity index 86% rename from Tests/GRDBTests/TransactionObserverObserveEverythingTest.swift rename to Tests/GRDBTests/DatabaseEventObservationStrategyTest.swift index f5b3f7932..df871f460 100644 --- a/Tests/GRDBTests/TransactionObserverObserveEverythingTest.swift +++ b/Tests/GRDBTests/DatabaseEventObservationStrategyTest.swift @@ -5,16 +5,18 @@ import SQLite3 private class EverythingObserver: TransactionObserver { var changedTables = Set() + var databaseEventObservationStrategy: DatabaseEventObservationStrategy { + var strategy = DatabaseEventObservationStrategy.default + strategy.requiresDatabaseEventKind = false + return strategy + } + func databaseDidChange(with event: GRDB.DatabaseEvent) { changedTables.insert(event.tableName) } - var observesAllDatabaseChanges: Bool { - true - } - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - fatalError("Should not be called since observesAllDatbaaseChanges is true") + fatalError("Should not be called since requiresDatabaseEventKind is false") } func databaseDidCommit(_ db: GRDB.Database) {} @@ -26,7 +28,7 @@ private struct SendablePtr: @unchecked Sendable { let ptr: OpaquePointer } -class TransactionObserverObserveEverythingTests: GRDBTestCase { +class DatabaseEventObservationStrategyTest: GRDBTestCase { func testIndirectWrite() throws { var config = Configuration() config.prepareDatabase{ database in