diff --git a/CHANGELOG.md b/CHANGELOG.md index a0f9d8cef..3e369ea8c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 5.x Releases - +- [Next Release](#next-release) - `5.1.x` Releases - [5.1.0](#510) - `5.0.x` Releases - [5.0.0](#500) | [5.0.1](#501) | [5.0.2](#502) | [5.0.3](#503) @@ -69,6 +69,12 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [0.110.0](#01100), ... +## Next Release + +- **New**: [#868](https://github.com/groue/GRDB.swift/pull/868): ValueObservation optimization is opt-in. +- **Documentation update**: The [ValueObservation Performance](https://github.com/groue/GRDB.swift#valueobservation-performance) chapter has been extanded with a tip for observations that track a constant database region. + + ## 5.1.0 Released November 1, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v5.0.3...v5.1.0) diff --git a/Documentation/GRDB5MigrationGuide.md b/Documentation/GRDB5MigrationGuide.md index 6dfd64d5c..979673ee3 100644 --- a/Documentation/GRDB5MigrationGuide.md +++ b/Documentation/GRDB5MigrationGuide.md @@ -93,19 +93,6 @@ let observation = ValueObservation.tracking { db in let observation = ValueObservation.tracking(Player.fetchAll) ``` -If the tracked value is computed from several database requests that are not always the same, make sure you use the `trackingVaryingRegion` method, as below. See [Observing a Varying Database Region] for more information. - -```swift -// An observation which does not always execute the same requests: -let observation = ValueObservation.trackingVaryingRegion { db -> Int in - let preference = try Preference.fetchOne(db) ?? .default - switch preference.selection { - case .food: return try Food.fetchCount(db) - case .beverage: return try Beverage.fetchCount(db) - } -} -``` - Several methods that build observations were removed: ```swift @@ -515,7 +502,6 @@ let publisher = observation [ValueObservation]: ../README.md#valueobservation [DatabaseRegionObservation]: ../README.md#databaseregionobservation [RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB -[Observing a Varying Database Region]: ../README.md#observing-a-varying-database-region [removeDuplicates]: ../README.md#valueobservationremoveduplicates [Custom SQL functions]: ../README.md#custom-sql-functions [Batch updates]: ../README.md#update-requests diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 29ccf8925..9f9fbe6d3 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -409,14 +409,85 @@ extension ValueObservation where Reducer == ValueReducers.Auto { // MARK: - Creating ValueObservation - /// Creates a ValueObservation which notifies the values returned by the - /// *fetch* function whenever a database transaction changes them. + /// Creates an optimized `ValueObservation` that notifies the values + /// returned by the `fetch` function whenever a database transaction + /// changes them. /// - /// The *fetch* function must always performs the same database requests. - /// The stability of the observed database region allows optimizations. + /// The optimization only kicks in when the observation is started from a + /// `DatabasePool`: fresh values are fetched concurrently, and do not block + /// database writes. /// - /// When you want to observe a varying database region, use the - /// `ValueObservation.trackingVaryingRegion(_:)` method instead. + /// - precondition: The *fetch* function must perform requests that fetch + /// from a single and constant database region. The tracked region is made + /// of tables, columns, and, when possible, rowids of individual rows. All + /// changes that happen outside of this region do not impact + /// the observation. + /// + /// For example: + /// + /// // Tracks the full 'player' table + /// let observation = ValueObservation.trackingConstantRegion { db -> [Player] in + /// try Player.fetchAll(db) + /// } + /// + /// // Tracks the row with id 42 in the 'player' table + /// let observation = ValueObservation.trackingConstantRegion { db -> Player? in + /// try Player.fetchOne(db, key: 42) + /// } + /// + /// // Tracks the 'score' column in the 'player' table + /// let observation = ValueObservation.trackingConstantRegion { db -> Int? in + /// try Player.select(max(Column("score"))).fetchOne(db) + /// } + /// + /// // Tracks both the 'player' and 'team' tables + /// let observation = ValueObservation.trackingConstantRegion { db -> ([Team], [Player]) in + /// let teams = try Team.fetchAll(db) + /// let players = try Player.fetchAll(db) + /// return (teams, players) + /// } + /// + /// When you want to observe a varying database region, make sure you use + /// the `ValueObservation.tracking(_:)` method instead, or else some changes + /// will not be notified. + /// + /// For example, consider those three observations below that depend on some + /// user preference. They all track a varying region, and must + /// use `ValueObservation.tracking(_:)`: + /// + /// // Does not always track the same row in the player table. + /// let observation = ValueObservation.tracking { db -> Player? in + /// let pref = try Preference.fetchOne(db) ?? .default + /// return try Player.fetchOne(db, key: pref.favoritePlayerId) + /// } + /// + /// // Only tracks the 'user' table if there are some blocked emails. + /// let observation = ValueObservation.tracking { db -> [User] in + /// let pref = try Preference.fetchOne(db) ?? .default + /// let blockedEmails = pref.blockedEmails + /// return try User.filter(blockedEmails.contains(Column("email"))).fetchAll(db) + /// } + /// + /// // Sometimes tracks the 'food' table, and sometimes the 'beverage' table. + /// let observation = ValueObservation.tracking { db -> Int in + /// let pref = try Preference.fetchOne(db) ?? .default + /// switch pref.selection { + /// case .food: return try Food.fetchCount(db) + /// case .beverage: return try Beverage.fetchCount(db) + /// } + /// } + /// + /// - parameter fetch: A function that fetches the observed value from + /// the database. + public static func trackingConstantRegion( + _ fetch: @escaping (Database) throws -> Value) + -> ValueObservation> + { + .init(makeReducer: { .init(isSelectedRegionDeterministic: true, fetch: fetch) }) + } + + /// Creates a `ValueObservation` that notifies the values returned by the + /// `fetch` function whenever a database transaction changes them. /// /// For example: /// @@ -427,7 +498,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto { /// let cancellable = try observation.start( /// in: dbQueue, /// onError: { error in ... }, - /// onChange:) { players: [Player] in + /// onChange: { players: [Player] in /// print("Players have changed") /// }) /// @@ -437,18 +508,32 @@ extension ValueObservation where Reducer == ValueReducers.Auto { _ fetch: @escaping (Database) throws -> Value) -> ValueObservation> { - .init(makeReducer: { .init(isSelectedRegionDeterministic: true, fetch: fetch) }) + .init(makeReducer: { .init(isSelectedRegionDeterministic: false, fetch: fetch) }) } - /// Creates a ValueObservation which notifies the values returned by the - /// *fetch* function whenever a database transaction changes them. + /// Creates a `ValueObservation` that notifies the values returned by the + /// `fetch` function whenever a database transaction changes them. + /// + /// For example: + /// + /// let observation = ValueObservation.tracking { db in + /// try Player.fetchAll(db) + /// } + /// + /// let cancellable = try observation.start( + /// in: dbQueue, + /// onError: { error in ... }, + /// onChange: { players: [Player] in + /// print("Players have changed") + /// }) /// /// - parameter fetch: A function that fetches the observed value from /// the database. + @available(*, deprecated, renamed: "tracking(_:)") public static func trackingVaryingRegion( _ fetch: @escaping (Database) throws -> Value) -> ValueObservation> { - .init(makeReducer: { .init(isSelectedRegionDeterministic: false, fetch: fetch) }) + tracking(fetch) } } diff --git a/README.md b/README.md index 2ffafbaf5..2d911cd30 100644 --- a/README.md +++ b/README.md @@ -5509,84 +5509,6 @@ let disposable = observation.rx.observe(in: dbQueue).subscribe( 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). -#### Observing a Varying Database Region - -The `ValueObservation.tracking(_:)` creates an observation that tracks a *database region* which is infered from the function argument: - -```swift -// Tracks the full 'player' table -let observation = ValueObservation.tracking { db -> [Player] in - try Player.fetchAll(db) -} - -// Tracks the row with id 42 in the 'player' table -let observation = ValueObservation.tracking { db -> Player? in - try Player.fetchOne(db, key: 42) -} - -// Tracks the 'score' column in the 'player' table -let observation = ValueObservation.tracking { db -> Int? in - try Player.select(max(Column("score"))).fetchOne(db) -} - -// Tracks both the 'player' and 'team' tables -let observation = ValueObservation.tracking { db -> ([Team], [Player]) in - let teams = try Team.fetchAll(db) - let players = try Player.fetchAll(db) - return (teams, players) -} -``` - -The tracked region is made of tables, columns, and, when possible, rowids of individual rows. All changes that happen outside of this region do not impact the observation. - -Most observations track a constant region. But some need to observe a **varying region**, and those need to be created with the `ValueObservation.trackingVaryingRegion(_:)` method, or else they will miss changes. - -For example, consider those three observations that depend on some user preference: - -```swift -// Does not always track the same row in the player table. -let observation = ValueObservation.trackingVaryingRegion { db -> Player? in - let pref = try Preference.fetchOne(db) ?? .default - return try Player.fetchOne(db, key: pref.favoritePlayerId) -} - -// Only tracks the 'user' table if there are some blocked emails. -let observation = ValueObservation.trackingVaryingRegion { db -> [User] in - let pref = try Preference.fetchOne(db) ?? .default - let blockedEmails = pref.blockedEmails - return try User.filter(blockedEmails.contains(Column("email"))).fetchAll(db) -} - -// Sometimes tracks the 'food' table, and sometimes the 'beverage' table. -let observation = ValueObservation.trackingVaryingRegion { db -> Int in - let pref = try Preference.fetchOne(db) ?? .default - switch pref.selection { - case .food: return try Food.fetchCount(db) - case .beverage: return try Beverage.fetchCount(db) - } -} -``` - -As you see, observations of a varying region do not perform always the same requests, or perform several requests that depend on each other. - -When you are in doubt, add the [`print()` method](#valueobservationprint) to your observation before starting it, and look in your application logs for lines that start with `tracked region`. Make sure the printed database region covers the changes you expect to be tracked. - -
- Examples of tracked regions - -- `empty`: The empty region, which tracks nothing and never triggers the observation. -- `player(*)`: The full `player` table -- `player(id,name)`: The `id` and `name` columns of the `player` table -- `player(id,name)[1]`: The `id` and `name` columns of the row with id 1 in the `player` table -- `player(*),preference(*)`: Both the full `player` and `preference` tables - -
- -> :point_up: **Note**: observations of a varying region can not profit from a [database pool](#database-pools)'s ability to perform concurrent readonly requests. They must fetch their fresh values from the writer database connection, and thus postpone other application components that want to write. In other words, observations of varying regions increase write contention. -> -> Conversely, in a [database queue](#database-queues), observations of varying regions do not take any additional toll, compared to observations of a constant region. - - ### ValueObservation Scheduling By default, ValueObservation notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously: @@ -5819,7 +5741,7 @@ When needed, you can help GRDB optimize observations and reduce database content .share(replay: 1, scope: .whileConnected) ``` -3. :bulb: **Tip**: Use a [DatabasePool](#database-pools), because it can perform multi-threaded database accesses. +3. :bulb: **Tip**: Use a [database pool](#database-pools), because it can perform multi-threaded database accesses. 4. :bulb: **Tip**: When the observation processes some raw fetched values, use the [`map`](#valueobservationmap) operator: @@ -5838,27 +5760,78 @@ When needed, you can help GRDB optimize observations and reduce database content The `map` operator helps reducing database contention because it performs its job without blocking concurrent database reads. -5. :bulb: **Tip**: Consider rewriting [observations of a varying region](#observing-a-varying-database-region) into observations of a constant region, so that they can profit from DatabasePool concurrency: +4. :bulb: **Tip**: When the observation tracks a constant database region, create an optimized observation with the `ValueObservation.trackingConstantRegion(_:)` method. + + The optimization only kicks in when the observation is started from a [database pool](#database-pools): fresh values are fetched concurrently, and do not block database writes. + + The `ValueObservation.trackingConstantRegion(_:)` has a precondition: the observed requests must fetch from a single and constant database region. The tracked region is made of tables, columns, and, when possible, rowids of individual rows. All changes that happen outside of this region do not impact the observation. + + For example: ```swift - // An observation of a varying region - let observation = ValueObservation.trackingVaryingRegion { db -> Int in - switch try Preference.fetchOne(db)!.selection { - case .food: return try Food.fetchCount(db) - case .beverage: return try Beverage.fetchCount(db) - } + // Tracks the full 'player' table (only) + let observation = ValueObservation.trackingConstantRegion { db -> [Player] in + try Player.fetchAll(db) } - // The same observation, rewritten so that it tracks a constant region + // Tracks the row with id 42 in the 'player' table (only) + let observation = ValueObservation.trackingConstantRegion { db -> Player? in + try Player.fetchOne(db, key: 42) + } + + // Tracks the 'score' column in the 'player' table (only) + let observation = ValueObservation.trackingConstantRegion { db -> Int? in + try Player.select(max(Column("score"))).fetchOne(db) + } + + // Tracks both the 'player' and 'team' tables (only) + let observation = ValueObservation.trackingConstantRegion { db -> ([Team], [Player]) in + let teams = try Team.fetchAll(db) + let players = try Player.fetchAll(db) + return (teams, players) + } + ``` + + When you want to observe a varying database region, make sure you use the plain `ValueObservation.tracking(_:)` method instead, or else some changes will not be notified. + + For example, consider those three observations below that depend on some user preference. They all track a varying region, and must use `ValueObservation.tracking(_:)`: + + ```swift + // Does not always track the same row in the player table. + let observation = ValueObservation.tracking { db -> Player? in + let pref = try Preference.fetchOne(db) ?? .default + return try Player.fetchOne(db, key: pref.favoritePlayerId) + } + + // Only tracks the 'user' table if there are some blocked emails. + let observation = ValueObservation.tracking { db -> [User] in + let pref = try Preference.fetchOne(db) ?? .default + let blockedEmails = pref.blockedEmails + return try User.filter(blockedEmails.contains(Column("email"))).fetchAll(db) + } + + // Sometimes tracks the 'food' table, and sometimes the 'beverage' table. let observation = ValueObservation.tracking { db -> Int in - let foodCount = try Food.fetchCount(db) - let beverageCount = try Beverage.fetchCount(db) - switch try Preference.fetchOne(db)!.selection { - case .food: return foodCount - case .beverage: return beverageCount + let pref = try Preference.fetchOne(db) ?? .default + switch pref.selection { + case .food: return try Food.fetchCount(db) + case .beverage: return try Beverage.fetchCount(db) } } ``` + + When you are in doubt, add the [`print()` method](#valueobservationprint) to your observation before starting it, and look in your application logs for lines that start with `tracked region`. Make sure the printed database region covers the changes you expect to be tracked. + +
+ Examples of tracked regions + + - `empty`: The empty region, which tracks nothing and never triggers the observation. + - `player(*)`: The full `player` table + - `player(id,name)`: The `id` and `name` columns of the `player` table + - `player(id,name)[1]`: The `id` and `name` columns of the row with id 1 in the `player` table + - `player(*),preference(*)`: Both the full `player` and `preference` tables + +
## DatabaseRegionObservation @@ -7885,16 +7858,7 @@ For example: - `player(id,name)[1]`: The `id` and `name` columns of the row with id 1 in the `player` table - `player(*),team(*)`: Both the full `player` and `team` tables -If you happen to see a mismatch between the tracked region and your expectation, then your observation is likely an [observation of a varying region](#observing-a-varying-database-region). Change the definition of your observation by using `trackingVaryingRegion(_:)`: - -```swift -let observation = ValueObservation - .trackingVaryingRegion { db in ... } // <- - .print() -let cancellable = observation.start(...) -``` - -You should witness that the logs which start with `tracked region` now evolve in order to include the expected changes, and that you get the expected notifications. +If you happen to use the `ValueObservation.trackingConstantRegion(_:)` method and see a mismatch between the tracked region and your expectation, then change the definition of your observation by using `tracking(_:)`. You should witness that the logs which start with `tracked region` now evolve in order to include the expected changes, and that you get the expected notifications. If after all those steps (thanks you!), your observation is still failing you, please [open an issue](https://github.com/groue/GRDB.swift/issues/new) and provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example)! diff --git a/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift b/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift index 17ff11c7a..755febc62 100644 --- a/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift +++ b/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift @@ -33,7 +33,7 @@ class ValueObservationPublisherTests : XCTestCase { func test(writer: DatabaseWriter) throws { let publisher = ValueObservation - .tracking(Player.fetchCount) + .trackingConstantRegion(Player.fetchCount) .publisher(in: writer) let recorder = publisher.record() @@ -78,7 +78,7 @@ class ValueObservationPublisherTests : XCTestCase { let expectation = self.expectation(description: "") let semaphore = DispatchSemaphore(value: 0) let cancellable = ValueObservation - .tracking(Player.fetchCount) + .trackingConstantRegion(Player.fetchCount) .publisher(in: writer) .sink( receiveCompletion: { _ in }, @@ -105,7 +105,7 @@ class ValueObservationPublisherTests : XCTestCase { func test(writer: DatabaseWriter) throws { let publisher = ValueObservation - .tracking { try $0.execute(sql: "THIS IS NOT SQL") } + .trackingConstantRegion { try $0.execute(sql: "THIS IS NOT SQL") } .publisher(in: writer) let recorder = publisher.record() let completion = try wait(for: recorder.completion, timeout: 1) @@ -137,7 +137,7 @@ class ValueObservationPublisherTests : XCTestCase { func test(writer: DatabaseWriter) throws { let publisher = ValueObservation - .tracking(Player.fetchCount) + .trackingConstantRegion(Player.fetchCount) .publisher(in: writer, scheduling: .immediate) let recorder = publisher.record() @@ -190,7 +190,7 @@ class ValueObservationPublisherTests : XCTestCase { }) let observationCancellable = ValueObservation - .tracking(Player.fetchCount) + .trackingConstantRegion(Player.fetchCount) .publisher(in: writer, scheduling: .immediate) .subscribe(testSubject) @@ -212,7 +212,7 @@ class ValueObservationPublisherTests : XCTestCase { func test(writer: DatabaseWriter) throws { let publisher = ValueObservation - .tracking { try $0.execute(sql: "THIS IS NOT SQL") } + .trackingConstantRegion { try $0.execute(sql: "THIS IS NOT SQL") } .publisher(in: writer, scheduling: .immediate) let recorder = publisher.record() let completion = try recorder.completion.get() @@ -283,7 +283,7 @@ class ValueObservationPublisherTests : XCTestCase { receiveValue: { _ in expectation.fulfill() }) ValueObservation - .tracking(Player.fetchCount) + .trackingConstantRegion(Player.fetchCount) .publisher(in: writer) .subscribe(subscriber) @@ -320,7 +320,7 @@ class ValueObservationPublisherTests : XCTestCase { }) ValueObservation - .tracking(Player.fetchCount) + .trackingConstantRegion(Player.fetchCount) .publisher(in: writer) .subscribe(subscriber) @@ -359,7 +359,7 @@ class ValueObservationPublisherTests : XCTestCase { receiveValue: { _ in expectation.fulfill() }) ValueObservation - .tracking(Player.fetchCount) + .trackingConstantRegion(Player.fetchCount) .publisher(in: writer, scheduling: .immediate /* make sure we get the initial db state */) .subscribe(subscriber) @@ -403,7 +403,7 @@ class ValueObservationPublisherTests : XCTestCase { }) ValueObservation - .tracking(Player.fetchCount) + .trackingConstantRegion(Player.fetchCount) .publisher(in: writer, scheduling: .immediate /* make sure we get two db states */) .subscribe(subscriber) diff --git a/Tests/GRDBTests/ValueObservationCountTests.swift b/Tests/GRDBTests/ValueObservationCountTests.swift index 8124b94fb..45910416c 100644 --- a/Tests/GRDBTests/ValueObservationCountTests.swift +++ b/Tests/GRDBTests/ValueObservationCountTests.swift @@ -6,7 +6,7 @@ class ValueObservationCountTests: GRDBTestCase { struct T: TableRecord { } try assertValueObservation( - ValueObservation.tracking(T.fetchCount), + ValueObservation.trackingConstantRegion(T.fetchCount), records: [0, 1, 1, 2, 3, 4], setup: { db in try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") @@ -29,7 +29,7 @@ class ValueObservationCountTests: GRDBTestCase { struct T: TableRecord { } try assertValueObservation( - ValueObservation.tracking(T.fetchCount).removeDuplicates(), + ValueObservation.trackingConstantRegion(T.fetchCount).removeDuplicates(), records: [0, 1, 2, 3, 4], setup: { db in try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") diff --git a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift index d73803684..79e0a4236 100644 --- a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift @@ -21,7 +21,7 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { let request = SQLRequest(sql: "SELECT name FROM t ORDER BY id") try assertValueObservation( - ValueObservation.tracking(request.fetchAll), + ValueObservation.trackingConstantRegion(request.fetchAll), records: [ [], [Name(rawValue: "foo")], @@ -44,7 +44,7 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { }) try assertValueObservation( - ValueObservation.tracking(request.fetchAll).removeDuplicates(), + ValueObservation.trackingConstantRegion(request.fetchAll).removeDuplicates(), records: [ [], [Name(rawValue: "foo")], @@ -70,7 +70,7 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { let request = SQLRequest(sql: "SELECT name FROM t ORDER BY id DESC") try assertValueObservation( - ValueObservation.tracking(request.fetchOne), + ValueObservation.trackingConstantRegion(request.fetchOne), records: [ nil, Name(rawValue: "foo"), @@ -103,7 +103,7 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { }) try assertValueObservation( - ValueObservation.tracking(request.fetchOne).removeDuplicates(), + ValueObservation.trackingConstantRegion(request.fetchOne).removeDuplicates(), records: [ nil, Name(rawValue: "foo"), @@ -137,7 +137,7 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { let request = SQLRequest(sql: "SELECT name FROM t ORDER BY id") try assertValueObservation( - ValueObservation.tracking(request.fetchAll), + ValueObservation.trackingConstantRegion(request.fetchAll), records: [ [], [Name(rawValue: "foo")], @@ -160,7 +160,7 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { }) try assertValueObservation( - ValueObservation.tracking(request.fetchAll).removeDuplicates(), + ValueObservation.trackingConstantRegion(request.fetchAll).removeDuplicates(), records: [ [], [Name(rawValue: "foo")], @@ -186,7 +186,7 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { let request = SQLRequest(sql: "SELECT name FROM t ORDER BY id DESC") try assertValueObservation( - ValueObservation.tracking(request.fetchOne), + ValueObservation.trackingConstantRegion(request.fetchOne), records: [ nil, Name(rawValue: "foo"), @@ -219,7 +219,7 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { }) try assertValueObservation( - ValueObservation.tracking(request.fetchOne).removeDuplicates(), + ValueObservation.trackingConstantRegion(request.fetchOne).removeDuplicates(), records: [ nil, Name(rawValue: "foo"), diff --git a/Tests/GRDBTests/ValueObservationFetchTests.swift b/Tests/GRDBTests/ValueObservationFetchTests.swift index b4914065e..9da456677 100644 --- a/Tests/GRDBTests/ValueObservationFetchTests.swift +++ b/Tests/GRDBTests/ValueObservationFetchTests.swift @@ -4,7 +4,7 @@ import GRDB class ValueObservationFetchTests: GRDBTestCase { func testFetch() throws { try assertValueObservation( - ValueObservation.tracking { + ValueObservation.trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! }, records: [0, 1, 1, 2], @@ -21,7 +21,7 @@ class ValueObservationFetchTests: GRDBTestCase { func testRemoveDuplicated() throws { try assertValueObservation( ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! } + .trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! } .removeDuplicates(), records: [0, 1, 2], setup: { db in diff --git a/Tests/GRDBTests/ValueObservationMapTests.swift b/Tests/GRDBTests/ValueObservationMapTests.swift index 57e1d4bf6..511cc0395 100644 --- a/Tests/GRDBTests/ValueObservationMapTests.swift +++ b/Tests/GRDBTests/ValueObservationMapTests.swift @@ -4,7 +4,7 @@ import GRDB class ValueObservationMapTests: GRDBTestCase { func testMap() throws { let valueObservation = ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! } + .trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! } .map { "\($0)" } try assertValueObservation( @@ -20,7 +20,7 @@ class ValueObservationMapTests: GRDBTestCase { } func testMapPreservesConfiguration() { - var observation = ValueObservation.tracking { _ in } + var observation = ValueObservation.trackingConstantRegion { _ in } observation.requiresWriteAccess = true let mappedObservation = observation.map { _ in } diff --git a/Tests/GRDBTests/ValueObservationPrintTests.swift b/Tests/GRDBTests/ValueObservationPrintTests.swift index 0c9c314c6..22c4dc918 100644 --- a/Tests/GRDBTests/ValueObservationPrintTests.swift +++ b/Tests/GRDBTests/ValueObservationPrintTests.swift @@ -31,7 +31,7 @@ class ValueObservationPrintTests: GRDBTestCase { func test(_ dbReader: DatabaseReader) throws { let logger = TestStream() let observation = ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } + .trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } .print(to: logger) let expectation = self.expectation(description: "") @@ -65,7 +65,7 @@ class ValueObservationPrintTests: GRDBTestCase { func test(_ dbReader: DatabaseReader) throws { let logger = TestStream() let observation = ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } + .trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } .print(to: logger) let expectation = self.expectation(description: "") @@ -97,7 +97,7 @@ class ValueObservationPrintTests: GRDBTestCase { struct TestError: Error { } let logger = TestStream() let observation = ValueObservation - .tracking { _ in throw TestError() } + .trackingConstantRegion { _ in throw TestError() } .print(to: logger) let expectation = self.expectation(description: "") @@ -129,7 +129,7 @@ class ValueObservationPrintTests: GRDBTestCase { struct TestError: Error { } let logger = TestStream() let observation = ValueObservation - .tracking { _ in throw TestError() } + .trackingConstantRegion { _ in throw TestError() } .print(to: logger) let expectation = self.expectation(description: "") @@ -164,7 +164,7 @@ class ValueObservationPrintTests: GRDBTestCase { let logger = TestStream() var observation = ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } + .trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } .print(to: logger) observation.requiresWriteAccess = true @@ -206,7 +206,7 @@ class ValueObservationPrintTests: GRDBTestCase { let logger = TestStream() var observation = ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } + .trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } .print(to: logger) observation.requiresWriteAccess = true @@ -244,7 +244,7 @@ class ValueObservationPrintTests: GRDBTestCase { func test(_ dbWriter: DatabaseWriter) throws { let logger = TestStream() var observation = ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } + .trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } .print(to: logger) observation.requiresWriteAccess = true @@ -271,7 +271,7 @@ class ValueObservationPrintTests: GRDBTestCase { func test(_ dbWriter: DatabaseWriter) throws { let logger = TestStream() var observation = ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } + .trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } .print(to: logger) observation.requiresWriteAccess = true @@ -302,7 +302,7 @@ class ValueObservationPrintTests: GRDBTestCase { let logger = TestStream() var observation = ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } + .trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } .print(to: logger) observation.requiresWriteAccess = true @@ -345,7 +345,7 @@ class ValueObservationPrintTests: GRDBTestCase { let logger = TestStream() var observation = ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } + .trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } .print(to: logger) observation.requiresWriteAccess = true @@ -394,7 +394,7 @@ class ValueObservationPrintTests: GRDBTestCase { // transaction observer, some write did happen. var needsChange = true let observation = ValueObservation - .tracking({ db -> Int? in + .trackingConstantRegion({ db -> Int? in if needsChange { needsChange = false try dbPool.write { db in @@ -441,7 +441,7 @@ class ValueObservationPrintTests: GRDBTestCase { // transaction observer, some write did happen. var needsChange = true let observation = ValueObservation - .tracking({ db -> Int? in + .trackingConstantRegion({ db -> Int? in if needsChange { needsChange = false try dbPool.write { db in @@ -491,7 +491,7 @@ class ValueObservationPrintTests: GRDBTestCase { let logger = TestStream() let observation = ValueObservation - .trackingVaryingRegion({ db -> Int? in + .tracking({ db -> Int? in let table = try String.fetchOne(db, sql: "SELECT t FROM choice")! return try Int.fetchOne(db, sql: "SELECT MAX(id) FROM \(table)") }) @@ -543,7 +543,7 @@ class ValueObservationPrintTests: GRDBTestCase { let logger1 = TestStream() let logger2 = TestStream() let observation = ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } + .trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } .print("", to: logger1) .print("log", to: logger2) @@ -575,7 +575,7 @@ class ValueObservationPrintTests: GRDBTestCase { let logger1 = TestStream() let logger2 = TestStream() let observation = ValueObservation - .tracking { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } + .trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } .print(to: logger1) .removeDuplicates() .map { _ in "foo" } @@ -668,7 +668,7 @@ class ValueObservationPrintTests: GRDBTestCase { } } - let observation = ValueObservation.tracking { + let observation = ValueObservation.trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } diff --git a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift index 8ef808c27..18eb61e27 100644 --- a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift @@ -76,7 +76,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { .including(all: Parent.children.orderByPrimaryKey()) .orderByPrimaryKey() .asRequest(of: Row.self) - let observation = ValueObservation.tracking(request.fetchOne) + let observation = ValueObservation.trackingConstantRegion(request.fetchOne) let recorder = observation.record(in: dbQueue) try dbQueue.writeWithoutTransaction(performDatabaseModifications) @@ -113,7 +113,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { .including(all: Parent.children.orderByPrimaryKey()) .orderByPrimaryKey() .asRequest(of: Row.self) - let observation = ValueObservation.tracking(request.fetchAll) + let observation = ValueObservation.trackingConstantRegion(request.fetchAll) let recorder = observation.record(in: dbQueue) try dbQueue.writeWithoutTransaction(performDatabaseModifications) @@ -171,7 +171,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { .asRequest(of: ParentInfo.self) try assertValueObservation( - ValueObservation.tracking(request.fetchOne), + ValueObservation.trackingConstantRegion(request.fetchOne), records: [ nil, ParentInfo( @@ -205,7 +205,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { // The fundamental technique for removing duplicates of non-Equatable types try assertValueObservation( ValueObservation - .tracking { db in try Row.fetchOne(db, request) } + .trackingConstantRegion { db in try Row.fetchOne(db, request) } .removeDuplicates() .map { row in row.map(ParentInfo.init(row:)) }, records: [ @@ -240,7 +240,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { .asRequest(of: ParentInfo.self) try assertValueObservation( - ValueObservation.tracking(request.fetchAll), + ValueObservation.trackingConstantRegion(request.fetchAll), records: [ [], [ @@ -310,7 +310,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { // The fundamental technique for removing duplicates of non-Equatable types try assertValueObservation( ValueObservation - .tracking { db in try Row.fetchAll(db, request) } + .trackingConstantRegion { db in try Row.fetchAll(db, request) } .removeDuplicates() .map { rows in rows.map(ParentInfo.init(row:)) }, records: [ diff --git a/Tests/GRDBTests/ValueObservationReadonlyTests.swift b/Tests/GRDBTests/ValueObservationReadonlyTests.swift index 0697a1be2..3cff84226 100644 --- a/Tests/GRDBTests/ValueObservationReadonlyTests.swift +++ b/Tests/GRDBTests/ValueObservationReadonlyTests.swift @@ -5,7 +5,7 @@ class ValueObservationReadonlyTests: GRDBTestCase { func testReadOnlyObservation() throws { try assertValueObservation( - ValueObservation.tracking { + ValueObservation.trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! }, records: [0, 1], @@ -19,7 +19,7 @@ class ValueObservationReadonlyTests: GRDBTestCase { func testWriteObservationFailsByDefaultWithErrorHandling() throws { try assertValueObservation( - ValueObservation.tracking { db -> Int in + ValueObservation.trackingConstantRegion { db -> Int in try db.execute(sql: "INSERT INTO t DEFAULT VALUES") return 0 }, @@ -35,7 +35,7 @@ class ValueObservationReadonlyTests: GRDBTestCase { } func testWriteObservation() throws { - var observation = ValueObservation.tracking { db -> Int in + var observation = ValueObservation.trackingConstantRegion { db -> Int in XCTAssert(db.isInsideTransaction, "expected a wrapping transaction") try db.execute(sql: "CREATE TEMPORARY TABLE temp AS SELECT * FROM t") let result = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM temp")! @@ -57,7 +57,7 @@ class ValueObservationReadonlyTests: GRDBTestCase { func testWriteObservationIsWrappedInSavepointWithErrorHandling() throws { struct TestError: Error { } - var observation = ValueObservation.tracking { db in + var observation = ValueObservation.trackingConstantRegion { db in try db.execute(sql: "INSERT INTO t DEFAULT VALUES") throw TestError() } diff --git a/Tests/GRDBTests/ValueObservationRecordTests.swift b/Tests/GRDBTests/ValueObservationRecordTests.swift index 0568df3aa..9f52d61d6 100644 --- a/Tests/GRDBTests/ValueObservationRecordTests.swift +++ b/Tests/GRDBTests/ValueObservationRecordTests.swift @@ -18,7 +18,7 @@ class ValueObservationRecordTests: GRDBTestCase { let request = SQLRequest(sql: "SELECT * FROM t ORDER BY id") try assertValueObservation( - ValueObservation.tracking(request.fetchAll), + ValueObservation.trackingConstantRegion(request.fetchAll), records: [ [], [Player(id: 1, name: "foo")], @@ -43,7 +43,7 @@ class ValueObservationRecordTests: GRDBTestCase { // The fundamental technique for removing duplicates of non-Equatable types try assertValueObservation( ValueObservation - .tracking { try Row.fetchAll($0, request) } + .trackingConstantRegion { try Row.fetchAll($0, request) } .removeDuplicates() .map { $0.map(Player.init(row:)) }, records: [ @@ -71,7 +71,7 @@ class ValueObservationRecordTests: GRDBTestCase { let request = SQLRequest(sql: "SELECT * FROM t ORDER BY id DESC") try assertValueObservation( - ValueObservation.tracking(request.fetchOne), + ValueObservation.trackingConstantRegion(request.fetchOne), records: [ nil, Player(id: 1, name: "foo"), @@ -98,7 +98,7 @@ class ValueObservationRecordTests: GRDBTestCase { // The fundamental technique for removing duplicates of non-Equatable types try assertValueObservation( ValueObservation - .tracking { try Row.fetchOne($0, request) } + .trackingConstantRegion { try Row.fetchOne($0, request) } .removeDuplicates() .map { $0.map(Player.init(row:)) }, records: [ diff --git a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift index 9e0d34f07..e1ce89817 100644 --- a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift +++ b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift @@ -110,7 +110,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { // I'm completely paranoid about tuple destructuring - I can't wrap my // head about the rules that allow or disallow it. let dbQueue = try makeDatabaseQueue() - let observation = ValueObservation.tracking { db -> (Int, String) in + let observation = ValueObservation.trackingConstantRegion { db -> (Int, String) in (0, "") } _ = observation.start( @@ -137,7 +137,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { var regions: [DatabaseRegion] = [] let observation = ValueObservation - .trackingVaryingRegion({ db -> Int in + .tracking({ db -> Int in let table = try String.fetchOne(db, sql: "SELECT name FROM source")! return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! }) @@ -188,7 +188,7 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { var regions: [DatabaseRegion] = [] let observation = ValueObservation - .trackingVaryingRegion({ db -> Int in + .tracking({ db -> Int in let table = try String.fetchOne(db, sql: "SELECT name FROM source")! return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! }) diff --git a/Tests/GRDBTests/ValueObservationRowTests.swift b/Tests/GRDBTests/ValueObservationRowTests.swift index 8b377eb95..5b01e8e63 100644 --- a/Tests/GRDBTests/ValueObservationRowTests.swift +++ b/Tests/GRDBTests/ValueObservationRowTests.swift @@ -6,7 +6,7 @@ class ValueObservationRowTests: GRDBTestCase { let request = SQLRequest(sql: "SELECT * FROM t ORDER BY id") try assertValueObservation( - ValueObservation.tracking(request.fetchAll), + ValueObservation.trackingConstantRegion(request.fetchAll), records: [ [], [["id":1, "name":"foo"]], @@ -29,7 +29,7 @@ class ValueObservationRowTests: GRDBTestCase { }) try assertValueObservation( - ValueObservation.tracking(request.fetchAll).removeDuplicates(), + ValueObservation.trackingConstantRegion(request.fetchAll).removeDuplicates(), records: [ [], [["id":1, "name":"foo"]], @@ -55,7 +55,7 @@ class ValueObservationRowTests: GRDBTestCase { let request = SQLRequest(sql: "SELECT * FROM t ORDER BY id DESC") try assertValueObservation( - ValueObservation.tracking(request.fetchOne), + ValueObservation.trackingConstantRegion(request.fetchOne), records: [ nil, ["id":1, "name":"foo"], @@ -80,7 +80,7 @@ class ValueObservationRowTests: GRDBTestCase { }) try assertValueObservation( - ValueObservation.tracking(request.fetchOne).removeDuplicates(), + ValueObservation.trackingConstantRegion(request.fetchOne).removeDuplicates(), records: [ nil, ["id":1, "name":"foo"], @@ -106,7 +106,7 @@ class ValueObservationRowTests: GRDBTestCase { func testFTS4Observation() throws { try assertValueObservation( - ValueObservation.tracking(SQLRequest(sql: "SELECT * FROM ft_documents").fetchAll), + ValueObservation.trackingConstantRegion(SQLRequest(sql: "SELECT * FROM ft_documents").fetchAll), records: [ [], [["content":"foo"]]], @@ -120,7 +120,7 @@ class ValueObservationRowTests: GRDBTestCase { func testSynchronizedFTS4Observation() throws { try assertValueObservation( - ValueObservation.tracking(SQLRequest(sql: "SELECT * FROM ft_documents").fetchAll), + ValueObservation.trackingConstantRegion(SQLRequest(sql: "SELECT * FROM ft_documents").fetchAll), records: [ [], [["content":"foo"]]], @@ -141,7 +141,7 @@ class ValueObservationRowTests: GRDBTestCase { func testJoinedFTS4Observation() throws { try assertValueObservation( - ValueObservation.tracking(SQLRequest(sql: """ + ValueObservation.trackingConstantRegion(SQLRequest(sql: """ SELECT document.* FROM document JOIN ft_document ON ft_document.rowid = document.id WHERE ft_document MATCH 'foo' diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index 8c2a1957c..b3a60cbf6 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -7,7 +7,7 @@ class ValueObservationTests: GRDBTestCase { func test(_ dbWriter: DatabaseWriter) throws { // Create an observation struct TestError: Error { } - let observation = ValueObservation.tracking { _ in throw TestError() } + let observation = ValueObservation.trackingConstantRegion { _ in throw TestError() } // Start observation var error: TestError? @@ -36,7 +36,7 @@ class ValueObservationTests: GRDBTestCase { struct TestError: Error { } var nextError: Error? = nil // If not null, observation throws an error - let observation = ValueObservation.tracking { + let observation = ValueObservation.trackingConstantRegion { _ = try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t") if let error = nextError { throw error @@ -93,7 +93,7 @@ class ValueObservationTests: GRDBTestCase { var region: DatabaseRegion? let expectation = self.expectation(description: "") let observation = ValueObservation - .tracking(request.fetchAll) + .trackingConstantRegion(request.fetchAll) .handleEvents(willTrackRegion: { region = $0 expectation.fulfill() @@ -120,7 +120,7 @@ class ValueObservationTests: GRDBTestCase { // its first read access, and its write access that installs the // transaction observer, some write did happen. var needsChange = true - let observation = ValueObservation.tracking { db -> Int in + let observation = ValueObservation.trackingConstantRegion { db -> Int in if needsChange { needsChange = false try dbPool.write { db in @@ -160,7 +160,7 @@ class ValueObservationTests: GRDBTestCase { // its first read access, and its write access that installs the // transaction observer, some write did happen. var needsChange = true - let observation = ValueObservation.tracking { db -> Int in + let observation = ValueObservation.trackingConstantRegion { db -> Int in if needsChange { needsChange = false try dbPool.write { db in @@ -200,7 +200,7 @@ class ValueObservationTests: GRDBTestCase { // its first read access, and its write access that installs the // transaction observer, no write did happen. var needsChange = true - let observation = ValueObservation.tracking { db -> Int in + let observation = ValueObservation.trackingConstantRegion { db -> Int in if needsChange { needsChange = false DispatchQueue.main.asyncAfter(deadline: .now() + 1) { @@ -259,7 +259,7 @@ class ValueObservationTests: GRDBTestCase { // its first read access, and its write access that installs the // transaction observer, no write did happen. var needsChange = true - let observation = ValueObservation.tracking { db -> Int in + let observation = ValueObservation.trackingConstantRegion { db -> Int in if needsChange { needsChange = false DispatchQueue.main.asyncAfter(deadline: .now() + 1) { @@ -322,7 +322,7 @@ class ValueObservationTests: GRDBTestCase { notificationExpectation.expectedFulfillmentCount = 2 // Create an observation - let observation = ValueObservation.tracking { + let observation = ValueObservation.trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT * FROM t") } @@ -368,7 +368,7 @@ class ValueObservationTests: GRDBTestCase { notificationExpectation.expectedFulfillmentCount = 2 // Create an observation - let observation = ValueObservation.tracking { + let observation = ValueObservation.trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT * FROM t") }