From 06bf3980b6cf5999d36192666fa7e2ef9585dd2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 1 Dec 2021 19:42:22 +0100 Subject: [PATCH 01/13] Fix documentation links --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0189635df..78f12c55b 100644 --- a/README.md +++ b/README.md @@ -6669,7 +6669,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan A request knows which database modifications can impact its results. It can communicate this information to [transaction observers](#transactionobserver-protocol) by the way of a DatabaseRegion. -DatabaseRegion fuels, for example, [ValueObservation and DatabaseRegionObservation]. +DatabaseRegion fuels, for example, [ValueObservation] and [DatabaseRegionObservation]. **A region notifies *potential* changes, not *actual* changes in the results of a request.** A change is notified if and only if a statement has actually modified the tracked tables and columns by inserting, updating, or deleting a row. From bb2ce74125fcde21542243971a20fa292f7faa15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 2 Dec 2021 08:08:20 +0100 Subject: [PATCH 02/13] Add helper method Database.isolated(readOnly:) --- GRDB/Core/Database.swift | 15 +++++++++++++++ GRDB/Core/DatabasePool.swift | 9 ++------- GRDB/Core/DatabaseQueue.swift | 22 +++++----------------- 3 files changed, 22 insertions(+), 24 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index f8f6bc47f..1b47e7e90 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1008,6 +1008,21 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib } } + /// Runs the block with an isolation level equal or greater than + /// snapshot isolation. + func isolated(readOnly: Bool = false, _ block: () throws -> T) throws -> T { + var result: T? + try inSavepoint { + if readOnly { + result = try self.readOnly(block) + } else { + result = try block() + } + return .commit + } + return result! + } + /// Executes a block inside a savepoint. /// /// try dbQueue.inDatabase do { diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index acc7c09de..25ffd5528 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -310,15 +310,10 @@ extension DatabasePool: DatabaseReader { } return try readerPool.get { reader in try reader.sync { db in - var result: T? = nil - // The block isolation comes from the DEFERRED transaction. - // See DatabasePoolTests.testReadMethodIsolationOfBlock(). - try db.inTransaction(.deferred) { + try db.isolated { try db.clearSchemaCacheIfNeeded() - result = try value(db) - return .commit + return try value(db) } - return result! } } } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index a763b67cf..ea34bcb65 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -180,14 +180,9 @@ extension DatabaseQueue { public func read(_ value: (Database) throws -> T) throws -> T { try writer.sync { db in - // The transaction guarantees snapshot isolation against eventual - // external connection. - var result: T? - try db.inTransaction(.deferred) { - result = try db.readOnly { try value(db) } - return .commit + try db.isolated(readOnly: true) { + try value(db) } - return result! } } @@ -249,18 +244,11 @@ extension DatabaseQueue { // DatabaseQueue can't perform parallel reads. // Perform a blocking read instead. return DatabaseFuture(Result { - // Check that we're on the writer queue... + // Check that we're on the writer queue, as documented try writer.execute { db in - // ... and that no transaction is opened. - GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.") - // The transaction guarantees snapshot isolation against eventual - // external connection. - var result: T? - try db.inTransaction(.deferred) { - result = try db.readOnly { try value(db) } - return .commit + try db.isolated(readOnly: true) { + try value(db) } - return result! } }) } From e69092ca6a86ea5edd529546ce562e3da8073a29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 1 Dec 2021 19:36:40 +0100 Subject: [PATCH 03/13] Add DatabaseRegionConvertible to Table --- GRDB/QueryInterface/SQL/Table.swift | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index adce66876..03f8fa45c 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -33,6 +33,12 @@ extension Table where RowDecoder == Row { } } +extension Table: DatabaseRegionConvertible { + public func databaseRegion(_ db: Database) throws -> DatabaseRegion { + DatabaseRegion(table: tableName) + } +} + // MARK: Request Derivation extension Table { From ad66fbc6663717471b2f7885cf9d988f4617eacd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 2 Dec 2021 08:08:50 +0100 Subject: [PATCH 04/13] ValueObserver documentation --- GRDB/ValueObservation/ValueObserver.swift | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index f93bbb72d..1124204b4 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -23,6 +23,11 @@ final class ValueObserver { private let reduceQueue: DispatchQueue private var isChanged = false private let onChange: (Reducer.Value) -> Void + + // This lock protects `_isCompleted`. + // It also protects `reducer` because of what is likely a compiler bug: + // - + // - private var lock = NSRecursiveLock() // protects _isCompleted and reducer init( From 6240585a030bc6ad8fe506e4e48ea0d222c4377f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 2 Dec 2021 09:23:12 +0100 Subject: [PATCH 05/13] Make sure ValueObservation fetches in an isolated transaction Previously, ValueObservation could fetch in a non-isolated way. When an external connection would commit changes, we could fetch inconsistent values. Here we make sure ValueObservation always fetch in an isolated way. --- GRDB/Core/DatabaseReader.swift | 6 +++++- GRDB/ValueObservation/ValueObservation.swift | 2 +- GRDB/ValueObservation/ValueObserver.swift | 18 ++++++++++++----- .../ValueObservation/ValueReducer/Fetch.swift | 3 ++- .../ValueReducer/ValueReducer.swift | 20 ++----------------- 5 files changed, 23 insertions(+), 26 deletions(-) diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index be083967c..e31b7cb7a 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -393,7 +393,11 @@ extension DatabaseReader { { if scheduler.immediateInitialValue() { do { - let value = try unsafeReentrantRead(observation.fetchValue) + let value = try unsafeReentrantRead { db in + try db.isolated(readOnly: true) { + try observation.fetchValue(db) + } + } onChange(value) } catch { observation.events.didFail?(error) diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index fe2e5339f..b99fe5843 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -212,7 +212,7 @@ extension ValueObservation: Refinable { /// Returns the value. func fetchValue(_ db: Database) throws -> Reducer.Value { var reducer = makeReducer() - guard let value = try reducer.fetchAndReduce(db, requiringWriteAccess: requiresWriteAccess) else { + guard let value = try reducer.fetchAndReduce(db) else { fatalError("Contract broken: reducer has no initial value") } return value diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index 1124204b4..b79218a69 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -99,15 +99,21 @@ extension ValueObserver: TransactionObserver { // Synchronously fetchedFuture = DatabaseFuture(Result { try recordingSelectedRegionIfNeeded(db) { - try synchronized { - try reducer.fetch(db, requiringWriteAccess: requiresWriteAccess) + try db.isolated(readOnly: !requiresWriteAccess) { + try synchronized { + try reducer._fetch(db) + } } } }) } else { // Concurrently guard let writer = writer else { return } - fetchedFuture = writer.concurrentRead { db in try self.synchronized { try self.reducer._fetch(db) } } + fetchedFuture = writer.concurrentRead { db in + try self.synchronized { + try self.reducer._fetch(db) + } + } } // 2. Reduce @@ -151,8 +157,10 @@ extension ValueObserver { /// Fetch an observed value, and moves the reducer forward. func fetchValue(_ db: Database) throws -> Reducer.Value? { try recordingSelectedRegionIfNeeded(db) { - try synchronized { - try reducer.fetchAndReduce(db, requiringWriteAccess: requiresWriteAccess) + try db.isolated(readOnly: !requiresWriteAccess) { + try synchronized { + try reducer.fetchAndReduce(db) + } } } } diff --git a/GRDB/ValueObservation/ValueReducer/Fetch.swift b/GRDB/ValueObservation/ValueReducer/Fetch.swift index 4fdcc04e7..c93325f71 100644 --- a/GRDB/ValueObservation/ValueReducer/Fetch.swift +++ b/GRDB/ValueObservation/ValueReducer/Fetch.swift @@ -25,7 +25,8 @@ extension ValueReducers { /// :nodoc: public func _fetch(_ db: Database) throws -> Value { - try __fetch(db) + assert(db.isInsideTransaction, "Fetching in a non-isolated way is illegal") + return try __fetch(db) } /// :nodoc: diff --git a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift index 868b9960d..69e3ccdc4 100644 --- a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift +++ b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift @@ -37,24 +37,8 @@ public protocol _ValueReducer { public protocol ValueReducer: _ValueReducer { } extension ValueReducer { - func fetch(_ db: Database, requiringWriteAccess: Bool) throws -> Fetched { - if requiringWriteAccess { - var fetchedValue: Fetched? - try db.inSavepoint { - fetchedValue = try _fetch(db) - return .commit - } - return fetchedValue! - } else { - return try db.readOnly { - try _fetch(db) - } - } - } - - mutating func fetchAndReduce(_ db: Database, requiringWriteAccess: Bool) throws -> Value? { - let fetchedValue = try fetch(db, requiringWriteAccess: requiringWriteAccess) - return _value(fetchedValue) + mutating func fetchAndReduce(_ db: Database) throws -> Value? { + try _value(_fetch(db)) } } From 36fba9a79a5562a6840a6e5f78d53d1dd50e8819 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 2 Dec 2021 17:20:30 +0100 Subject: [PATCH 06/13] TODO: deprecate DatabaseRegion(table:) We have `Table` now, wich is DatabaseRegionConvertible. This deprecation will revert https://github.com/groue/GRDB.swift/pull/510 --- GRDB/Core/DatabaseRegion.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index e05f14409..9f9601beb 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -60,6 +60,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { self.init(tableRegions: [:]) } + // TODO: @available(*, deprecated, message: "In order to specify a table region, prefer `Table(tableName)`") /// Creates a region that spans all rows and columns of a database table. /// /// - parameter table: A table name. From 85747935c87c2d96f10624870e07c5ca934695d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 1 Dec 2021 19:42:51 +0100 Subject: [PATCH 07/13] ValueObservation can track an explicit database region --- GRDB/Fixit/GRDB-5.0.swift | 4 +- GRDB/ValueObservation/ValueObservation.swift | 94 +++++++++- GRDB/ValueObservation/ValueObserver.swift | 142 ++++++++++----- .../ValueObservation/ValueReducer/Fetch.swift | 20 +- GRDB/ValueObservation/ValueReducer/Map.swift | 2 +- .../ValueReducer/RemoveDuplicates.swift | 2 +- .../ValueObservation/ValueReducer/Trace.swift | 2 +- .../ValueReducer/ValueReducer.swift | 39 +++- Tests/GRDBTests/GRDBTestCase.swift | 2 +- Tests/GRDBTests/ValueObservationTests.swift | 171 ++++++++++++++++++ 10 files changed, 402 insertions(+), 76 deletions(-) diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index 3e51a7177..0d7da5410 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -21,7 +21,7 @@ extension AnyFetchRequest { @available(*, unavailable, message: "Custom reducers are no longer supported. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") public struct AnyValueReducer: ValueReducer { - public var _isSelectedRegionDeterministic: Bool + public var _trackingMode: _ValueReducerTrackingMode { preconditionFailure() } public init(fetch: @escaping (Database) throws -> Fetched, value: @escaping (Fetched) -> Value?) @@ -559,7 +559,7 @@ extension ValueObservation where Reducer.Value: Equatable { extension ValueReducers { @available(*, unavailable) public enum Unavailable: ValueReducer { - public var _isSelectedRegionDeterministic: Bool + public var _trackingMode: _ValueReducerTrackingMode { preconditionFailure() } public func _fetch(_ db: Database) throws -> Never diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index b99fe5843..477c25c24 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -496,7 +496,97 @@ extension ValueObservation where Reducer == ValueReducers.Auto { _ fetch: @escaping (Database) throws -> Value) -> ValueObservation> { - .init(makeReducer: { .init(isSelectedRegionDeterministic: true, fetch: fetch) }) + .init(makeReducer: { ValueReducers.Fetch(trackingMode: .constantRegionRecordedFromSelection, fetch: fetch) }) + } + + /// Creates a `ValueObservation` that notifies the values returned by the + /// `fetch` function whenever a database transaction has an impact on the + /// given regions. + /// + /// The tracked region *is not* automatically inferred from the requests + /// performed in the `fetch` function. + /// + /// For example: + /// + /// // Tracks the full database + /// let observation = ValueObservation.tracking + /// region: .fullDatabase, + /// fetch: { db in ... }) + /// + /// // Tracks the full 'player' table + /// let observation = ValueObservation.tracking + /// region: Player.all(), + /// fetch: { db in ... }) + /// + /// // Tracks the row with id 42 in the 'player' table + /// let observation = ValueObservation.tracking + /// region: Player.filter(id: 42), + /// fetch: { db in ... }) + /// + /// // Tracks the 'score' column in the 'player' table + /// let observation = ValueObservation.tracking + /// region: Player.select(max(Column("score")), + /// fetch: { db in ... }) + /// + /// // Tracks both the 'player' and 'team' tables + /// let observation = ValueObservation.tracking + /// region: Player.all(), Team.all(), + /// fetch: { db in ... }) + /// + /// - parameter region: A list of observed regions. + /// - parameter fetch: A function that fetches the observed value from + /// the database. + public static func tracking( + region: DatabaseRegionConvertible..., + fetch: @escaping (Database) throws -> Value) + -> ValueObservation> + { + tracking(regions: region, fetch: fetch) + } + + /// Creates a `ValueObservation` that notifies the values returned by the + /// `fetch` function whenever a database transaction has an impact on the + /// given regions. + /// + /// The tracked region *is not* automatically inferred from the requests + /// performed in the `fetch` function. + /// + /// For example: + /// + /// // Tracks the full database + /// let observation = ValueObservation.tracking + /// regions: [.fullDatabase], + /// fetch: { db in ... }) + /// + /// // Tracks the full 'player' table + /// let observation = ValueObservation.tracking + /// regions: [Player.all()], + /// fetch: { db in ... }) + /// + /// // Tracks the row with id 42 in the 'player' table + /// let observation = ValueObservation.tracking + /// regions: [Player.filter(id: 42)], + /// fetch: { db in ... }) + /// + /// // Tracks the 'score' column in the 'player' table + /// let observation = ValueObservation.tracking + /// regions: [Player.select(max(Column("score"))], + /// fetch: { db in ... }) + /// + /// // Tracks both the 'player' and 'team' tables + /// let observation = ValueObservation.tracking + /// regions: [Player.all(), Team.all()], + /// fetch: { db in ... }) + /// + /// - parameter regions: A list of observed regions. + /// - parameter fetch: A function that fetches the observed value from + /// the database. + public static func tracking( + regions: [DatabaseRegionConvertible], + fetch: @escaping (Database) throws -> Value) + -> ValueObservation> + { + .init(makeReducer: { ValueReducers.Fetch(trackingMode: .constantRegion(regions), fetch: fetch) }) } /// Creates a `ValueObservation` that notifies the values returned by the @@ -521,7 +611,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto { _ fetch: @escaping (Database) throws -> Value) -> ValueObservation> { - .init(makeReducer: { .init(isSelectedRegionDeterministic: false, fetch: fetch) }) + .init(makeReducer: { ValueReducers.Fetch(trackingMode: .nonConstantRegionRecordedFromSelection, fetch: fetch) }) } /// Creates a `ValueObservation` that notifies the values returned by the diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index b79218a69..f21f787e2 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -5,6 +5,7 @@ import Foundation final class ValueObserver { var isCompleted: Bool { synchronized { _isCompleted } } let events: ValueObservationEvents + let trackingMode: _ValueReducerTrackingMode private var observedRegion: DatabaseRegion? { didSet { if let willTrackRegion = events.willTrackRegion, @@ -46,6 +47,7 @@ final class ValueObserver { self.scheduler = scheduler self.reduceQueue = reduceQueue self.onChange = onChange + self.trackingMode = reducer._trackingMode } convenience init( @@ -86,53 +88,19 @@ extension ValueObserver: TransactionObserver { } } - func databaseDidCommit(_ db: Database) { + func databaseDidCommit(_ writerDB: Database) { guard isChanged else { return } isChanged = false if isCompleted { return } events.databaseDidChange?() - // 1. Fetch - let fetchedFuture: DatabaseFuture - if requiresWriteAccess || needsRecordingSelectedRegion { - // Synchronously - fetchedFuture = DatabaseFuture(Result { - try recordingSelectedRegionIfNeeded(db) { - try db.isolated(readOnly: !requiresWriteAccess) { - try synchronized { - try reducer._fetch(db) - } - } - } - }) - } else { - // Concurrently - guard let writer = writer else { return } - fetchedFuture = writer.concurrentRead { db in - try self.synchronized { - try self.reducer._fetch(db) - } - } + guard let future = fetchFuture(writerDB) else { + // Database connection closed: give up + return } - // 2. Reduce - // - // Wait for the future fetched value in reduceQueue. This guarantees: - // - that notifications have the same ordering as transactions. - // - that expensive reduce operations are computed without blocking - // any database dispatch queue. - reduceQueue.async { - if self.isCompleted { return } - do { - let fetchedValue = try fetchedFuture.wait() - if let value = self.synchronized({ self.reducer._value(fetchedValue) }) { - self.notifyChange(value) - } - } catch { - self.notifyErrorAndComplete(error) - } - } + reduce(future: future) } func databaseDidRollback(_ db: Database) { @@ -156,8 +124,8 @@ extension ValueObserver { /// Fetch an observed value, and moves the reducer forward. func fetchValue(_ db: Database) throws -> Reducer.Value? { - try recordingSelectedRegionIfNeeded(db) { - try db.isolated(readOnly: !requiresWriteAccess) { + try db.isolated(readOnly: !requiresWriteAccess) { + try updatingObserverRegionIfNeeded(db) { try synchronized { try reducer.fetchAndReduce(db) } @@ -209,25 +177,103 @@ extension ValueObserver { // MARK: - Private extension ValueObserver { + /// Returns nil if the database was closed + private func fetchFuture(_ writerDB: Database) -> DatabaseFuture? { + if requiresWriteAccess { + // We obviously need to fetch from the writer connection + return fetchFutureSync(writerDB) + } + + switch trackingMode { + case .nonConstantRegionRecordedFromSelection: + // When the tracked region is not constant, we must fetch from the + // writer connection so that we do not miss future changes that + // would modify the tracked region. + return fetchFutureSync(writerDB) + + case .constantRegion, .constantRegionRecordedFromSelection: + // When the tracked region is constant, we can fetch concurrently. + return fetchFutureConcurrent(writerDB) + } + } + + private func fetchFutureSync(_ writerDB: Database) -> DatabaseFuture { + DatabaseFuture(Result { + try writerDB.isolated(readOnly: !requiresWriteAccess) { + try fetchUpdatingObserverRegionIfNeeded(writerDB) + } + }) + } + + /// Returns nil if the database was closed + private func fetchFutureConcurrent(_ writerDB: Database) -> DatabaseFuture? { + guard let writer = writer else { + // Database connection closed: give up + return nil + } + return writer.concurrentRead { readerDB in + try self.fetchUpdatingObserverRegionIfNeeded(readerDB) + } + } + + private func fetchUpdatingObserverRegionIfNeeded(_ db: Database) throws -> Reducer.Fetched { + try updatingObserverRegionIfNeeded(db) { + let reducer = synchronized { self.reducer } + return try reducer._fetch(db) + } + } + + private func reduce(future: DatabaseFuture) { + // Wait for the future fetched value in reduceQueue. This guarantees: + // - that notifications have the same ordering as transactions. + // - that expensive reduce operations are computed without blocking + // any database dispatch queue. + reduceQueue.async { + if self.isCompleted { return } + do { + let fetchedValue = try future.wait() + if let value = self.synchronized({ self.reducer._value(fetchedValue) }) { + self.notifyChange(value) + } + } catch { + self.notifyErrorAndComplete(error) + } + } + } + private func synchronized(_ execute: () throws -> T) rethrows -> T { lock.lock() defer { lock.unlock() } return try execute() } - private var needsRecordingSelectedRegion: Bool { - observedRegion == nil || synchronized { !reducer._isSelectedRegionDeterministic } - } - - private func recordingSelectedRegionIfNeeded( + private func updatingObserverRegionIfNeeded( _ db: Database, fetch: () throws -> T) throws -> T { - guard needsRecordingSelectedRegion else { + switch trackingMode { + case let .constantRegion(regions): + if observedRegion == nil { + observedRegion = try DatabaseRegion.union(regions)(db) + } return try fetch() + case .constantRegionRecordedFromSelection: + if observedRegion == nil { + return try recordingSelectedRegion(db, fetch: fetch) + } else { + return try fetch() + } + case .nonConstantRegionRecordedFromSelection: + return try recordingSelectedRegion(db, fetch: fetch) } - + } + + private func recordingSelectedRegion( + _ db: Database, + fetch: () throws -> T) + throws -> T + { var region = DatabaseRegion() let result = try db.recordingSelection(®ion, fetch) observedRegion = try region.observableRegion(db) diff --git a/GRDB/ValueObservation/ValueReducer/Fetch.swift b/GRDB/ValueObservation/ValueReducer/Fetch.swift index c93325f71..4c7474129 100644 --- a/GRDB/ValueObservation/ValueReducer/Fetch.swift +++ b/GRDB/ValueObservation/ValueReducer/Fetch.swift @@ -3,23 +3,11 @@ extension ValueReducers { public struct Fetch: ValueReducer { private let __fetch: (Database) throws -> Value /// :nodoc: - public let _isSelectedRegionDeterministic: Bool + public let _trackingMode: _ValueReducerTrackingMode - /// Creates a reducer, which passes raw fetched values through. - /// - /// - parameter isSelectedRegionDeterministic: When true, the fetching - /// function is assumed to always fetch from the same database region. - /// This information is used by ValueObserver, which can optimize the - /// observation by computing the observed region only once, and - /// performing concurrent fetches of fresh values. - /// - /// When false, the ValueObserver always fetches fresh values from the - /// writer dispatch queue, and updates its observed region on - /// each fetch. - /// - /// - parameter fetch: A function that fetches the observed value. - init(isSelectedRegionDeterministic: Bool, fetch: @escaping (Database) throws -> Value) { - self._isSelectedRegionDeterministic = isSelectedRegionDeterministic + /// Creates a reducer which passes raw fetched values through. + init(trackingMode: _ValueReducerTrackingMode, fetch: @escaping (Database) throws -> Value) { + self._trackingMode = trackingMode self.__fetch = fetch } diff --git a/GRDB/ValueObservation/ValueReducer/Map.swift b/GRDB/ValueObservation/ValueReducer/Map.swift index 43fa98828..31942cf01 100644 --- a/GRDB/ValueObservation/ValueReducer/Map.swift +++ b/GRDB/ValueObservation/ValueReducer/Map.swift @@ -18,7 +18,7 @@ extension ValueReducers { private var base: Base private let transform: (Base.Value) -> Value /// :nodoc: - public var _isSelectedRegionDeterministic: Bool { base._isSelectedRegionDeterministic } + public var _trackingMode: _ValueReducerTrackingMode { base._trackingMode } init(_ base: Base, _ transform: @escaping (Base.Value) -> Value) { self.base = base diff --git a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift index 10dbb04a9..f9420a674 100644 --- a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift +++ b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift @@ -14,7 +14,7 @@ extension ValueReducers { private var base: Base private var previousValue: Base.Value? /// :nodoc: - public var _isSelectedRegionDeterministic: Bool { base._isSelectedRegionDeterministic } + public var _trackingMode: _ValueReducerTrackingMode { base._trackingMode } init(_ base: Base) { self.base = base diff --git a/GRDB/ValueObservation/ValueReducer/Trace.swift b/GRDB/ValueObservation/ValueReducer/Trace.swift index 8b2a2310b..9d1a6dc79 100644 --- a/GRDB/ValueObservation/ValueReducer/Trace.swift +++ b/GRDB/ValueObservation/ValueReducer/Trace.swift @@ -5,7 +5,7 @@ extension ValueReducers { let willFetch: () -> Void let didReceiveValue: (Base.Value) -> Void /// :nodoc: - public var _isSelectedRegionDeterministic: Bool { base._isSelectedRegionDeterministic } + public var _trackingMode: _ValueReducerTrackingMode { base._trackingMode } /// :nodoc: public func _fetch(_ db: Database) throws -> Base.Fetched { diff --git a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift index 69e3ccdc4..ddf5ee4ca 100644 --- a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift +++ b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift @@ -8,9 +8,8 @@ public protocol _ValueReducer { /// The type of observed values associatedtype Value - /// Returns whether the database region selected by the `fetch(_:)` method - /// is constant. - var _isSelectedRegionDeterministic: Bool { get } + /// The tracked region + var _trackingMode: _ValueReducerTrackingMode { get } /// Fetches database values upon changes in an observed database region. /// @@ -33,6 +32,38 @@ public protocol _ValueReducer { mutating func _value(_ fetched: Fetched) -> Value? } +/// Implementation details of `ValueReducer`. +/// +/// :nodoc: +public enum _ValueReducerTrackingMode { + /// The tracked region is constant and explicit. + /// + /// Use case: + /// + /// // Tracked Region is always the full player table + /// ValueObservation.trackingConstantRegion(Player.all()) { db in ... } + case constantRegion([DatabaseRegionConvertible]) + + /// The tracked region is constant and inferred from the fetched values. + /// + /// Use case: + /// + /// // Tracked Region is always the full player table + /// ValueObservation.trackingConstantRegion { db in Player.fetchAll(db) } + case constantRegionRecordedFromSelection + + /// The tracked region is not constant, and inferred from the fetched values. + /// + /// Use case: + /// + /// // Tracked Region is the one row of the table, and it changes on + /// // each fetch. + /// ValueObservation.tracking { db in + /// try Player.fetchOne(db, id: Int.random(in: 1.1000)) + /// } + case nonConstantRegionRecordedFromSelection +} + /// The `ValueReducer` protocol supports `ValueObservation`. public protocol ValueReducer: _ValueReducer { } @@ -51,7 +82,7 @@ public enum ValueReducers { /// :nodoc: public enum Auto: ValueReducer { /// :nodoc: - public var _isSelectedRegionDeterministic: Bool { preconditionFailure() } + public var _trackingMode: _ValueReducerTrackingMode { preconditionFailure() } /// :nodoc: public func _fetch(_ db: Database) throws -> Never { preconditionFailure() } /// :nodoc: diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 56dcebe8a..6a10b831a 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -242,7 +242,7 @@ public struct AnyValueReducer: ValueReducer { private var __fetch: (Database) throws -> Fetched private var __value: (Fetched) -> Value? - public var _isSelectedRegionDeterministic: Bool { false } + public var _trackingMode: _ValueReducerTrackingMode { .nonConstantRegionRecordedFromSelection } public init( fetch: @escaping (Database) throws -> Fetched, diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index 6e7cd95ec..cbb15ba38 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -141,6 +141,177 @@ class ValueObservationTests: GRDBTestCase { } } + // MARK: - Constant Explicit Region + + func testTrackingExplicitRegion() throws { + class TestStream: TextOutputStream { + @LockedBox var strings: [String] = [] + func write(_ string: String) { + strings.append(string) + } + } + + // Test behavior with DatabaseQueue, DatabasePool, etc + do { + try assertValueObservation( + ValueObservation + .tracking(region: .fullDatabase, fetch: Table("t").fetchCount), + records: [0, 1, 1, 2, 3, 4], + setup: { db in + try db.execute(sql: """ + CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT); + """) + }, + recordedUpdates: { db in + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + try db.execute(sql: "UPDATE t SET id = id") + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + try db.inTransaction { + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + try db.execute(sql: "DELETE FROM t WHERE id = 1") + return .commit + } + try db.execute(sql: "INSERT INTO t DEFAULT VALUES") + }) + } + + // Track only table "t" + do { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(sql: """ + CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT); + CREATE TABLE other(id INTEGER PRIMARY KEY AUTOINCREMENT); + """) + } + + let logger = TestStream() + let observation = ValueObservation.tracking( + region: Table("t"), + fetch: Table("t").fetchCount) + .print(to: logger) + + let expectation = self.expectation(description: "") + expectation.expectedFulfillmentCount = 2 + let cancellable = observation.start( + in: dbQueue, + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { _ in + expectation.fulfill() + }) + try withExtendedLifetime(cancellable) { + try dbQueue.writeWithoutTransaction { db in + try db.execute(sql: """ + INSERT INTO other DEFAULT VALUES; + INSERT INTO t DEFAULT VALUES; + """) + } + wait(for: [expectation], timeout: 4) + XCTAssertEqual(logger.strings, [ + "start", + "tracked region: t(*)", + "fetch", + "value: 0", + "database did change", + "fetch", + "value: 1", + ]) + } + } + + // Track only table "other" + do { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(sql: """ + CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT); + CREATE TABLE other(id INTEGER PRIMARY KEY AUTOINCREMENT); + """) + } + + let logger = TestStream() + let observation = ValueObservation.tracking( + region: Table("other"), + fetch: Table("t").fetchCount) + .print(to: logger) + + let expectation = self.expectation(description: "") + expectation.expectedFulfillmentCount = 2 + let cancellable = observation.start( + in: dbQueue, + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { _ in + expectation.fulfill() + }) + try withExtendedLifetime(cancellable) { + try dbQueue.writeWithoutTransaction { db in + try db.execute(sql: """ + INSERT INTO other DEFAULT VALUES; + INSERT INTO t DEFAULT VALUES; + """) + } + wait(for: [expectation], timeout: 4) + XCTAssertEqual(logger.strings, [ + "start", + "tracked region: other(*)", + "fetch", + "value: 0", + "database did change", + "fetch", + "value: 0", + ]) + } + } + + // Track both "t" and "other" + do { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.execute(sql: """ + CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT); + CREATE TABLE other(id INTEGER PRIMARY KEY AUTOINCREMENT); + """) + } + + let logger = TestStream() + let observation = ValueObservation.tracking( + region: Table("t"), Table("other"), + fetch: Table("t").fetchCount) + .print(to: logger) + + let expectation = self.expectation(description: "") + expectation.expectedFulfillmentCount = 3 + let cancellable = observation.start( + in: dbQueue, + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { _ in + expectation.fulfill() + }) + try withExtendedLifetime(cancellable) { + try dbQueue.writeWithoutTransaction { db in + try db.execute(sql: """ + INSERT INTO other DEFAULT VALUES; + INSERT INTO t DEFAULT VALUES; + """) + } + wait(for: [expectation], timeout: 4) + XCTAssertEqual(logger.strings, [ + "start", + "tracked region: other(*),t(*)", + "fetch", + "value: 0", + "database did change", + "fetch", + "value: 0", + "database did change", + "fetch", + "value: 1", + ]) + } + } + } + // MARK: - Snapshot Optimization func testDisallowedSnapshotOptimizationWithAsyncScheduler() throws { From 6180e4b81516994423626c73c16f19e7e655f714 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 2 Dec 2021 10:12:23 +0100 Subject: [PATCH 08/13] Fix for Swift 5.3 --- Tests/GRDBTests/ValueObservationTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index cbb15ba38..faf30c2fe 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -155,7 +155,7 @@ class ValueObservationTests: GRDBTestCase { do { try assertValueObservation( ValueObservation - .tracking(region: .fullDatabase, fetch: Table("t").fetchCount), + .tracking(region: DatabaseRegion.fullDatabase, fetch: Table("t").fetchCount), records: [0, 1, 1, 2, 3, 4], setup: { db in try db.execute(sql: """ From 06eb45db658be4f32231e07726b904f8a80019b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 2 Dec 2021 15:59:01 +0100 Subject: [PATCH 09/13] Documentation for ValueObservation(region:fetch:) --- README.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/README.md b/README.md index 78f12c55b..cd3c6a859 100644 --- a/README.md +++ b/README.md @@ -5807,6 +5807,7 @@ Tracked changes are insertions, updates, and deletions that impact the tracked v - [ValueObservation Scheduling](#valueobservation-scheduling) - [ValueObservation Operators](#valueobservation-operators): [map](#valueobservationmap), [removeDuplicates](#valueobservationremoveduplicates), ... - [ValueObservation Sharing](#valueobservation-sharing) +- [Specifying the Region Tracked by ValueObservation](#specifying-the-region-tracked-by-valueobservation) - [ValueObservation Performance](#valueobservation-performance) - :blue_book: [Combine Publisher](Documentation/Combine.md#database-observation) @@ -6225,6 +6226,23 @@ let sharedObservation = ValueObservation > - Unlike `ValueObservation`, `SharedValueObservation` retains the database connection. As long as there exists a `SharedValueObservation` instance, or an active suscription to a shared observation, the database connection won't be deinitialized. +### Specifying the Region Tracked by ValueObservation + +While the standard `ValueObservation.tracking { db in ... }` method lets you track changes to a fetched value and receive any changes to it, sometimes your use case might require more granular control. + +Consider a scenario where you'd like to get a specific Player's row, but only when their `score` column changes. You can use `tracking(region:fetch:)` to do just that: + +```swift +let observation = ValueObservation.tracking( + // Define what database region constitutes a "change" + region: Player.select(Column("score")).filter(id: 1), + // Define what to fetch upon such change + fetch: { db in try Player.fetchOne(db, id: 1) } +) +``` + +This overload of `ValueObservation` lets you entirely separate the **observed region** from the **fetched value** itself, providing utmost flexibility. See [DatabaseRegionConvertible] for more information. + ### ValueObservation Performance This chapter further describes runtime aspects of ValueObservation, and provides some optimization tips for demanding applications. @@ -6690,6 +6708,23 @@ protocol DatabaseRegionConvertible { All [requests](#requests) adopt this protocol, and this allows them to be observed with [DatabaseRegionObservation] and [ValueObservation]. +For example: + +```swift +// An observation triggered by all changes to the database +DatabaseRegionObservation(tracking: .fullDatabase) + +// An observation triggered by all changes to the player table +DatabaseRegionObservation(tracking: Table("player")) + +// An observation triggered by all changes to the row with rowid 1 in the player table +DatabaseRegionObservation(tracking: Player.filter(id: 1)) + +// An observation triggered by all changes to the score column of the player table +DatabaseRegionObservation(tracking: SQLRequest("SELECT score FROM player")) +``` + +Note that specifying a region as a request _does not run the request_. In the above example, `Player.filter(id: 1)` and `SELECT score FROM player` are never executed. They are only _compiled_ by SQLite, so that GRDB understands the tables, rows, and columns that constitute the database region. ### Support for SQLite Pre-Update Hooks From e419bb55cadec37bd053c8c2dc6fa66b285f9c66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 2 Dec 2021 16:34:04 +0100 Subject: [PATCH 10/13] Enhance documentation of DatabaseRegion --- README.md | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index cd3c6a859..cb5b5c671 100644 --- a/README.md +++ b/README.md @@ -6683,17 +6683,22 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan ### DatabaseRegion -**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.14/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**. +A `DatabaseRegion` is a reunion of database tables, and combination of columns and rows (identified by their rowid): -A request knows which database modifications can impact its results. It can communicate this information to [transaction observers](#transactionobserver-protocol) by the way of a DatabaseRegion. + |Table1 | |Table2 | |Table3 | |Table4 | |Table5 | + |-------| |-------| |-------| |-------| |-------| + |x|x|x|x| |x| | | | |x|x|x|x| |x|x| |x| | | | | | + |x|x|x|x| |x| | | | | | | | | | | | | | | |x| | | + |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | | + |x|x|x|x| |x| | | | | | | | | | | | | | | | | | | -DatabaseRegion fuels, for example, [ValueObservation] and [DatabaseRegionObservation]. +DatabaseRegion helps [ValueObservation] and [DatabaseRegionObservation] track changes in the database through the [TransactionObserver](#transactionobserver-protocol) protocol. -**A region notifies *potential* changes, not *actual* changes in the results of a request.** A change is notified if and only if a statement has actually modified the tracked tables and columns by inserting, updating, or deleting a row. +**Note that observing a database region spots *potential* changes, not *actual* changes in the results of a request.** A change is notified if and only if a statement has actually modified the tracked tables and columns by inserting, updating, or deleting a row. For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table. -For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.14/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). +For more details, see the [reference](https://groue.github.io/GRDB.swift/docs/5.14/Structs/DatabaseRegion.html). #### The DatabaseRegionConvertible Protocol From 76d2168988a9489774f141508477c3f6382b706e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 2 Dec 2021 16:48:02 +0100 Subject: [PATCH 11/13] Extend the general description of ValueObservation behavior Link to the ability to track something which is not the fetched region. --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index cb5b5c671..bc7fcc9a8 100644 --- a/README.md +++ b/README.md @@ -5935,6 +5935,8 @@ See the companion library [RxGRDB] for more information. **Generally speaking**: - ValueObservation notifies an initial value before the eventual changes. +- ValueObservation only notifies changes committed to disk. +- By default, ValueObservation notifies a fresh value whenever any of its component is modified (any fetched column, row, etc.). This can be [configured](#specifying-the-region-tracked-by-valueobservation). - By default, ValueObservation notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously. This can be [configured](#valueobservation-scheduling). - ValueObservation may coalesce subsequent changes into a single notification. - ValueObservation may notify consecutive identical values. You can filter out the undesired duplicates with the [removeDuplicates()](#valueobservationremoveduplicates) method. @@ -5943,7 +5945,7 @@ See the companion library [RxGRDB] for more information. - An error occurs. - The database connection is closed. -Take care that there are use cases that ValueObservation is unfit for. For example, your application may need to process absolutely all changes, and avoid any coalescing. It may also need to process changes before any further modifications are performed in the database file. In those cases, you need to track *individual transactions*, not values. See [DatabaseRegionObservation], and the low-level [TransactionObserver Protocol](#transactionobserver-protocol). +Take care that there are use cases that ValueObservation is unfit for. For example, your application may need to process absolutely all changes, and avoid any coalescing. It may also need to process changes before any further modifications are performed in the database file. In those cases, you need to track *individual transactions*, not values. See [DatabaseRegionObservation]. If you need to process uncommitted changes, see [TransactionObserver](#transactionobserver-protocol). ### ValueObservation Scheduling From 89b178322052281c0658090f3de6a6543d87cc39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 2 Dec 2021 17:18:23 +0100 Subject: [PATCH 12/13] TrackingMode is a property of ValueObservation No reducer changes the tracking mode, so let's simplify the code. --- GRDB/Fixit/GRDB-5.0.swift | 6 -- GRDB/ValueObservation/ValueObservation.swift | 56 ++++++++++++++++--- GRDB/ValueObservation/ValueObserver.swift | 6 +- .../ValueObservation/ValueReducer/Fetch.swift | 5 +- GRDB/ValueObservation/ValueReducer/Map.swift | 2 - .../ValueReducer/RemoveDuplicates.swift | 2 - .../ValueObservation/ValueReducer/Trace.swift | 2 - .../ValueReducer/ValueReducer.swift | 37 ------------ Tests/GRDBTests/GRDBTestCase.swift | 2 - Tests/GRDBTests/ValueObservationTests.swift | 48 ++++++++-------- 10 files changed, 78 insertions(+), 88 deletions(-) diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index 0d7da5410..e8ef6a721 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -21,9 +21,6 @@ extension AnyFetchRequest { @available(*, unavailable, message: "Custom reducers are no longer supported. See the \"Migrating From GRDB 4 to GRDB 5\" guide.") public struct AnyValueReducer: ValueReducer { - public var _trackingMode: _ValueReducerTrackingMode - { preconditionFailure() } - public init(fetch: @escaping (Database) throws -> Fetched, value: @escaping (Fetched) -> Value?) { preconditionFailure() } @@ -559,9 +556,6 @@ extension ValueObservation where Reducer.Value: Equatable { extension ValueReducers { @available(*, unavailable) public enum Unavailable: ValueReducer { - public var _trackingMode: _ValueReducerTrackingMode - { preconditionFailure() } - public func _fetch(_ db: Database) throws -> Never { preconditionFailure() } diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 477c25c24..b3ba5b517 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -22,10 +22,6 @@ import Foundation public struct ValueObservation { var events = ValueObservationEvents() - /// The reducer is created when observation starts, and is triggered upon - /// each database change. - var makeReducer: () -> Reducer - /// Default is false. Set this property to true when the observation /// requires write access in order to fetch fresh values. Fetches are then /// wrapped inside a savepoint. @@ -34,16 +30,52 @@ public struct ValueObservation { /// observation is less efficient than a read-only observation. public var requiresWriteAccess = false + var trackingMode: ValueObservationTrackingMode + + /// The reducer is created when observation starts, and is triggered upon + /// each database change. + var makeReducer: () -> Reducer + /// Returns a ValueObservation with a transformed reducer. func mapReducer(_ transform: @escaping (Reducer) -> R) -> ValueObservation { let makeReducer = self.makeReducer return ValueObservation( events: events, - makeReducer: { transform(makeReducer()) }, - requiresWriteAccess: requiresWriteAccess) + requiresWriteAccess: requiresWriteAccess, + trackingMode: trackingMode, + makeReducer: { transform(makeReducer()) }) } } +enum ValueObservationTrackingMode { + /// The tracked region is constant and explicit. + /// + /// Use case: + /// + /// // Tracked Region is always the full player table + /// ValueObservation.trackingConstantRegion(Player.all()) { db in ... } + case constantRegion([DatabaseRegionConvertible]) + + /// The tracked region is constant and inferred from the fetched values. + /// + /// Use case: + /// + /// // Tracked Region is always the full player table + /// ValueObservation.trackingConstantRegion { db in Player.fetchAll(db) } + case constantRegionRecordedFromSelection + + /// The tracked region is not constant, and inferred from the fetched values. + /// + /// Use case: + /// + /// // Tracked Region is the one row of the table, and it changes on + /// // each fetch. + /// ValueObservation.tracking { db in + /// try Player.fetchOne(db, id: Int.random(in: 1.1000)) + /// } + case nonConstantRegionRecordedFromSelection +} + struct ValueObservationEvents: Refinable { var willStart: (() -> Void)? var willTrackRegion: ((DatabaseRegion) -> Void)? @@ -496,7 +528,9 @@ extension ValueObservation where Reducer == ValueReducers.Auto { _ fetch: @escaping (Database) throws -> Value) -> ValueObservation> { - .init(makeReducer: { ValueReducers.Fetch(trackingMode: .constantRegionRecordedFromSelection, fetch: fetch) }) + .init( + trackingMode: .constantRegionRecordedFromSelection, + makeReducer: { ValueReducers.Fetch(fetch: fetch) }) } /// Creates a `ValueObservation` that notifies the values returned by the @@ -586,7 +620,9 @@ extension ValueObservation where Reducer == ValueReducers.Auto { fetch: @escaping (Database) throws -> Value) -> ValueObservation> { - .init(makeReducer: { ValueReducers.Fetch(trackingMode: .constantRegion(regions), fetch: fetch) }) + .init( + trackingMode: .constantRegion(regions), + makeReducer: { ValueReducers.Fetch(fetch: fetch) }) } /// Creates a `ValueObservation` that notifies the values returned by the @@ -611,7 +647,9 @@ extension ValueObservation where Reducer == ValueReducers.Auto { _ fetch: @escaping (Database) throws -> Value) -> ValueObservation> { - .init(makeReducer: { ValueReducers.Fetch(trackingMode: .nonConstantRegionRecordedFromSelection, fetch: fetch) }) + .init( + trackingMode: .nonConstantRegionRecordedFromSelection, + makeReducer: { ValueReducers.Fetch(fetch: fetch) }) } /// Creates a `ValueObservation` that notifies the values returned by the diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift index f21f787e2..f7e6e2d50 100644 --- a/GRDB/ValueObservation/ValueObserver.swift +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -5,7 +5,7 @@ import Foundation final class ValueObserver { var isCompleted: Bool { synchronized { _isCompleted } } let events: ValueObservationEvents - let trackingMode: _ValueReducerTrackingMode + let trackingMode: ValueObservationTrackingMode private var observedRegion: DatabaseRegion? { didSet { if let willTrackRegion = events.willTrackRegion, @@ -35,6 +35,7 @@ final class ValueObserver { events: ValueObservationEvents, reducer: Reducer, requiresWriteAccess: Bool, + trackingMode: ValueObservationTrackingMode, writer: DatabaseWriter, scheduler: ValueObservationScheduler, reduceQueue: DispatchQueue, @@ -43,11 +44,11 @@ final class ValueObserver { self.events = events self.reducer = reducer self.requiresWriteAccess = requiresWriteAccess + self.trackingMode = trackingMode self.writer = writer self.scheduler = scheduler self.reduceQueue = reduceQueue self.onChange = onChange - self.trackingMode = reducer._trackingMode } convenience init( @@ -61,6 +62,7 @@ final class ValueObserver { events: observation.events, reducer: observation.makeReducer(), requiresWriteAccess: observation.requiresWriteAccess, + trackingMode: observation.trackingMode, writer: writer, scheduler: scheduler, reduceQueue: reduceQueue, diff --git a/GRDB/ValueObservation/ValueReducer/Fetch.swift b/GRDB/ValueObservation/ValueReducer/Fetch.swift index 4c7474129..28e5bc6fc 100644 --- a/GRDB/ValueObservation/ValueReducer/Fetch.swift +++ b/GRDB/ValueObservation/ValueReducer/Fetch.swift @@ -2,12 +2,9 @@ extension ValueReducers { /// A reducer which passes raw fetched values through. public struct Fetch: ValueReducer { private let __fetch: (Database) throws -> Value - /// :nodoc: - public let _trackingMode: _ValueReducerTrackingMode /// Creates a reducer which passes raw fetched values through. - init(trackingMode: _ValueReducerTrackingMode, fetch: @escaping (Database) throws -> Value) { - self._trackingMode = trackingMode + init(fetch: @escaping (Database) throws -> Value) { self.__fetch = fetch } diff --git a/GRDB/ValueObservation/ValueReducer/Map.swift b/GRDB/ValueObservation/ValueReducer/Map.swift index 31942cf01..f980f0349 100644 --- a/GRDB/ValueObservation/ValueReducer/Map.swift +++ b/GRDB/ValueObservation/ValueReducer/Map.swift @@ -17,8 +17,6 @@ extension ValueReducers { public struct Map: ValueReducer { private var base: Base private let transform: (Base.Value) -> Value - /// :nodoc: - public var _trackingMode: _ValueReducerTrackingMode { base._trackingMode } init(_ base: Base, _ transform: @escaping (Base.Value) -> Value) { self.base = base diff --git a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift index f9420a674..7dcab6460 100644 --- a/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift +++ b/GRDB/ValueObservation/ValueReducer/RemoveDuplicates.swift @@ -13,8 +13,6 @@ extension ValueReducers { public struct RemoveDuplicates: ValueReducer where Base.Value: Equatable { private var base: Base private var previousValue: Base.Value? - /// :nodoc: - public var _trackingMode: _ValueReducerTrackingMode { base._trackingMode } init(_ base: Base) { self.base = base diff --git a/GRDB/ValueObservation/ValueReducer/Trace.swift b/GRDB/ValueObservation/ValueReducer/Trace.swift index 9d1a6dc79..239897a3d 100644 --- a/GRDB/ValueObservation/ValueReducer/Trace.swift +++ b/GRDB/ValueObservation/ValueReducer/Trace.swift @@ -4,8 +4,6 @@ extension ValueReducers { var base: Base let willFetch: () -> Void let didReceiveValue: (Base.Value) -> Void - /// :nodoc: - public var _trackingMode: _ValueReducerTrackingMode { base._trackingMode } /// :nodoc: public func _fetch(_ db: Database) throws -> Base.Fetched { diff --git a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift index ddf5ee4ca..d3197de8c 100644 --- a/GRDB/ValueObservation/ValueReducer/ValueReducer.swift +++ b/GRDB/ValueObservation/ValueReducer/ValueReducer.swift @@ -8,9 +8,6 @@ public protocol _ValueReducer { /// The type of observed values associatedtype Value - /// The tracked region - var _trackingMode: _ValueReducerTrackingMode { get } - /// Fetches database values upon changes in an observed database region. /// /// ValueReducer semantics require that this method does not depend on @@ -32,38 +29,6 @@ public protocol _ValueReducer { mutating func _value(_ fetched: Fetched) -> Value? } -/// Implementation details of `ValueReducer`. -/// -/// :nodoc: -public enum _ValueReducerTrackingMode { - /// The tracked region is constant and explicit. - /// - /// Use case: - /// - /// // Tracked Region is always the full player table - /// ValueObservation.trackingConstantRegion(Player.all()) { db in ... } - case constantRegion([DatabaseRegionConvertible]) - - /// The tracked region is constant and inferred from the fetched values. - /// - /// Use case: - /// - /// // Tracked Region is always the full player table - /// ValueObservation.trackingConstantRegion { db in Player.fetchAll(db) } - case constantRegionRecordedFromSelection - - /// The tracked region is not constant, and inferred from the fetched values. - /// - /// Use case: - /// - /// // Tracked Region is the one row of the table, and it changes on - /// // each fetch. - /// ValueObservation.tracking { db in - /// try Player.fetchOne(db, id: Int.random(in: 1.1000)) - /// } - case nonConstantRegionRecordedFromSelection -} - /// The `ValueReducer` protocol supports `ValueObservation`. public protocol ValueReducer: _ValueReducer { } @@ -81,8 +46,6 @@ public enum ValueReducers { // ValueObservation.tracking(_:). /// :nodoc: public enum Auto: ValueReducer { - /// :nodoc: - public var _trackingMode: _ValueReducerTrackingMode { preconditionFailure() } /// :nodoc: public func _fetch(_ db: Database) throws -> Never { preconditionFailure() } /// :nodoc: diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 6a10b831a..1b92338e0 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -242,8 +242,6 @@ public struct AnyValueReducer: ValueReducer { private var __fetch: (Database) throws -> Fetched private var __value: (Fetched) -> Value? - public var _trackingMode: _ValueReducerTrackingMode { .nonConstantRegionRecordedFromSelection } - public init( fetch: @escaping (Database) throws -> Fetched, value: @escaping (Fetched) -> Value?) diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index faf30c2fe..cb0b97cce 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -618,23 +618,25 @@ class ValueObservationTests: GRDBTestCase { var cancellable: DatabaseCancellable? = nil _ = cancellable // Avoid "Variable 'cancellable' was written to, but never read" warning var shouldStopObservation = false - let observation = ValueObservation(makeReducer: { - AnyValueReducer( - fetch: { _ in - if shouldStopObservation { - cancellable = nil /* deallocation */ - } - shouldStopObservation = true - }, - value: { _ in () }) - }) + let observation = ValueObservation( + trackingMode: .nonConstantRegionRecordedFromSelection, + makeReducer: { + AnyValueReducer( + fetch: { _ in + if shouldStopObservation { + cancellable = nil /* deallocation */ + } + shouldStopObservation = true + }, + value: { _ in () }) + }) cancellable = observation.start( in: dbWriter, scheduling: .immediate, onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { _ in notificationExpectation.fulfill() - }) + }) } try dbWriter.write { db in @@ -660,24 +662,26 @@ class ValueObservationTests: GRDBTestCase { var cancellable: DatabaseCancellable? = nil _ = cancellable // Avoid "Variable 'cancellable' was written to, but never read" warning var shouldStopObservation = false - let observation = ValueObservation(makeReducer: { - AnyValueReducer( - fetch: { _ in }, - value: { _ in - if shouldStopObservation { - cancellable = nil /* deallocation right before notification */ - } - shouldStopObservation = true - return () + let observation = ValueObservation( + trackingMode: .nonConstantRegionRecordedFromSelection, + makeReducer: { + AnyValueReducer( + fetch: { _ in }, + value: { _ in + if shouldStopObservation { + cancellable = nil /* deallocation right before notification */ + } + shouldStopObservation = true + return () + }) }) - }) cancellable = observation.start( in: dbWriter, scheduling: .immediate, onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { _ in notificationExpectation.fulfill() - }) + }) } try dbWriter.write { db in From c7291db3607c0037d77415681fe985249cbe6e2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 2 Dec 2021 18:48:36 +0100 Subject: [PATCH 13/13] v5.15.0 --- CHANGELOG.md | 9 +++++++ Documentation/FullTextSearch.md | 4 ++-- Documentation/Migrations.md | 2 +- Documentation/ReleaseProcess.md | 2 +- GRDB.swift.podspec | 2 +- Makefile | 6 ++--- README.md | 42 ++++++++++++++++----------------- Support/Info.plist | 2 +- 8 files changed, 39 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 50d073dd2..70accc30d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 5.x Releases +- `5.15.x` Releases - [5.15.0](#5150) - `5.14.x` Releases - [5.14.0](#5140) - `5.13.x` Releases - [5.13.0](#5130) - `5.12.x` Releases - [5.12.0](#5120) @@ -81,6 +82,14 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## 5.15.0 + +Released December 2, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.14.0...v5.15.0) + +- **Fixed**: `ValueObservation` now always fetches fresh values in an isolated fashion. This prevents all risks of fetching inconsistent data even if an external connection modifies the database. +- **New**: `Table` now conforms to `DatabaseRegionConvertible`. You can write `DatabaseRegionObservation(tracking: Table("player"))`. +- **New**: [#1102](https://github.com/groue/GRDB.swift/pull/1102) by [@groue](https://github.com/groue): Explicit tracked region for ValueObservation + ## 5.14.0 Released November 25, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.13.0...v5.14.0) diff --git a/Documentation/FullTextSearch.md b/Documentation/FullTextSearch.md index 1b6594975..c9cb0481e 100644 --- a/Documentation/FullTextSearch.md +++ b/Documentation/FullTextSearch.md @@ -304,7 +304,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.14/Structs/StatementArguments.html): +FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, @@ -587,7 +587,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.14/Structs/StatementArguments.html): +FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index be8f825a4..e77e563ca 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -77,7 +77,7 @@ try dbQueue.read { db in } ``` -See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.14/Structs/DatabaseMigrator.html) for more migrator methods. +See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.15/Structs/DatabaseMigrator.html) for more migrator methods. ## The `eraseDatabaseOnSchemaChange` Option diff --git a/Documentation/ReleaseProcess.md b/Documentation/ReleaseProcess.md index 8ad41a55e..18a4bcda4 100644 --- a/Documentation/ReleaseProcess.md +++ b/Documentation/ReleaseProcess.md @@ -22,7 +22,7 @@ To release a new GRDB version: - Support/Info.plist - Commit and tag - Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags` -- Push to the master branch +- Push to the master & development branch - `pod trunk push --allow-warnings GRDB.swift.podspec` - `make doc`, and update index.html in the `gh-pages` branch - Update http://github.com/groue/WWDCCompanion diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index fc8811a04..953788528 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '5.14.0' + s.version = '5.15.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/Makefile b/Makefile index 7f569056a..006ecaace 100644 --- a/Makefile +++ b/Makefile @@ -488,10 +488,10 @@ ifdef JAZZY --author 'Gwendal Roué' \ --author_url https://github.com/groue \ --github_url https://github.com/groue/GRDB.swift \ - --github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.14.0 \ - --module-version 5.14.0 \ + --github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.15.0 \ + --module-version 5.15.0 \ --module GRDB \ - --root-url http://groue.github.io/GRDB.swift/docs/5.14/ \ + --root-url http://groue.github.io/GRDB.swift/docs/5.15/ \ --output Documentation/Reference \ --xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS else diff --git a/README.md b/README.md index bc7fcc9a8..e14672a2e 100644 --- a/README.md +++ b/README.md @@ -11,13 +11,13 @@ --- -**Latest release**: November 7, 2021 • [version 5.14.0](https://github.com/groue/GRDB.swift/tree/v5.14.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) +**Latest release**: December 2, 2021 • [version 5.15.0](https://github.com/groue/GRDB.swift/tree/v5.15.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) **Requirements**: iOS 11.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ • SQLite 3.8.5+ • Swift 5.3+ / Xcode 12+ | Swift version | GRDB version | | -------------- | ----------------------------------------------------------- | -| **Swift 5.3+** | **v5.14.0** | +| **Swift 5.3+** | **v5.15.0** | | Swift 5.2 | [v5.12.0](https://github.com/groue/GRDB.swift/tree/v5.12.0) | | Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | | Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | @@ -317,7 +317,7 @@ Documentation #### Reference -- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.14/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) +- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.15/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) #### Getting Started @@ -511,7 +511,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.14/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.15/Structs/Configuration.html) for more details. ## Database Pools @@ -591,7 +591,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.14/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.15/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -651,7 +651,7 @@ try dbQueue.write { db in } ``` -The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.14/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. You can also embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details. @@ -909,7 +909,7 @@ try dbQueue.read { db in let dictionary = try Dictionary(uniqueKeysWithValues: cursor) ``` -- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.14/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: +- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.15/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: ```swift // Prints all Github links @@ -988,7 +988,7 @@ let rows = try Row.fetchAll(db, arguments: ["name": "Arthur"]) ``` -See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.14/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care: @@ -1273,7 +1273,7 @@ GRDB ships with built-in support for the following value types: - Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol. -Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.14/Structs/StatementArguments.html): +Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html): ```swift let url: URL = ... @@ -1720,7 +1720,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction } ``` -Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.14/Structs/Configuration.html) configuration flag: +Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.15/Structs/Configuration.html) configuration flag: ```swift // fatal error: A transaction has been left opened at the end of a database access @@ -1832,7 +1832,7 @@ try dbQueue.write { db in } ``` -The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.14/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). +The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). ```swift insertStatement.arguments = ["name": "Arthur", "score": 1000] @@ -1915,7 +1915,7 @@ See also `Database.execute(sql:)` in the [Executing Updates](#executing-updates) > :point_up: **Note**: it is a programmer error to reuse a prepared statement that has failed: GRDB may crash if you do so. -For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.14/Classes/Statement.html). +For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.15/Classes/Statement.html). ### Prepared Statements Cache @@ -2658,7 +2658,7 @@ try Place.fetchSet(db, sql: "SELECT ...", arguments:...) // Set try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place? ``` -See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.14/Structs/StatementArguments.html) for more information about the query arguments. +See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html) for more information about the query arguments. > :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`. @@ -3098,7 +3098,7 @@ protocol EncodableRecord { } ``` -See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.14/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.14/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies. +See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.15/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.15/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies. ### Date and UUID Coding Strategies @@ -3120,7 +3120,7 @@ protocol EncodableRecord { } ``` -See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.14/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.14/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.14/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. +See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.15/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.15/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.15/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. There is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs and uuid strings, both uppercase and lowercase). @@ -4642,7 +4642,7 @@ Player // SELECT * FROM player ``` -Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.14/Structs/StatementArguments.html): +Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.15/Structs/StatementArguments.html): ```swift // SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) @@ -5410,7 +5410,7 @@ try Player.customRequest().fetchAll(db) // [Player] - The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method. -- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.14/Structs/AnyFetchRequest.html): a type-erased request. +- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.15/Structs/AnyFetchRequest.html): a type-erased request. ## Joined Queries Support @@ -6700,7 +6700,7 @@ DatabaseRegion helps [ValueObservation] and [DatabaseRegionObservation] track ch For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table. -For more details, see the [reference](https://groue.github.io/GRDB.swift/docs/5.14/Structs/DatabaseRegion.html). +For more details, see the [reference](https://groue.github.io/GRDB.swift/docs/5.15/Structs/DatabaseRegion.html). #### The DatabaseRegionConvertible Protocol @@ -7985,7 +7985,7 @@ When this is the case, there are two possible explanations: try db.execute(sql: "UPDATE player SET name = ?", arguments: [name]) ``` -For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.14/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp). +For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.15/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp). @@ -8126,7 +8126,7 @@ This chapter has [moved](Documentation/Concurrency.md#database-snapshots). #### DatabaseWriter and DatabaseReader Protocols -This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.14/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.14/Protocols/DatabaseWriter.html). +This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.15/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.15/Protocols/DatabaseWriter.html). #### Asynchronous APIs @@ -8174,7 +8174,7 @@ This chapter has [moved](Documentation/Concurrency.md#safe-and-unsafe-database-a [Sharing a Database]: Documentation/SharingADatabase.md [FAQ]: #faq [Database Observation]: #database-changes-observation -[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.14/Structs/SQLRequest.html +[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.15/Structs/SQLRequest.html [SQL literal]: Documentation/SQLInterpolation.md#sql-literal [Identifiable]: https://developer.apple.com/documentation/swift/identifiable [Query Interface Organization]: Documentation/QueryInterfaceOrganization.md diff --git a/Support/Info.plist b/Support/Info.plist index 50dcdecb8..00dd8a268 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 5.14.0 + 5.15.0 CFBundleSignature ???? CFBundleVersion