Merge branch 'development'

This commit is contained in:
Gwendal Roué committed 2021-12-02 19:43:04 +01:00
commit 7a77a1fd06
24 files changed
+564 -190

No files matched your search

+9
View File
@@ -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)
+2 -2
View File
@@ -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,
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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.'
+15
View File
@@ -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<T>(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 {
+2 -7
View File
@@ -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!
}
}
}
+5 -17
View File
@@ -180,14 +180,9 @@ extension DatabaseQueue {
public func read<T>(_ 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!
}
})
}
+5 -1
View File
@@ -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)
+1
View File
@@ -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.
-6
View File
@@ -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<Fetched, Value>: ValueReducer {
public var _isSelectedRegionDeterministic: Bool
{ 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<T>: ValueReducer {
public var _isSelectedRegionDeterministic: Bool
{ preconditionFailure() }
public func _fetch(_ db: Database) throws -> Never
{ preconditionFailure() }
+6
View File
@@ -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 {
+137 -9
View File
@@ -22,10 +22,6 @@ import Foundation
public struct ValueObservation<Reducer: ValueReducer> {
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<Reducer: ValueReducer> {
/// 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<R>(_ transform: @escaping (Reducer) -> R) -> ValueObservation<R> {
let makeReducer = self.makeReducer
return ValueObservation<R>(
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)?
@@ -212,7 +244,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
@@ -496,7 +528,101 @@ extension ValueObservation where Reducer == ValueReducers.Auto {
_ fetch: @escaping (Database) throws -> Value)
-> ValueObservation<ValueReducers.Fetch<Value>>
{
.init(makeReducer: { .init(isSelectedRegionDeterministic: true, fetch: fetch) })
.init(
trackingMode: .constantRegionRecordedFromSelection,
makeReducer: { ValueReducers.Fetch(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<Value>(
region: DatabaseRegionConvertible...,
fetch: @escaping (Database) throws -> Value)
-> ValueObservation<ValueReducers.Fetch<Value>>
{
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<Value>(
regions: [DatabaseRegionConvertible],
fetch: @escaping (Database) throws -> Value)
-> ValueObservation<ValueReducers.Fetch<Value>>
{
.init(
trackingMode: .constantRegion(regions),
makeReducer: { ValueReducers.Fetch(fetch: fetch) })
}
/// Creates a `ValueObservation` that notifies the values returned by the
@@ -521,7 +647,9 @@ extension ValueObservation where Reducer == ValueReducers.Auto {
_ fetch: @escaping (Database) throws -> Value)
-> ValueObservation<ValueReducers.Fetch<Value>>
{
.init(makeReducer: { .init(isSelectedRegionDeterministic: false, fetch: fetch) })
.init(
trackingMode: .nonConstantRegionRecordedFromSelection,
makeReducer: { ValueReducers.Fetch(fetch: fetch) })
}
/// Creates a `ValueObservation` that notifies the values returned by the
+104 -43
View File
@@ -5,6 +5,7 @@ import Foundation
final class ValueObserver<Reducer: ValueReducer> {
var isCompleted: Bool { synchronized { _isCompleted } }
let events: ValueObservationEvents
let trackingMode: ValueObservationTrackingMode
private var observedRegion: DatabaseRegion? {
didSet {
if let willTrackRegion = events.willTrackRegion,
@@ -23,12 +24,18 @@ final class ValueObserver<Reducer: ValueReducer> {
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:
// - <https://github.com/groue/GRDB.swift/issues/1026>
// - <https://github.com/groue/GRDB.swift/pull/1025>
private var lock = NSRecursiveLock() // protects _isCompleted and reducer
init(
events: ValueObservationEvents,
reducer: Reducer,
requiresWriteAccess: Bool,
trackingMode: ValueObservationTrackingMode,
writer: DatabaseWriter,
scheduler: ValueObservationScheduler,
reduceQueue: DispatchQueue,
@@ -37,6 +44,7 @@ final class ValueObserver<Reducer: ValueReducer> {
self.events = events
self.reducer = reducer
self.requiresWriteAccess = requiresWriteAccess
self.trackingMode = trackingMode
self.writer = writer
self.scheduler = scheduler
self.reduceQueue = reduceQueue
@@ -54,6 +62,7 @@ final class ValueObserver<Reducer: ValueReducer> {
events: observation.events,
reducer: observation.makeReducer(),
requiresWriteAccess: observation.requiresWriteAccess,
trackingMode: observation.trackingMode,
writer: writer,
scheduler: scheduler,
reduceQueue: reduceQueue,
@@ -81,47 +90,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<Reducer.Fetched>
if requiresWriteAccess || needsRecordingSelectedRegion {
// Synchronously
fetchedFuture = DatabaseFuture(Result {
try recordingSelectedRegionIfNeeded(db) {
try synchronized {
try reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
}
})
} 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) {
@@ -145,9 +126,11 @@ 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 updatingObserverRegionIfNeeded(db) {
try synchronized {
try reducer.fetchAndReduce(db)
}
}
}
}
@@ -196,25 +179,103 @@ extension ValueObserver {
// MARK: - Private
extension ValueObserver {
/// Returns nil if the database was closed
private func fetchFuture(_ writerDB: Database) -> DatabaseFuture<Reducer.Fetched>? {
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<Reducer.Fetched> {
DatabaseFuture(Result {
try writerDB.isolated(readOnly: !requiresWriteAccess) {
try fetchUpdatingObserverRegionIfNeeded(writerDB)
}
})
}
/// Returns nil if the database was closed
private func fetchFutureConcurrent(_ writerDB: Database) -> DatabaseFuture<Reducer.Fetched>? {
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<Reducer.Fetched>) {
// 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<T>(_ 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<T>(
private func updatingObserverRegionIfNeeded<T>(
_ 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<T>(
_ db: Database,
fetch: () throws -> T)
throws -> T
{
var region = DatabaseRegion()
let result = try db.recordingSelection(&region, fetch)
observedRegion = try region.observableRegion(db)
+4 -18
View File
@@ -2,30 +2,16 @@ extension ValueReducers {
/// A reducer which passes raw fetched values through.
public struct Fetch<Value>: ValueReducer {
private let __fetch: (Database) throws -> Value
/// :nodoc:
public let _isSelectedRegionDeterministic: Bool
/// 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(fetch: @escaping (Database) throws -> Value) {
self.__fetch = fetch
}
/// :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:
@@ -17,8 +17,6 @@ extension ValueReducers {
public struct Map<Base: ValueReducer, Value>: ValueReducer {
private var base: Base
private let transform: (Base.Value) -> Value
/// :nodoc:
public var _isSelectedRegionDeterministic: Bool { base._isSelectedRegionDeterministic }
init(_ base: Base, _ transform: @escaping (Base.Value) -> Value) {
self.base = base
@@ -13,8 +13,6 @@ extension ValueReducers {
public struct RemoveDuplicates<Base: ValueReducer>: ValueReducer where Base.Value: Equatable {
private var base: Base
private var previousValue: Base.Value?
/// :nodoc:
public var _isSelectedRegionDeterministic: Bool { base._isSelectedRegionDeterministic }
init(_ base: Base) {
self.base = base
@@ -4,8 +4,6 @@ extension ValueReducers {
var base: Base
let willFetch: () -> Void
let didReceiveValue: (Base.Value) -> Void
/// :nodoc:
public var _isSelectedRegionDeterministic: Bool { base._isSelectedRegionDeterministic }
/// :nodoc:
public func _fetch(_ db: Database) throws -> Base.Fetched {
@@ -8,10 +8,6 @@ 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 }
/// Fetches database values upon changes in an observed database region.
///
/// ValueReducer semantics require that this method does not depend on
@@ -37,24 +33,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))
}
}
@@ -66,8 +46,6 @@ public enum ValueReducers {
// ValueObservation<ValueReducers.Auto>.tracking(_:).
/// :nodoc:
public enum Auto: ValueReducer {
/// :nodoc:
public var _isSelectedRegionDeterministic: Bool { preconditionFailure() }
/// :nodoc:
public func _fetch(_ db: Database) throws -> Never { preconditionFailure() }
/// :nodoc:
+3 -3
View File
@@ -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
+68 -26
View File
@@ -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+ &bull; SQLite 3.8.5+ &bull; 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<Place>
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
@@ -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)
@@ -5934,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.
@@ -5942,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
@@ -6225,6 +6228,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.
@@ -6665,17 +6685,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.15/Structs/DatabaseRegion.html).
#### The DatabaseRegionConvertible Protocol
@@ -6690,6 +6715,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
@@ -7943,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).
@@ -8084,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
@@ -8132,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
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>5.14.0</string>
<string>5.15.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
-2
View File
@@ -242,8 +242,6 @@ public struct AnyValueReducer<Fetched, Value>: ValueReducer {
private var __fetch: (Database) throws -> Fetched
private var __value: (Fetched) -> Value?
public var _isSelectedRegionDeterministic: Bool { false }
public init(
fetch: @escaping (Database) throws -> Fetched,
value: @escaping (Fetched) -> Value?)
+197 -22
View File
@@ -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: DatabaseRegion.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 {
@@ -447,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<Void, Void>(
fetch: { _ in
if shouldStopObservation {
cancellable = nil /* deallocation */
}
shouldStopObservation = true
},
value: { _ in () })
})
let observation = ValueObservation(
trackingMode: .nonConstantRegionRecordedFromSelection,
makeReducer: {
AnyValueReducer<Void, Void>(
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
@@ -489,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<Void, Void>(
fetch: { _ in },
value: { _ in
if shouldStopObservation {
cancellable = nil /* deallocation right before notification */
}
shouldStopObservation = true
return ()
let observation = ValueObservation(
trackingMode: .nonConstantRegionRecordedFromSelection,
makeReducer: {
AnyValueReducer<Void, Void>(
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