From 638e586dbcdbc60c9f2af605f2cedc5a8d1efba9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 17 Sep 2022 14:46:55 +0200 Subject: [PATCH] Expose Database.registerAccess(to:) This helps tools that intend to declare an observed region without directly accessing it. This will be necessary for (future) snapshot-based observations that postpone actual database access. --- GRDB/Core/Database+Statements.swift | 4 +- GRDB/Core/Database.swift | 75 +++++++++++++++----- GRDB/ValueObservation/ValueObservation.swift | 39 +++++++++- 3 files changed, 97 insertions(+), 21 deletions(-) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 25993284b..6a8d52f01 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -431,9 +431,7 @@ extension Database { try checkForSuspensionViolation(from: statement) // Record the database region selected by the statement execution. - if isRecordingSelectedRegion { - selectedRegion.formUnion(statement.databaseRegion) - } + try registerAccess(to: statement.databaseRegion) // Database observation: prepare transaction observers. observationBroker?.statementWillExecute(statement) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index cd053a86b..013d682f8 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -64,11 +64,12 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_ /// - ``TransactionCompletion`` /// - ``TransactionKind`` /// -/// ### Observing Database Transactions +/// ### Database Observation /// /// - ``add(transactionObserver:extent:)`` /// - ``afterNextTransaction(onCommit:onRollback:)`` /// - ``remove(transactionObserver:)`` +/// - ``registerAccess(to:)`` /// /// ### Collations /// @@ -259,9 +260,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib } /// Whether the database region selected by statement execution is - /// recorded into `selectedRegion`. + /// recorded into `selectedRegion` by `track(_:)`. /// - /// To record the selected region, use `recordingSelection(_:_:)`. + /// To start recording the selected region, use `recordingSelection(_:_:)`. private(set) var isRecordingSelectedRegion = false /// The database region selected by statement execution, when @@ -686,27 +687,67 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib readOnlyDepth > 0 || configuration.readonly } - // MARK: - Recording of the selected region + // MARK: - Database Observation - /// Extends the `region` argument with the database region selected by all - /// statements executed by the closure. + /// Reports the region to ``ValueObservation``. /// /// For example: /// - /// var region = DatabaseRegion() - /// try db.recordingSelection(®ion) { - /// let players = try Player.fetchAll(db) - /// let team = try Team.fetchOne(db, id: 42) - /// } - /// print(region) // player(*),team(*)[42] + /// ```swift + /// let observation = ValueObservation.tracking { db in + /// // All changes to the 'player' and 'team' tables + /// // will trigger the observation. + /// try db.registerAccess(to: Table("player")) + /// try db.registerAccess(to: Table("team")) + /// } + /// ``` + /// + /// See ``ValueObservation/trackingConstantRegion(_:)`` for some examples + /// of such explicit region tracking. + /// + /// This method only has an effect if and only if the ``ValueObservation`` + /// is inferring the observed region from the database access. In the + /// example below, the observation explicitly tracks the `player` table + /// only. All calls to the `registerAccess` method are ignored: + /// + /// ```swift + /// // Observes the 'player' table only + /// let observation = ValueObservation.tracking(region: Table("player")) { db in + /// // Ignored + /// try db.registerAccess(to: Table("team")) + /// } + /// ``` + public func registerAccess(to region: @autoclosure () -> some DatabaseRegionConvertible) throws { + if isRecordingSelectedRegion { + try selectedRegion.formUnion(region().databaseRegion(self)) + } + } + + /// Extends the `region` argument with the database region selected by all + /// statements executed by the closure, and all regions explicitly tracked + /// with the ``registerAccess(to:)`` method. + /// + /// For example: + /// + /// ```swift + /// var region = DatabaseRegion() + /// try db.recordingSelection(®ion) { + /// let players = try Player.fetchAll(db) + /// let team = try Team.fetchOne(db, id: 42) + /// try db.registerAccess(to: Table("awards")) + /// } + /// print(region) // awards,player(*),team(*)[42] + /// ``` /// /// This method is used by ``ValueObservation``: /// - /// let playersObservation = ValueObservation.tracking { db in - /// // Here all fetches are recorded, so that we know what is the - /// // database region that must be observed. - /// try Player.fetchAll(db) - /// } + /// ```swift + /// let playersObservation = ValueObservation.tracking { db in + /// // Here all fetches are recorded, so that we know what is the + /// // database region that must be observed. + /// try Player.fetchAll(db) + /// } + /// ``` func recordingSelection(_ region: inout DatabaseRegion, _ block: () throws -> T) rethrows -> T { if region.isFullDatabase { return try block() diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 13dac99cc..31208226a 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -31,7 +31,7 @@ import Foundation /// - ``tracking(region:fetch:)`` /// - ``tracking(regions:fetch:)`` /// -/// ### Creating A Shared Observation +/// ### Creating a Shared Observation /// /// - ``shared(in:scheduling:extent:)`` /// - ``SharedValueObservationExtent`` @@ -693,6 +693,43 @@ extension ValueObservation where Reducer == ValueReducers.Auto { /// } /// ``` /// + /// You can turn them into optimized observations of a constant region with + /// the ``Database/registerAccess(to:)`` method: + /// + /// ```swift + /// let observation = ValueObservation.trackingConstantRegion { db -> Player? in + /// // Track all players so that the observed region does not depend on + /// // the rowid of the favorite player. + /// try db.registerAccess(to: Player.all()) + /// + /// let pref = try Preference.fetchOne(db) ?? .default + /// return try Player.fetchOne(db, id: pref.favoritePlayerId) + /// } + /// + /// let observation = ValueObservation.trackingConstantRegion { db -> [User] in + /// // Track all players so that the observed region does not change + /// // even if there is no favorite player at all. + /// try db.registerAccess(to: Player.all()) + /// + /// let pref = try Preference.fetchOne(db) ?? .default + /// let playerIds: [Int64] = pref.favoritePlayerIds // may be empty + /// return try Player.fetchAll(db, ids: playerIds) + /// } + /// + /// let observation = ValueObservation.trackingConstantRegion { db -> Int in + /// // Track foods and beverages so that the observed region does not + /// // depend on preferences. + /// try db.registerAccess(to: Food.all()) + /// try db.registerAccess(to: Beverage.all()) + /// + /// let pref = try Preference.fetchOne(db) ?? .default + /// switch pref.selection { + /// case .food: return try Food.fetchCount(db) + /// case .beverage: return try Beverage.fetchCount(db) + /// } + /// } + /// ``` + /// /// - parameter fetch: The closure that fetches the observed value. public static func trackingConstantRegion( _ fetch: @escaping (Database) throws -> Value)