diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 529ad6e18..1c05fd109 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,18 +1,13 @@ -### One more thing… +### Pull Request Checklist + - [ ] This pull request is submitted against the `development` branch. - [ ] Inline documentation has been updated. - [ ] README.md or another dedicated guide has been updated. - [ ] Changes are tested, for all flavors of GRDB, GRDBCipher, and GRDBCustomSQLite. -- [ ] Updated CHANGELOG.md +- [ ] CHANGELOG.md has been updated. diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d952cd80..804d541c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,136 @@ Release Notes ============= +All notable changes to this project will be documented in this file. + +GRDB adheres to [Semantic Versioning](https://semver.org/). + +#### 3.x Releases + +- `3.5.x` Releases - [3.5.0](#350) +- `3.4.x` Releases - [3.4.0](#340) +- `3.3.x` Releases - [3.3.0](#330) | [3.3.1](#331) +- `3.3.0` Betas - [3.3.0-beta1](#330-beta1) +- `3.2.x` Releases - [3.2.0](#320) +- `3.1.x` Releases - [3.1.0](#310) +- `3.0.x` Releases - [3.0.0](#300) + +#### 2.x Releases + +- `2.10.x` Releases - [2.10.0](#2100) +- `2.9.x` Releases - [2.9.0](#290) +- `2.8.x` Releases - [2.8.0](#280) +- `2.7.x` Releases - [2.7.0](#270) +- `2.6.x` Releases - [2.6.0](#260) | [2.6.1](#261) +- `2.5.x` Releases - [2.5.0](#250) +- `2.4.x` Releases - [2.4.0](#240) | [2.4.1](#241) | [2.4.2](#242) +- `2.3.x` Releases - [2.3.0](#230) | [2.3.1](#231) +- `2.2.x` Releases - [2.2.0](#220) +- `2.1.x` Releases - [2.1.0](#210) +- `2.0.x` Releases - [2.0.0](#200) | [2.0.1](#201) | [2.0.2](#202) | [2.0.3](#203) + +#### 1.x Releases + +- `1.3.x` Releases - [1.3.0](#130) +- `1.2.x` Releases - [1.2.0](#120) | [1.2.1](#121) | [1.2.2](#122) +- `1.1.x` Releases - [1.1.0](#110) +- `1.0.x` Releases - [1.0.0](#100) + +#### 0.x Releases + +- [0.110.0](#01100), ... + + +## Next Version + +### Fixed + +- [#449](https://github.com/groue/GRDB.swift/pull/449): Fix JSON encoding of empty containers + + +### New + +- [#442](https://github.com/groue/GRDB.swift/pull/442): Reindex +- [#443](https://github.com/groue/GRDB.swift/pull/443): In place record update +- [#445](https://github.com/groue/GRDB.swift/pull/445): Quality of service and target dispatch queue +- [#446](https://github.com/groue/GRDB.swift/pull/446): ValueObservation: delayed reducer creation +- [#444](https://github.com/groue/GRDB.swift/pull/444): Combine Value Observations +- [#451](https://github.com/groue/GRDB.swift/pull/451): ValueObservation.compactMap +- [#452](https://github.com/groue/GRDB.swift/pull/452): ValueObservation.mapReducer +- [#454](https://github.com/groue/GRDB.swift/pull/454): ValueObservation.distinctUntilChanged +- [#455](https://github.com/groue/GRDB.swift/pull/455): DatabaseRegionObservation +- ValueObservation methods which used to accept a variadic list of observed regions now also accept an array. +- ValueReducer, the protocol that fuels ValueObservation, is flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). It will remain so until more experience has been acquired. + + +### Documentation Diff + +- [Record Comparison](README.md#record-comparison): this chapter has been updated for the new `updateChanges(_:with:)` method. +- [ValueObservation](README.md#valueobservation): this chapter has been updated for the new `ValueObservation.combine`, `ValueObservation.compactMap`, and `Value.distinctUntilChanged` methods. +- [DatabaseRegionObservation](README.md#databaseregionobservation): this chapter describes the new `DatabaseRegionObservation` type. + + +### API diff + +```diff + extension Database { ++ func reindex(collation: Database.CollationName) throws ++ func reindex(collation: DatabaseCollation) throws + } + + extension MutablePersistableRecord { ++ mutating func updateChanges(_ db: Database, with change: (inout Self) throws -> Void) throws -> Bool + } + + extension PersistableRecord { ++ func updateChanges(_ db: Database, with change: (Self) throws -> Void) throws -> Bool + } + + struct ValueObservation { ++ static func tracking( ++ _ regions: [DatabaseRegionConvertible], ++ reducer: @escaping (Database) throws -> Reducer) ++ -> ValueObservation + } + ++extension ValueObservation where Reducer == Void { ++ static func tracking( ++ _ regions: [DatabaseRegionConvertible], ++ fetch: @escaping (Database) throws -> Value) ++ -> ValueObservation> ++ static func tracking( ++ _ regions: [DatabaseRegionConvertible], ++ fetchDistinct fetch: @escaping (Database) throws -> Value) ++ -> ValueObservation> ++ where Value: Equatable ++ static func combine(_ o1: ValueObservation, ...) ++ -> ValueObservation<...> ++} + ++extension ValueObservation where Reducer: ValueReducer { ++ func compactMap(_ transform: @escaping (Reducer.Value) -> T?) ++ -> ValueObservation> ++} + ++extension ValueObservation { ++ func mapReducer(_ transform: @escaping (Database, Reducer) throws -> R) ++ -> ValueObservation ++} + + struct Configuration { ++ var qos: DispatchQoS ++ var targetQueue: DispatchQueue? + } + ++struct DatabaseRegionObservation { ++ var extent: Database.TransactionObservationExtent ++ init(tracking regions: DatabaseRegionConvertible...) ++ init(tracking regions: [DatabaseRegionConvertible]) ++ func start(in dbWriter: DatabaseWriter, onChange: @escaping (Database) -> Void) throws -> TransactionObserver ++} +``` + + ## 3.5.0 Released November 2, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v3.4.0...v3.5.0) @@ -1308,7 +1438,7 @@ Released July 19, 2017 • [diff](https://github.com/groue/GRDB.swift/compare It used to generate `= NULL` which would not behave as expected. -## 1.2 +## 1.2.0 Released July 13, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.1...v1.2) @@ -1407,7 +1537,7 @@ Released July 13, 2017 • [diff](https://github.com/groue/GRDB.swift/compare ``` -## 1.1 +## 1.1.0 Released July 1, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.0...v1.1) @@ -1469,9 +1599,9 @@ Released July 1, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/ ``` -## 1.0 :tada: +## 1.0.0 -Released June 20, 2017 +Released June 20, 2017 :tada: **GRDB 1.0 comes with enhancements, and API stability.** diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift index dd39c279e..54ebb3e45 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift @@ -8,11 +8,10 @@ struct AppDatabase { /// Creates a fully initialized database at path static func openDatabase(atPath path: String) throws -> DatabaseQueue { // Connect to the database - // See https://github.com/groue/GRDB.swift/#database-connections - dbQueue = try DatabaseQueue(path: path) + // See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections + let dbQueue = try DatabaseQueue(path: path) - // Use DatabaseMigrator to define the database schema - // See https://github.com/groue/GRDB.swift/#migrations + // Define the database schema try migrator.migrate(dbQueue) return dbQueue @@ -20,8 +19,7 @@ struct AppDatabase { /// The DatabaseMigrator that defines the database schema. /// - /// This migrator is exposed so that migrations can be tested. - // See https://github.com/groue/GRDB.swift/#migrations + /// See https://github.com/groue/GRDB.swift/blob/master/README.md#migrations static var migrator: DatabaseMigrator { var migrator = DatabaseMigrator() @@ -29,11 +27,10 @@ struct AppDatabase { // Create a table // See https://github.com/groue/GRDB.swift#create-tables try db.create(table: "player") { t in - // An integer primary key auto-generates unique IDs - t.column("id", .integer).primaryKey() + t.autoIncrementedPrimaryKey("id") // Sort player names in a localized case insensitive fashion by default - // See https://github.com/groue/GRDB.swift/#unicode + // See https://github.com/groue/GRDB.swift/blob/master/README.md#unicode t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare) t.column("score", .integer).notNull() diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift index e88354b7a..672c383c0 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift @@ -20,7 +20,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { dbQueue = try AppDatabase.openDatabase(atPath: databaseURL.path) // Be a nice iOS citizen, and don't consume too much memory - // See https://github.com/groue/GRDB.swift/#memory-management + // See https://github.com/groue/GRDB.swift/blob/master/README.md#memory-management dbQueue.setupMemoryManagement(in: application) } } diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift index 66094ceab..3d22cef06 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift @@ -1,13 +1,17 @@ import GRDB +// A plain Player struct struct Player { - var id: Int64? // Auto-incremented database ids are Int64 + // Prefer Int64 for auto-incremented database ids + var id: Int64? var name: String var score: Int } // MARK: - Persistence +// Turn Player into a Codable Record. +// See https://github.com/groue/GRDB.swift/blob/master/README.md#records extension Player: Codable, FetchableRecord, MutablePersistableRecord { // Add ColumnExpression to Codable's CodingKeys so that we can use them // as database columns. @@ -26,6 +30,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord { // MARK: - Database access +// Define some useful player requests. +// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests extension Player { static func orderedByName() -> QueryInterfaceRequest { return Player.order(CodingKeys.name) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 61b709b22..0b761f1b3 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -308,11 +308,13 @@ This synchronization is not automatic with GRDB: records do not "auto-update". T Instead, have a look at [Database Observation]: -> :bulb: **Tip**: Use [FetchedRecordsController] when a table or collection views should remained synchronized with the database, in an animated way. +> :bulb: **Tip**: [ValueObservation] performs automated tracking of database changes. > -> :bulb: **Tip**: Use [RxGRDB] when your application needs to react to all changes in the results of a database request. +> :bulb: **Tip**: [FetchedRecordsController] performs automated tracking of database changes, and can animate the cells of a table or collection view. > -> :bulb: **Tip**: Use [TransactionObserver], the low-level protocol for database observation, for your most advanced needs. +> :bulb: **Tip**: [RxGRDB] performs automated tracking of database changes, in the [RxSwift](https://github.com/ReactiveX/RxSwift) way. +> +> :bulb: **Tip**: [TransactionObserver] provides low-level database observation, for your most advanced needs. > > :bulb: **Tip**: Don't try to write complex methods that both modify the database and the values in memory at the same time. Instead, modify the database with plain record types, and rely on database observation for automatically refreshing values, even complex ones. @@ -337,6 +339,7 @@ Instead, have a look at [Database Observation]: [Concurrency Guide]: ../README.md#concurrency [PersistableRecord]: ../README.md#persistablerecord-protocol [Database Observation]: ../README.md#database-changes-observation +[ValueObservation]: ../README.md#valueobservation [FetchedRecordsController]: ../README.md#fetchedrecordscontroller [RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB [TransactionObserver]: ../README.md#transactionobserver-protocol diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index b42142903..1782e4008 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -49,6 +49,29 @@ 560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; 560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; + 5613ED3521A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3421A95A5C00DC7A68 /* ValueObservation+Map.swift */; }; + 5613ED3621A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3421A95A5C00DC7A68 /* ValueObservation+Map.swift */; }; + 5613ED3721A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3421A95A5C00DC7A68 /* ValueObservation+Map.swift */; }; + 5613ED3F21A95A8B00DC7A68 /* ValueObservation+Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3E21A95A8B00DC7A68 /* ValueObservation+Combine.swift */; }; + 5613ED4021A95A8B00DC7A68 /* ValueObservation+Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3E21A95A8B00DC7A68 /* ValueObservation+Combine.swift */; }; + 5613ED4121A95A8B00DC7A68 /* ValueObservation+Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3E21A95A8B00DC7A68 /* ValueObservation+Combine.swift */; }; + 5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; }; + 5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; }; + 5613ED4621A95B2C00DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; }; + 5613ED4821A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */; }; + 5613ED4921A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */; }; + 5613ED4A21A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */; }; + 5613ED4C21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */; }; + 5613ED4D21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */; }; + 5613ED4E21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */; }; + 5613ED5021A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; }; + 5613ED5121A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; }; + 5613ED5221A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; }; + 5613ED5421A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */; }; + 5613ED5521A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */; }; + 5613ED5621A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */; }; + 5613EDA621A96A9300DC7A68 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613EDA521A96A9200DC7A68 /* ValueObservationCombineTests.swift */; }; + 5613EDA721A96A9300DC7A68 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613EDA521A96A9200DC7A68 /* ValueObservationCombineTests.swift */; }; 561667051D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; 5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */; }; 5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */; }; @@ -178,6 +201,27 @@ 5644DE6E20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; }; 5644DE6F20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; }; 564A50C81BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */; }; + 564CE43121AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; }; + 564CE43221AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; }; + 564CE43321AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; }; + 564CE4D621B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4D521B2DEB500652B19 /* ValueObservation+CompactMap.swift */; }; + 564CE4D721B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4D521B2DEB500652B19 /* ValueObservation+CompactMap.swift */; }; + 564CE4D821B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4D521B2DEB500652B19 /* ValueObservation+CompactMap.swift */; }; + 564CE4E621B2E06700652B19 /* ValueObservationCompactMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E521B2E06700652B19 /* ValueObservationCompactMapTests.swift */; }; + 564CE4E721B2E06800652B19 /* ValueObservationCompactMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E521B2E06700652B19 /* ValueObservationCompactMapTests.swift */; }; + 564CE4E921B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; }; + 564CE4EA21B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; }; + 564CE52021B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; }; + 564CE52121B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; }; + 564CE52221B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; }; + 564CE59D21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; + 564CE59E21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; + 564CE59F21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; + 564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */; }; + 564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */; }; + 564CE5AE21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */; }; + 564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */; }; + 564CE5BF21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */; }; 564E73DF203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; }; 564E73E0203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; }; 564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; }; @@ -881,6 +925,14 @@ 560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = ""; }; 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; 560FC5101CAEEDF10014AA8E /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; + 5613ED3421A95A5C00DC7A68 /* ValueObservation+Map.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Map.swift"; sourceTree = ""; }; + 5613ED3E21A95A8B00DC7A68 /* ValueObservation+Combine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Combine.swift"; sourceTree = ""; }; + 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueReducer.swift; sourceTree = ""; }; + 5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Row.swift"; sourceTree = ""; }; + 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+FetchableRecord.swift"; sourceTree = ""; }; + 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DatabaseValueConvertible.swift"; sourceTree = ""; }; + 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Count.swift"; sourceTree = ""; }; + 5613EDA521A96A9200DC7A68 /* ValueObservationCombineTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCombineTests.swift; sourceTree = ""; }; 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; @@ -929,6 +981,14 @@ 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = ""; }; 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversion.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; + 564CE43021AA901800652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = ""; }; + 564CE4D521B2DEB500652B19 /* ValueObservation+CompactMap.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+CompactMap.swift"; sourceTree = ""; }; + 564CE4E521B2E06700652B19 /* ValueObservationCompactMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCompactMapTests.swift; sourceTree = ""; }; + 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; + 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; + 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = ""; }; + 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = ""; }; + 564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = ""; }; 564E73DE203D50B9000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1348,6 +1408,25 @@ name = PersistableRecord; sourceTree = ""; }; + 5613ED4221A95AFB00DC7A68 /* ValueObservation */ = { + isa = PBXGroup; + children = ( + 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */, + 5613ED3E21A95A8B00DC7A68 /* ValueObservation+Combine.swift */, + 564CE4D521B2DEB500652B19 /* ValueObservation+CompactMap.swift */, + 5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */, + 5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */, + 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */, + 5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */, + 5613ED3421A95A5C00DC7A68 /* ValueObservation+Map.swift */, + 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */, + 5613ED4721A95C1200DC7A68 /* ValueObservation+Row.swift */, + 564CE43021AA901800652B19 /* ValueObserver.swift */, + 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */, + ); + path = ValueObservation; + sourceTree = ""; + }; 56176C581EACC2D8000F3F2B /* GRDBTests */ = { isa = PBXGroup; children = ( @@ -1361,6 +1440,7 @@ 56300B5C1C53C38F005A543B /* QueryInterface */, 56A238251B9C74A90082EB20 /* Record */, 56176C9F1EACEE15000F3F2B /* Support */, + 563B06BF2185CD1700B38F35 /* ValueObservation */, ); path = GRDBTests; sourceTree = ""; @@ -1484,10 +1564,13 @@ 563B06BF2185CD1700B38F35 /* ValueObservation */ = { isa = PBXGroup; children = ( + 5613EDA521A96A9200DC7A68 /* ValueObservationCombineTests.swift */, + 564CE4E521B2E06700652B19 /* ValueObservationCompactMapTests.swift */, 563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */, 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */, 563B06C02185D29F00B38F35 /* ValueObservationExtentTests.swift */, 563B06C92185D2E500B38F35 /* ValueObservationFetchTests.swift */, + 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */, 563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */, 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */, 563B06BC2185CCD300B38F35 /* ValueObservationReducerTests.swift */, @@ -1648,6 +1731,7 @@ 560A37A91C90084600949E71 /* DatabasePool */, 563363BB1C93FD32000BE133 /* DatabaseQueue */, 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */, + 564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */, 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */, 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */, 56A238131B9C74A90082EB20 /* DatabaseTests.swift */, @@ -1668,7 +1752,6 @@ 56A238201B9C74A90082EB20 /* Statement */, 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */, 5607EFD11BB8253300605DE3 /* TransactionObserver */, - 563B06BF2185CD1700B38F35 /* ValueObservation */, ); name = Core; sourceTree = ""; @@ -1746,6 +1829,7 @@ 56A238741B9C75030082EB20 /* DatabaseQueue.swift */, 563363BF1C942C04000BE133 /* DatabaseReader.swift */, 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */, + 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */, 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */, 566A84192041146100E50BFD /* DatabaseSnapshot.swift */, 56A238751B9C75030082EB20 /* DatabaseValue.swift */, @@ -1762,7 +1846,6 @@ 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, 5605F1471C672E4000235C62 /* Support */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, - 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */, ); path = Core; sourceTree = ""; @@ -1966,6 +2049,7 @@ 56A2389F1B9C753B0082EB20 /* Record */, DC37743319C8CFCE004FCF85 /* Supporting Files */, 5659F4861EA8D94E004A4992 /* Utils */, + 5613ED4221A95AFB00DC7A68 /* ValueObservation */, ); path = GRDB; sourceTree = ""; @@ -2402,22 +2486,28 @@ 56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 565490CE1D5AE252005622CB /* NSNull.swift in Sources */, 565490E41D5AE252005622CB /* TableRecord.swift in Sources */, + 564CE5AE21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */, 565490CF1D5AE252005622CB /* NSNumber.swift in Sources */, 566475C01D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56CEB51F1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, 565490E21D5AE252005622CB /* Record.swift in Sources */, 5656BF5120C723E300F98521 /* QueryOrdering.swift in Sources */, 565490C11D5AE236005622CB /* FetchRequest.swift in Sources */, + 5613ED4621A95B2C00DC7A68 /* ValueReducer.swift in Sources */, 5698AD1C1DAAD17F0056AF8C /* FTS5Tokenizer.swift in Sources */, 56CEB5171EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 56B964B71DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, + 5613ED5221A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 5653EB0B20944C7C00F46237 /* Association.swift in Sources */, + 564CE59F21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */, 56F5ABDA1D814330001F60CB /* NSData.swift in Sources */, 56D121601ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */, 566475A81D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5659F4961EA8D964004A4992 /* ReadWriteBox.swift in Sources */, + 5613ED3721A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */, 5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */, + 564CE43321AA901800652B19 /* ValueObserver.swift in Sources */, 56CEB5671EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 5653EB272094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 565490B91D5AE236005622CB /* DatabasePool.swift in Sources */, @@ -2430,18 +2520,23 @@ 565490D91D5AE252005622CB /* Migration.swift in Sources */, 56CEB5001EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD271DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, + 5613ED4121A95A8B00DC7A68 /* ValueObservation+Combine.swift in Sources */, 5653EB1120944C7C00F46237 /* AssociationRequest.swift in Sources */, C96C0F2D2084A45A006B2981 /* SQLiteDateParser.swift in Sources */, 566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, + 5613ED4A21A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */, 565490D51D5AE252005622CB /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 565490C51D5AE236005622CB /* SerializedDatabase.swift in Sources */, 56F3E7691E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, 5698AC7E1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, + 564CE52221B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */, 5653EB1A20944C7C00F46237 /* ForeignKey.swift in Sources */, 5698AC3D1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 563EF45D2163309F007DAACD /* Inflections.swift in Sources */, 565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */, 566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, + 5613ED4E21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, + 5613ED5621A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */, 56CEB5591EAA359A00BFAF62 /* SQLExpression.swift in Sources */, 5674A6FF1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 56E06F181E85906E008AE2A4 /* Fixits-0.102.0.swift in Sources */, @@ -2499,6 +2594,7 @@ 565490D61D5AE252005622CB /* StandardLibrary.swift in Sources */, 5653EB1720944C7C00F46237 /* AssociationQuery.swift in Sources */, 565490B81D5AE236005622CB /* DatabaseError.swift in Sources */, + 564CE4D821B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */, 56BF6D3C1DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56DAA2E11DE9C827006E10C8 /* Cursor.swift in Sources */, 5653EB0520944C7C00F46237 /* BelongsToAssociation.swift in Sources */, @@ -2549,7 +2645,9 @@ 56CEB5481EAA359A00BFAF62 /* Column.swift in Sources */, 5653EB262094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 5605F1641C672E4000235C62 /* Date.swift in Sources */, + 5613ED4921A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */, 566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, + 564CE43221AA901800652B19 /* ValueObserver.swift in Sources */, 5605F1721C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 56CEB5141EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 566475CF1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, @@ -2582,6 +2680,7 @@ 56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 5653EB1620944C7C00F46237 /* AssociationQuery.swift in Sources */, 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */, + 564CE52121B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */, 5653EC132098738B00F46237 /* SQLGenerationContext.swift in Sources */, 5657AB121D10899D006283EF /* URL.swift in Sources */, 5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */, @@ -2600,6 +2699,8 @@ 566B91161FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 56A238881B9C75030082EB20 /* Row.swift in Sources */, + 5613ED4D21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, + 564CE4D721B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */, 563EF44B2161F179007DAACD /* Inflections.swift in Sources */, 56CEB4F41EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 569531201C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, @@ -2622,15 +2723,21 @@ 5644DE6E20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */, C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */, 5605F1681C672E4000235C62 /* NSNumber.swift in Sources */, + 5613ED5521A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */, + 564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */, 56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 5656BF5020C723E300F98521 /* QueryOrdering.swift in Sources */, 5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */, 560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */, + 5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */, + 5613ED5121A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, + 5613ED3621A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */, 566475A51D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5653EB0720944C7C00F46237 /* ForeignKeyRequest.swift in Sources */, 5657AABC1D107001006283EF /* NSData.swift in Sources */, 31A778841C6A4E0600F507F6 /* FetchedRecordsController.swift in Sources */, + 5613ED4021A95A8B00DC7A68 /* ValueObservation+Combine.swift in Sources */, 56A238861B9C75030082EB20 /* DatabaseValue.swift in Sources */, 56CEB55D1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 566B91261FA4CF810012D5B0 /* Database+Schema.swift in Sources */, @@ -2638,6 +2745,7 @@ 56CEB5641EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56873BEF1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 564F9C311F07611600877A00 /* DatabaseFunction.swift in Sources */, + 564CE59E21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */, 56B964A01DA51B4C0002DA19 /* FTS5.swift in Sources */, 5674A6F01F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, ); @@ -2739,6 +2847,7 @@ 567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 563B06CB2185D2E500B38F35 /* ValueObservationFetchTests.swift in Sources */, 5623935B1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, + 5613EDA721A96A9300DC7A68 /* ValueObservationCombineTests.swift in Sources */, 5674A72D1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 566A84412041914000E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 56176C701EACCCC9000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, @@ -2774,7 +2883,9 @@ 56A238401B9C74A90082EB20 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 564F9C221F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, 56A8C2481D1918F00096E9D4 /* FoundationUUIDTests.swift in Sources */, + 564CE5BF21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */, 5653EAEF20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, + 564CE4E721B2E06800652B19 /* ValueObservationCompactMapTests.swift in Sources */, 56A2383C1B9C74A90082EB20 /* DatabaseErrorTests.swift in Sources */, 5690C32A1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */, 5657AB3A1D108BA9006283EF /* FoundationDataTests.swift in Sources */, @@ -2800,6 +2911,7 @@ 56F0B9921B6001C600A2F135 /* FoundationNSDateTests.swift in Sources */, 56A238381B9C74A90082EB20 /* DatabaseTests.swift in Sources */, 5653EAED20944B4F00F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, + 564CE4EA21B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */, 56300B5F1C53C38F005A543B /* QueryInterfaceRequestTests.swift in Sources */, 5634B10A1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, 560C97C81BFD0B8400BF8471 /* DatabaseFunctionTests.swift in Sources */, @@ -2915,6 +3027,7 @@ 56D496B81D813465008276D7 /* DataMemoryTests.swift in Sources */, 563B06CA2185D2E500B38F35 /* ValueObservationFetchTests.swift in Sources */, 56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */, + 5613EDA621A96A9300DC7A68 /* ValueObservationCombineTests.swift in Sources */, 56D496961D81317B008276D7 /* PersistableRecordTests.swift in Sources */, 5698AC9E1DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, 5674A72A1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, @@ -2950,7 +3063,9 @@ 56D496741D81309E008276D7 /* RecordCopyTests.swift in Sources */, 56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */, 56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, + 564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */, 564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, + 564CE4E621B2E06700652B19 /* ValueObservationCompactMapTests.swift in Sources */, 5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 56D496861D813147008276D7 /* UpdateStatementTests.swift in Sources */, 56D4965D1D81304E008276D7 /* FoundationNSNumberTests.swift in Sources */, @@ -2976,6 +3091,7 @@ 5674A7201F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 56D496551D812F83008276D7 /* FoundationDataTests.swift in Sources */, 56D4966A1D813086008276D7 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, + 564CE4E921B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */, 5653EAEC20944B4F00F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 562206071E420EA4005860AC /* DatabasePoolConcurrencyTests.swift in Sources */, 5698ACB61DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, @@ -3001,13 +3117,16 @@ files = ( 56873BEC1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */, + 5613ED4C21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, 56BF6D3D1DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, 5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */, + 5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */, 5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */, 56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 563EF44A2161F179007DAACD /* Inflections.swift in Sources */, 566B91091FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91231FA4CF810012D5B0 /* Database+Schema.swift in Sources */, + 5613ED3F21A95A8B00DC7A68 /* ValueObservation+Combine.swift in Sources */, 563B06AB217EF0CC00B38F35 /* ValueObservation.swift in Sources */, 56CEB5111EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */, @@ -3016,15 +3135,18 @@ 56CEB4F11EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */, 5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */, + 5613ED5421A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */, 566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215A1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 56CEB5611EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FA1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, + 564CE59D21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */, 5698AD351DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, 566B91131FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 5605F1591C672E4000235C62 /* CGFloat.swift in Sources */, 5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, + 564CE52021B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */, 5659F4A01EA8D997004A4992 /* Result.swift in Sources */, 5605F1631C672E4000235C62 /* Date.swift in Sources */, 5605F1711C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, @@ -3033,6 +3155,7 @@ 5698AC371D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */, 564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */, + 564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */, 5659F4981EA8D989004A4992 /* Pool.swift in Sources */, 5674A6F41F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB54C1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, @@ -3048,6 +3171,7 @@ 5653EB252094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 5605F1691C672E4000235C62 /* NSString.swift in Sources */, 560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */, + 564CE4D621B2DEB600652B19 /* ValueObservation+CompactMap.swift in Sources */, 56A8C2301D1914540096E9D4 /* UUID.swift in Sources */, 56CEB5011EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 56CEB55A1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, @@ -3061,13 +3185,16 @@ 5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56A238A41B9C753B0082EB20 /* Record.swift in Sources */, 56CEB5451EAA359A00BFAF62 /* Column.swift in Sources */, + 5613ED5021A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 5657AB0F1D10899D006283EF /* URL.swift in Sources */, 560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */, + 5613ED4821A95C1200DC7A68 /* ValueObservation+Row.swift in Sources */, 56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */, 5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 560A37A41C8F625000949E71 /* DatabasePool.swift in Sources */, 56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */, 5605F1931C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */, + 5613ED3521A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */, 566B912B1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56A2388B1B9C75030082EB20 /* Statement.swift in Sources */, 5690C3401D23E82A00E59934 /* Data.swift in Sources */, @@ -3082,6 +3209,7 @@ 56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 5653EB1520944C7C00F46237 /* AssociationQuery.swift in Sources */, 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */, + 564CE43121AA901800652B19 /* ValueObserver.swift in Sources */, 5605F1651C672E4000235C62 /* NSNull.swift in Sources */, 56CEB5191EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, 5653EB1820944C7C00F46237 /* ForeignKey.swift in Sources */, diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index b07c02286..fac576893 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -1,4 +1,5 @@ import Foundation +import Dispatch #if SWIFT_PACKAGE import CSQLite #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER @@ -136,11 +137,28 @@ public struct Configuration { /// Default: 5 public var maximumReaderCount: Int = 5 + /// The quality of service class for the work performed by the database. + /// + /// The quality of service is ignored if you supply a target queue. + /// + /// Default: .default (.unspecified on macOS < 10.10) + public var qos: DispatchQoS + + /// The target queue for the work performed by the database. + /// + /// Default: nil + public var targetQueue: DispatchQueue? = nil // MARK: - Factory Configuration /// Creates a factory configuration - public init() { } + public init() { + if #available(OSX 10.10, *) { + qos = .default + } else { + qos = .unspecified + } + } // MARK: - Not Public @@ -153,6 +171,15 @@ public struct Configuration { let readWriteFlags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE) return threadingMode.SQLiteOpenFlags | readWriteFlags } + + func makeDispatchQueue(defaultLabel: String, purpose: String? = nil) -> DispatchQueue { + let label = (self.label ?? defaultLabel) + (purpose.map { "." + $0 } ?? "") + if let targetQueue = targetQueue { + return DispatchQueue(label: label, target: targetQueue) + } else { + return DispatchQueue(label: label, qos: qos) + } + } } /// A tracing function that takes an SQL string. diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 1257be73b..fe07fd0ec 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -26,7 +26,7 @@ extension Database { /// Returns whether a table exists. public func tableExists(_ name: String) throws -> Bool { - return try exists(type: "table", name: name) + return try exists(type: .table, name: name) } /// Returns whether a table is an internal SQLite table. @@ -53,30 +53,21 @@ extension Database { /// Returns whether a view exists. public func viewExists(_ name: String) throws -> Bool { - return try exists(type: "view", name: name) + return try exists(type: .view, name: name) } /// Returns whether a trigger exists. public func triggerExists(_ name: String) throws -> Bool { - return try exists(type: "trigger", name: name) + return try exists(type: .trigger, name: name) } - private func exists(type: String, name: String) throws -> Bool { + private func exists(type: SchemaObjectType, name: String) throws -> Bool { // SQlite identifiers are case-insensitive, case-preserving: // http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html let name = name.lowercased() - - if try makeSelectStatement("SELECT 1 FROM sqlite_master WHERE type = ? AND LOWER(name) = ?") - .makeCursor(arguments: [type, name]) - .isEmpty() == false - { return true } - - if try makeSelectStatement("SELECT 1 FROM sqlite_temp_master WHERE type = ? AND LOWER(name) = ?") - .makeCursor(arguments: [type, name]) - .isEmpty() == false - { return true } - - return false + return try schema() + .names(ofType: type) + .contains { $0.lowercased() == name } } /// The primary key for table named `tableName`. @@ -271,27 +262,19 @@ extension Database { /// Returns the actual name of the database table func canonicalTableName(_ tableName: String) throws -> String { - if let canonicalTableName = schemaCache.canonicalTableName(tableName) { - return canonicalTableName - } - - guard let canonicalTableName = try String.fetchOne(self, """ - SELECT name FROM ( - SELECT name, type FROM sqlite_master - UNION - SELECT name, type FROM sqlite_temp_master) - WHERE type = 'table' AND LOWER(name) = ? - """, arguments: [tableName.lowercased()]) - else { + guard let name = try schema().canonicalName(tableName, ofType: .table) else { throw DatabaseError(message: "no such table: \(tableName)") } - - schemaCache.set(canonicalTableName: canonicalTableName, forTable: tableName) - return canonicalTableName + return name } func schema() throws -> SchemaInfo { - return try SchemaInfo(self) + if let schemaInfo = schemaCache.schemaInfo { + return schemaInfo + } + let schemaInfo = try SchemaInfo(self) + schemaCache.schemaInfo = schemaInfo + return schemaInfo } } @@ -585,24 +568,58 @@ public struct ForeignKeyInfo { } } +enum SchemaObjectType: String { + case index + case table + case trigger + case view +} + struct SchemaInfo: Equatable { - var objects: [SchemaKey: String?] + private var objects: Set init(_ db: Database) throws { - objects = try Dictionary(uniqueKeysWithValues: Row - .fetchAll(db, "SELECT type, name, tbl_name, sql FROM sqlite_master") - .map { row in (SchemaKey(row: row), row["sql"]) }) + objects = try Set(SchemaObject.fetchCursor(db, """ + SELECT type, name, tbl_name, sql, 0 AS isTemporary FROM sqlite_master \ + UNION \ + SELECT type, name, tbl_name, sql, 1 FROM sqlite_temp_master + """)) } - struct SchemaKey: Codable, Hashable, FetchableRecord { + /// All names for a given type + func names(ofType type: SchemaObjectType) -> Set { + return objects.reduce(into: []) { (set, key) in + if key.type == type.rawValue { + set.insert(key.name) + } + } + } + + /// Returns the canonical name of the object: + /// + /// try db.execute("CREATE TABLE FooBar (...)") + /// try db.schema().canonicalName("foobar", ofType: .table) // "FooBar" + func canonicalName(_ name: String, ofType type: SchemaObjectType) -> String? { + let name = name.lowercased() + return objects.first { $0.name.lowercased() == name }?.name + } + + private struct SchemaObject: Codable, Hashable, FetchableRecord { var type: String var name: String var tbl_name: String? - + var sql: String? + var isTemporary: Bool + #if !swift(>=4.2) - var hashValue: Int { - return type.hashValue ^ name.hashValue ^ (tbl_name?.hashValue ?? 0) - } + var hashValue: Int { + var hash = type.hashValue + hash ^= name.hashValue + hash ^= (tbl_name?.hashValue ?? 0) + hash ^= (sql?.hashValue ?? 0) + hash ^= isTemporary.hashValue + return hash + } #endif } } diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 2a2a96714..8d50b0dcf 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -202,6 +202,16 @@ extension Database { var sqliteConnection: SQLiteConnection? = nil let code = sqlite3_open_v2(path, &sqliteConnection, flags, nil) guard code == SQLITE_OK else { + // https://www.sqlite.org/c3ref/open.html + // > Whether or not an error occurs when it is opened, resources + // > associated with the database connection handle should be + // > released by passing it to sqlite3_close() when it is no + // > longer required. + // + // https://www.sqlite.org/c3ref/close.html + // > Calling sqlite3_close() or sqlite3_close_v2() with a NULL + // > pointer argument is a harmless no-op. + sqlite3_close(sqliteConnection) throw DatabaseError(resultCode: code) } if let sqliteConnection = sqliteConnection { @@ -539,8 +549,8 @@ extension Database { // query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) // Assume those pragmas never fail - try! execute("PRAGMA query_only = 1") - defer { try! execute("PRAGMA query_only = 0") } + try! internalCachedUpdateStatement("PRAGMA query_only = 1").execute() + defer { try! internalCachedUpdateStatement("PRAGMA query_only = 0").execute() } return try block() } } @@ -704,6 +714,56 @@ extension Database { public func beginTransaction(_ kind: TransactionKind? = nil) throws { let kind = kind ?? configuration.defaultTransactionKind try execute("BEGIN \(kind.rawValue) TRANSACTION") + assert(isInsideTransaction) + } + + /// Begins a database transaction and take a snapshot of the last committed + /// database state. + func beginSnapshotIsolation() throws { + // https://www.sqlite.org/isolation.html + // + // > In WAL mode, SQLite exhibits "snapshot isolation". When a read + // > transaction starts, that reader continues to see an unchanging + // > "snapshot" of the database file as it existed at the moment in time + // > when the read transaction started. Any write transactions that + // > commit while the read transaction is active are still invisible to + // > the read transaction, because the reader is seeing a snapshot of + // > database file from a prior moment in time. + // + // That's exactly what we need. But what does "when read transaction + // starts" mean? + // + // http://www.sqlite.org/lang_transaction.html + // + // > Deferred [transaction] means that no locks are acquired on the + // > database until the database is first accessed. [...] Locks are not + // > acquired until the first read or write operation. [...] Because the + // > acquisition of locks is deferred until they are needed, it is + // > possible that another thread or process could create a separate + // > transaction and write to the database after the BEGIN on the + // > current thread has executed. + // + // Now that's precise enough: SQLite defers "snapshot isolation" until + // the first SELECT: + // + // Reader Writer + // BEGIN DEFERRED TRANSACTION + // UPDATE ... (1) + // Here the change (1) is visible + // SELECT ... + // UPDATE ... (2) + // Here the change (2) is not visible + // + // We thus have to perform a select that establishes the + // snapshot isolation before we release the writer queue: + // + // Reader Writer + // BEGIN DEFERRED TRANSACTION + // SELECT anything + // UPDATE ... + // Here the change is not visible by GRDB user + try beginTransaction(.deferred) + try internalCachedSelectStatement("SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next() } /// Rollbacks a database transaction. diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index 778e3e8ef..2299c70a7 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -141,20 +141,28 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible // CustomStringConvertible extension ResultCode { - /// :nodoc: - public var description: String { + var errorString: String? { // sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15 // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) #if GRDBCUSTOMSQLITE || GRDBCIPHER - return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))" + return String(cString: sqlite3_errstr(rawValue)) #else if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) { - return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))" + return String(cString: sqlite3_errstr(rawValue)) } else { - return "\(rawValue)" + return nil } #endif } + + /// :nodoc: + public var description: String { + if let errorString = errorString { + return "\(rawValue) (\(errorString))" + } else { + return "\(rawValue)" + } + } } /// DatabaseError wraps an SQLite error. @@ -199,7 +207,7 @@ public struct DatabaseError : Error, CustomStringConvertible, CustomNSError { /// Creates a Database Error public init(resultCode: ResultCode = .SQLITE_ERROR, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) { self.extendedResultCode = resultCode - self.message = message + self.message = message ?? resultCode.errorString self.sql = sql self.arguments = arguments } diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 2da9e72cc..241723b58 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -52,7 +52,8 @@ public final class DatabasePool: DatabaseWriter { path: path, configuration: configuration, schemaCache: SimpleDatabaseSchemaCache(), - label: (configuration.label ?? "GRDB.DatabasePool") + ".writer") + defaultLabel: "GRDB.DatabasePool", + purpose: "writer") // Activate WAL Mode unless readonly if !configuration.readonly { @@ -89,7 +90,8 @@ public final class DatabasePool: DatabaseWriter { path: path, configuration: self.readerConfig, schemaCache: SimpleDatabaseSchemaCache(), - label: (self.readerConfig.label ?? "GRDB.DatabasePool") + ".reader.\(readerCount)") + defaultLabel: "GRDB.DatabasePool", + purpose: "reader.\(readerCount)") reader.sync { self.setupDatabase($0) } return reader }) @@ -386,50 +388,6 @@ extension DatabasePool : DatabaseReader { /// happen while establishing the read access to the database. @available(*, deprecated, message: "Use concurrentRead instead") public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws { - // https://www.sqlite.org/isolation.html - // - // > In WAL mode, SQLite exhibits "snapshot isolation". When a read - // > transaction starts, that reader continues to see an unchanging - // > "snapshot" of the database file as it existed at the moment in time - // > when the read transaction started. Any write transactions that - // > commit while the read transaction is active are still invisible to - // > the read transaction, because the reader is seeing a snapshot of - // > database file from a prior moment in time. - // - // That's exactly what we need. But what does "when read transaction - // starts" mean? - // - // http://www.sqlite.org/lang_transaction.html - // - // > Deferred [transaction] means that no locks are acquired on the - // > database until the database is first accessed. [...] Locks are not - // > acquired until the first read or write operation. [...] Because the - // > acquisition of locks is deferred until they are needed, it is - // > possible that another thread or process could create a separate - // > transaction and write to the database after the BEGIN on the - // > current thread has executed. - // - // Now that's precise enough: SQLite defers "snapshot isolation" until - // the first SELECT: - // - // Reader Writer - // BEGIN DEFERRED TRANSACTION - // UPDATE ... (1) - // Here the change (1) is visible - // SELECT ... - // UPDATE ... (2) - // Here the change (2) is not visible - // - // The readFromCurrentState method says that no change should be visible - // at all. We thus have to perform a select that establishes the - // snapshot isolation before we release the writer queue: - // - // Reader Writer - // BEGIN DEFERRED TRANSACTION - // SELECT anything - // UPDATE ... - // Here the change is not visible by GRDB user - // Check that we're on the writer queue... writer.execute { db in // ... and that no transaction is opened. @@ -445,79 +403,36 @@ extension DatabasePool : DatabaseReader { // isolation has been established: let semaphore = DispatchSemaphore(value: 0) - var readError: Error? = nil - try readerPool.get { reader in - reader.async { db in - do { - try db.beginTransaction(.deferred) - assert(db.isInsideTransaction) - try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").makeCursor().next() - } catch { - readError = error - semaphore.signal() // Release the writer queue and rethrow error - return - } - semaphore.signal() // We can release the writer queue now that we are isolated for good - - // Reset the schema cache before running user code in snapshot isolation - db.schemaCache = SimpleDatabaseSchemaCache() - block(db) - + var snapshotIsolationError: Error? = nil + let (reader, releaseReader) = try readerPool.get() + reader.async { db in + defer { _ = try? db.commit() // Ignore commit error + releaseReader() } + do { + try db.beginSnapshotIsolation() + } catch { + snapshotIsolationError = error + semaphore.signal() // Release the writer queue and rethrow error + return + } + semaphore.signal() // We can release the writer queue now that we are isolated for good + + // Reset the schema cache before running user code in snapshot isolation + db.schemaCache = SimpleDatabaseSchemaCache() + block(db) } + _ = semaphore.wait(timeout: .distantFuture) - if let readError = readError { + + if let error = snapshotIsolationError { // TODO: write a test for this - throw readError + throw error } } public func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future { - // https://www.sqlite.org/isolation.html - // - // > In WAL mode, SQLite exhibits "snapshot isolation". When a read - // > transaction starts, that reader continues to see an unchanging - // > "snapshot" of the database file as it existed at the moment in time - // > when the read transaction started. Any write transactions that - // > commit while the read transaction is active are still invisible to - // > the read transaction, because the reader is seeing a snapshot of - // > database file from a prior moment in time. - // - // That's exactly what we need. But what does "when read transaction - // starts" mean? - // - // http://www.sqlite.org/lang_transaction.html - // - // > Deferred [transaction] means that no locks are acquired on the - // > database until the database is first accessed. [...] Locks are not - // > acquired until the first read or write operation. [...] Because the - // > acquisition of locks is deferred until they are needed, it is - // > possible that another thread or process could create a separate - // > transaction and write to the database after the BEGIN on the - // > current thread has executed. - // - // Now that's precise enough: SQLite defers "snapshot isolation" until - // the first SELECT: - // - // Reader Writer - // BEGIN DEFERRED TRANSACTION - // UPDATE ... (1) - // Here the change (1) is visible - // SELECT ... - // UPDATE ... (2) - // Here the change (2) is not visible - // - // The readFromCurrentState method says that no change should be visible - // at all. We thus have to perform a select that establishes the - // snapshot isolation before we release the writer queue: - // - // Reader Writer - // BEGIN DEFERRED TRANSACTION - // SELECT anything - // UPDATE ... - // Here the change is not visible by GRDB user - // Check that we're on the writer queue... writer.execute { db in // ... and that no transaction is opened. @@ -538,32 +453,30 @@ extension DatabasePool : DatabaseReader { var futureResult: Result? = nil do { - try readerPool.get { reader in - reader.async { db in - // Open a deferred transaction and access the database in - // order to establish snapshot isolation. - defer { _ = try? db.commit() } - do { - try db.beginTransaction(.deferred) - try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").makeCursor().next() - } catch { - // Snapshot isolation failure - futureResult = .failure(error) - isolationSemaphore.signal() - futureSemaphore.signal() - return - } - - // Release the writer queue - isolationSemaphore.signal() - - // Reset the schema cache before running user code in snapshot isolation - db.schemaCache = SimpleDatabaseSchemaCache() - - // Fetch and release the future - futureResult = Result { try block(db) } - futureSemaphore.signal() + let (reader, releaseReader) = try readerPool.get() + reader.async { db in + defer { + try? db.commit() // Ignore commit error + releaseReader() } + do { + try db.beginSnapshotIsolation() + } catch { + futureResult = .failure(error) + isolationSemaphore.signal() + futureSemaphore.signal() + return + } + + // Release the writer queue + isolationSemaphore.signal() + + // Reset the schema cache before running user code in snapshot isolation + db.schemaCache = SimpleDatabaseSchemaCache() + + // Fetch and release the future + futureResult = Result { try block(db) } + futureSemaphore.signal() } } catch { return Future { throw error } @@ -844,7 +757,8 @@ extension DatabasePool { let snapshot = try DatabaseSnapshot( path: path, configuration: writer.configuration, - labelSuffix: ".snapshot.\(snapshotCount.increment())") + defaultLabel: "GRDB.DatabasePool", + purpose: "snapshot.\(snapshotCount.increment())") snapshot.read { setupDatabase($0) } return snapshot } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 0814bb11c..60df0bfe8 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -40,7 +40,7 @@ public final class DatabaseQueue: DatabaseWriter { path: path, configuration: configuration, schemaCache: SimpleDatabaseSchemaCache(), - label: configuration.label ?? "GRDB.DatabaseQueue") + defaultLabel: "GRDB.DatabaseQueue") } /// Opens an in-memory SQLite database. @@ -56,7 +56,7 @@ public final class DatabaseQueue: DatabaseWriter { path: ":memory:", configuration: configuration, schemaCache: SimpleDatabaseSchemaCache(), - label: configuration.label ?? "GRDB.DatabaseQueue") + defaultLabel: "GRDB.DatabaseQueue") } #if os(iOS) diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 613796e9d..042bf335a 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -18,15 +18,15 @@ /// /// - `SelectStatement.databaseRegion`: /// -/// let statement = db.makeSelectStatement("SELECT name, score FROM player") -/// print(statement.databaseRegion) -/// // prints "player(name,score)" +/// let statement = db.makeSelectStatement("SELECT name, score FROM player") +/// print(statement.databaseRegion) +/// // prints "player(name,score)" /// /// - `FetchRequest.databaseRegion(_:)` /// -/// let request = Player.filter(key: 1) -/// try print(request.databaseRegion(db)) -/// // prints "player(*)[1]" +/// let request = Player.filter(key: 1) +/// try print(request.databaseRegion(db)) +/// // prints "player(*)[1]" /// /// Database regions returned by requests can be more precise than regions /// returned by select statements. Especially, regions returned by statements @@ -47,7 +47,10 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { /// Returns whether the region is empty. public var isEmpty: Bool { - guard let tableRegions = tableRegions else { return false } + guard let tableRegions = tableRegions else { + // full database + return false + } return tableRegions.isEmpty } @@ -122,7 +125,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { guard let otherTableRegions = other.tableRegions else { return .fullDatabase } var tableRegionsUnion: [String: TableRegion] = [:] - let tableNames = Set(tableRegions.map { $0.key }).union(Set(otherTableRegions.map { $0.key })) + let tableNames = Set(tableRegions.keys).union(Set(otherTableRegions.keys)) for table in tableNames { let tableRegion = tableRegions[table] let otherTableRegion = otherTableRegions[table] @@ -145,6 +148,13 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { public mutating func formUnion(_ other: DatabaseRegion) { self = union(other) } + + func ignoring(_ tables: Set) -> DatabaseRegion { + guard tables.isEmpty == false else { return self } + guard let tableRegions = tableRegions else { return .fullDatabase } + let filteredRegions = tableRegions.filter { tables.contains($0.key) == false } + return DatabaseRegion(tableRegions: filteredRegions) + } } extension DatabaseRegion { @@ -154,7 +164,7 @@ extension DatabaseRegion { /// Returns whether the content in the region would be impacted if the /// database were modified by an event of this kind. public func isModified(byEventsOfKind eventKind: DatabaseEventKind) -> Bool { - return !intersection(eventKind.modifiedRegion).isEmpty + return intersection(eventKind.modifiedRegion).isEmpty == false } /// Returns whether the content in the region is impacted by this event. @@ -164,31 +174,27 @@ extension DatabaseRegion { /// region.isModified(byEventsOfKind:) public func isModified(by event: DatabaseEvent) -> Bool { guard let tableRegions = tableRegions else { + // Full database: all changes are impactful return true } - switch tableRegions.count { - case 1: - // The precondition applies here: + if tableRegions.count == 1 { + // Fast path when the region contains a single table. // - // The region contains a single table. Due to the - // filtering of events performed in observes(eventsOfKind:), the - // event argument is guaranteed to be about the fetched table. - // We thus only have to check for rowIds. - assert(event.tableName == tableRegions[tableRegions.startIndex].key) // sanity check - guard let rowIds = tableRegions[tableRegions.startIndex].value.rowIds else { - return true - } - return rowIds.contains(event.rowID) - default: + // We can apply the precondition: due to the filtering of events + // performed in observes(eventsOfKind:), the event argument is + // guaranteed to be about the fetched table. We thus only have to + // check for rowIds. + assert(event.tableName == tableRegions[tableRegions.startIndex].key) // sanity check in debug mode + let tableRegion = tableRegions[tableRegions.startIndex].value + return tableRegion.contains(rowID: event.rowID) + } else { + // Slow path when several tables are observed. guard let tableRegion = tableRegions[event.tableName] else { // Shouldn't happen if the precondition is met. fatalError("precondition failure: event was not filtered out in observes(eventsOfKind:) by region.isModified(byEventsOfKind:)") } - guard let rowIds = tableRegion.rowIds else { - return true - } - return rowIds.contains(event.rowID) + return tableRegion.contains(rowID: event.rowID) } } } @@ -201,8 +207,8 @@ extension DatabaseRegion { case (nil, nil): return true case (let ltableRegions?, let rtableRegions?): - let ltableNames = Set(ltableRegions.map { $0.key }) - let rtableNames = Set(rtableRegions.map { $0.key }) + let ltableNames = Set(ltableRegions.keys) + let rtableNames = Set(rtableRegions.keys) guard ltableNames == rtableNames else { return false } @@ -295,6 +301,14 @@ private struct TableRegion: Equatable { return TableRegion(columns: columnsUnion, rowIds: rowIdsUnion) } + + @inline(__always) + func contains(rowID: Int64) -> Bool { + guard let rowIds = rowIds else { + return true + } + return rowIds.contains(rowID) + } } // MARK: - DatabaseRegionConvertible @@ -330,3 +344,21 @@ public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible { return try _region(db) } } + +// MARK: - Utils + +extension DatabaseRegion { + static func union(_ regions: DatabaseRegion...) -> DatabaseRegion { + return regions.reduce(into: DatabaseRegion()) { union, region in + union.formUnion(region) + } + } + + static func union(_ regions: [DatabaseRegionConvertible]) -> (Database) throws -> DatabaseRegion { + return { db in + try regions.reduce(into: DatabaseRegion()) { union, region in + try union.formUnion(region.databaseRegion(db)) + } + } + } +} diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift new file mode 100644 index 000000000..a55fd2b3f --- /dev/null +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -0,0 +1,133 @@ +/// DatabaseRegionObservation tracks changes in the results of database +/// requests, and notifies each database transaction whenever the +/// database changes. +/// +/// For example: +/// +/// let observation = DatabaseRegionObservation(tracking: Player.all) +/// let observer = try observation.start(in: dbQueue) { db: Database in +/// print("Players have changed.") +/// } +public struct DatabaseRegionObservation { + /// The extent of the database observation. The default is + /// `.observerLifetime`: the observation lasts until the + /// observer returned by the `start(in:onChange:)` method + /// is deallocated. + public var extent = Database.TransactionObservationExtent.observerLifetime + + /// A closure that is evaluated when the observation starts, and returns + /// the observed database region. + var observedRegion: (Database) throws -> DatabaseRegion + + // Not public because we foster DatabaseRegionConvertible. + init(tracking region: @escaping (Database) throws -> DatabaseRegion) { + self.observedRegion = { db in + // Remove views from the observed region. + // + // We can do it because we are only interested in modifications in + // actual tables. And we want to do it because we have a fast path + // for simple regions that span a single table. + let views = try db.schema().names(ofType: .view) + return try region(db).ignoring(views) + } + } + + /// Creates a DatabaseRegionObservation which observes *regions*, and + /// notifies whenever one of the observed regions is modified by a + /// database transaction. + /// + /// For example, this sample code counts the number of a times the player + /// table is modified: + /// + /// let observation = DatabaseRegionObservation(tracking: Player.all()) + /// + /// var count = 0 + /// let observer = observation.start(in: dbQueue) { _ in + /// count += 1 + /// print("Players have been modified \(count) times.") + /// } + /// + /// The observation lasts until the observer returned by `start` is + /// deallocated. See the `extent` property for more information. + /// + /// - parameter regions: A list of observed regions. + public init(tracking regions: DatabaseRegionConvertible...) { + self.init(tracking: regions) + } + + /// Creates a DatabaseRegionObservation which observes *regions*, and + /// notifies whenever one of the observed regions is modified by a + /// database transaction. + /// + /// For example, this sample code counts the number of a times the player + /// table is modified: + /// + /// let observation = DatabaseRegionObservation(tracking: [Player.all()]) + /// + /// var count = 0 + /// let observer = observation.start(in: dbQueue) { _ in + /// count += 1 + /// print("Players have been modified \(count) times.") + /// } + /// + /// The observation lasts until the observer returned by `start` is + /// deallocated. See the `extent` property for more information. + /// + /// - parameter regions: A list of observed regions. + public init(tracking regions: [DatabaseRegionConvertible]) { + self.init(tracking: DatabaseRegion.union(regions)) + } +} + +extension DatabaseRegionObservation { + /// Starts the observation in the provided database writer (such as + /// a database queue or database pool), and returns a transaction observer. + /// + /// - parameter reader: A DatabaseWriter. + /// - parameter onChange: A closure that is provided a database connection + /// with write access each time the observed region has been modified. + /// - returns: a TransactionObserver + public func start(in dbWriter: DatabaseWriter, onChange: @escaping (Database) -> Void) throws -> TransactionObserver { + // Use unsafeReentrantWrite so that observation can start from any + // dispatch queue. + return try dbWriter.unsafeReentrantWrite { db -> TransactionObserver in + let region = try observedRegion(db) + let observer = DatabaseRegionObserver(region: region, onChange: onChange) + db.add(transactionObserver: observer, extent: extent) + return observer + } + } +} + +private class DatabaseRegionObserver: TransactionObserver { + let region: DatabaseRegion + let onChange: (Database) -> Void + var isChanged = false + + init(region: DatabaseRegion, onChange: @escaping (Database) -> Void) { + self.region = region + self.onChange = onChange + } + + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { + return region.isModified(byEventsOfKind: eventKind) + } + + func databaseDidChange(with event: DatabaseEvent) { + if region.isModified(by: event) { + isChanged = true + stopObservingDatabaseChangesUntilNextTransaction() + } + } + + func databaseDidCommit(_ db: Database) { + guard isChanged else { return } + isChanged = false + + onChange(db) + } + + func databaseDidRollback(_ db: Database) { + isChanged = false + } +} diff --git a/GRDB/Core/DatabaseSchemaCache.swift b/GRDB/Core/DatabaseSchemaCache.swift index 237db0b97..4f29cef90 100644 --- a/GRDB/Core/DatabaseSchemaCache.swift +++ b/GRDB/Core/DatabaseSchemaCache.swift @@ -2,9 +2,8 @@ protocol DatabaseSchemaCache { mutating func clear() - func canonicalTableName(_ table: String) -> String? - mutating func set(canonicalTableName: String, forTable table: String) - + var schemaInfo: SchemaInfo? { get set } + func primaryKey(_ table: String) -> PrimaryKeyInfo? mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) @@ -20,26 +19,18 @@ protocol DatabaseSchemaCache { /// A thread-unsafe database schema cache struct SimpleDatabaseSchemaCache: DatabaseSchemaCache { - private var canonicalTableNames: [String: String] = [:] + var schemaInfo: SchemaInfo? private var primaryKeys: [String: PrimaryKeyInfo] = [:] private var columns: [String: [ColumnInfo]] = [:] private var indexes: [String: [IndexInfo]] = [:] private var foreignKeys: [String: [ForeignKeyInfo]] = [:] mutating func clear() { - canonicalTableNames = [:] primaryKeys = [:] columns = [:] indexes = [:] foreignKeys = [:] - } - - func canonicalTableName(_ table: String) -> String? { - return canonicalTableNames[table] - } - - mutating func set(canonicalTableName: String, forTable table: String) { - canonicalTableNames[table] = table + schemaInfo = nil } func primaryKey(_ table: String) -> PrimaryKeyInfo? { @@ -79,8 +70,10 @@ struct SimpleDatabaseSchemaCache: DatabaseSchemaCache { struct EmptyDatabaseSchemaCache: DatabaseSchemaCache { func clear() { } - func canonicalTableName(_ table: String) -> String? { return nil } - func set(canonicalTableName: String, forTable table: String) { } + var schemaInfo: SchemaInfo? { + get { return nil } + set { } + } func primaryKey(_ table: String) -> PrimaryKeyInfo? { return nil } func set(primaryKey: PrimaryKeyInfo, forTable table: String) { } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 30f60bef2..5ea57064c 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -14,7 +14,7 @@ public class DatabaseSnapshot : DatabaseReader { return serializedDatabase.configuration } - init(path: String, configuration: Configuration = Configuration(), labelSuffix: String) throws { + init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws { var configuration = configuration configuration.readonly = true configuration.allowsUnsafeTransactions = true // Snaphost keeps a long-lived transaction @@ -23,7 +23,8 @@ public class DatabaseSnapshot : DatabaseReader { path: path, configuration: configuration, schemaCache: SimpleDatabaseSchemaCache(), - label: (configuration.label ?? "GRDB.DatabasePool") + labelSuffix) + defaultLabel: defaultLabel, + purpose: purpose) try serializedDatabase.sync { db in // Assert WAL mode @@ -31,13 +32,7 @@ public class DatabaseSnapshot : DatabaseReader { guard journalMode == "wal" else { throw DatabaseError(message: "WAL mode is not activated at path: \(path)") } - - // Establish snapshot isolation (see deinit) - try db.beginTransaction(.deferred) - - // Take snapshot - // See DatabasePool.concurrentRead for a complete discussion - try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").makeCursor().next() + try db.beginSnapshotIsolation() } } @@ -112,8 +107,7 @@ extension DatabaseSnapshot { // Deal with initial value switch observation.scheduling { case .mainQueue: - var reducer = observation.reducer - if let value = try reducer.value(unsafeReentrantRead(reducer.fetch)) { + if let value = try unsafeReentrantRead(observation.initialValue) { if DispatchQueue.isMain { onChange(value) } else { @@ -124,8 +118,7 @@ extension DatabaseSnapshot { } case let .onQueue(queue, startImmediately: startImmediately): if startImmediately { - var reducer = observation.reducer - if let value = try reducer.value(unsafeReentrantRead(reducer.fetch)) { + if let value = try unsafeReentrantRead(observation.initialValue) { queue.async { onChange(value) } @@ -133,8 +126,7 @@ extension DatabaseSnapshot { } case let .unsafe(startImmediately: startImmediately): if startImmediately { - var reducer = observation.reducer - if let value = try reducer.value(unsafeReentrantRead(reducer.fetch)) { + if let value = try unsafeReentrantRead(observation.initialValue) { onChange(value) } } @@ -149,6 +141,15 @@ extension DatabaseSnapshot { } } +extension ValueObservation where Reducer: ValueReducer { + /// Helper method for DatabaseSnapshot.add(observation:onError:onChange:) + fileprivate func initialValue(_ db: Database) throws -> Reducer.Value? { + var reducer = try makeReducer(db) + let fetched = try reducer.fetch(db) + return reducer.value(fetched) + } +} + /// An observer that does nothing, support for /// `DatabaseSnapshot.add(observation:onError:onChange:)`. private class SnapshotValueObserver: TransactionObserver { diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index c4b6b3966..5dbe867f5 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -129,6 +129,8 @@ extension DatabaseWriter { /// Add a transaction observer, so that it gets notified of /// database changes. /// + /// To remove the observer, use `DatabaseReader.remove(transactionObserver:)`. + /// /// - parameter transactionObserver: A transaction observer. /// - parameter extent: The duration of the observation. The default is /// the observer lifetime (observation lasts until observer @@ -137,6 +139,8 @@ extension DatabaseWriter { writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) } } + /// Default implementation for the DatabaseReader requirement. + /// :nodoc: public func remove(transactionObserver: TransactionObserver) { writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) } } @@ -198,6 +202,8 @@ extension DatabaseWriter { // MARK: - Value Observation + /// Default implementation for the DatabaseReader requirement. + /// :nodoc: public func add( observation: ValueObservation, onError: ((Error) -> Void)?, @@ -215,12 +221,14 @@ extension DatabaseWriter { // Use unsafeReentrantWrite so that observation can start from any // dispatch queue. return try unsafeReentrantWrite { db in + // Create the reducer + var reducer = try observation.makeReducer(db) + // Take care of initial value. Make sure it is dispatched before // any future transaction can trigger a change. - var reducer = observation.reducer switch observation.scheduling { case .mainQueue: - if let value = try reducer.value(observation.fetchInitial(db)) { + if let value = try reducer.initialValue(db, requiresWriteAccess: observation.requiresWriteAccess) { if calledOnMainQueue { startValue = value } else { @@ -229,20 +237,21 @@ extension DatabaseWriter { } case let .onQueue(queue, startImmediately: startImmediately): if startImmediately { - if let value = try reducer.value(observation.fetchInitial(db)) { + if let value = try reducer.initialValue(db, requiresWriteAccess: observation.requiresWriteAccess) { queue.async { onChange(value) } } } case let .unsafe(startImmediately: startImmediately): if startImmediately { - startValue = try reducer.value(observation.fetchInitial(db)) + startValue = try reducer.initialValue(db, requiresWriteAccess: observation.requiresWriteAccess) } } - + // Start observing the database let valueObserver = try ValueObserver( region: observation.observedRegion(db), reducer: reducer, + configuration: db.configuration, fetch: observation.fetchAfterChange(in: self), notificationQueue: observation.notificationQueue, onError: onError, @@ -254,21 +263,23 @@ extension DatabaseWriter { } } -extension ValueObservation where Reducer: ValueReducer { +extension ValueReducer { /// Helper method for DatabaseWriter.add(observation:onError:onChange:) - fileprivate func fetchInitial(_ db: Database) throws -> Reducer.Fetched { + fileprivate mutating func initialValue(_ db: Database, requiresWriteAccess: Bool) throws -> Value? { if requiresWriteAccess { - var fetchedValue: Reducer.Fetched! + var fetchedValue: Fetched! try db.inSavepoint { - fetchedValue = try reducer.fetch(db) + fetchedValue = try fetch(db) return .commit } - return fetchedValue + return value(fetchedValue) } else { - return try db.readOnly { try reducer.fetch(db) } + return try value(db.readOnly { try fetch(db) }) } } - +} + +extension ValueObservation where Reducer: ValueReducer { /// Helper method for DatabaseWriter.add(observation:onError:onChange:) fileprivate func fetchAfterChange(in writer: DatabaseWriter) -> (Database, Reducer) -> Future { // The technique to return a future value after database has changed @@ -294,103 +305,6 @@ extension ValueObservation where Reducer: ValueReducer { } } - -/// Support for ValueObservation. -/// See DatabaseWriter.add(observation:onError:onChange:) -private class ValueObserver: TransactionObserver { - private let region: DatabaseRegion - private var reducer: Reducer - private let fetch: (Database, Reducer) -> Future - private let notificationQueue: DispatchQueue? - private let onError: ((Error) -> Void)? - private let onChange: (Reducer.Value) -> Void - private let reduceQueue: DispatchQueue - private var isChanged = false - - init( - region: DatabaseRegion, - reducer: Reducer, - fetch: @escaping (Database, Reducer) -> Future, - notificationQueue: DispatchQueue?, - onError: ((Error) -> Void)?, - onChange: @escaping (Reducer.Value) -> Void) - { - self.region = region - self.reducer = reducer - self.fetch = fetch - self.notificationQueue = notificationQueue - self.onChange = onChange - self.onError = onError - if #available(OSX 10.10, *) { - if let queue = notificationQueue { - self.reduceQueue = DispatchQueue(label: "GRDB.ValueObservation", qos: queue.qos) - } else { - // Assume UI purpose - self.reduceQueue = DispatchQueue(label: "GRDB.ValueObservation", qos: .userInitiated) - } - } else { - self.reduceQueue = DispatchQueue(label: "GRDB.ValueObservation") - } - } - - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - return region.isModified(byEventsOfKind: eventKind) - } - - func databaseDidChange(with event: DatabaseEvent) { - if region.isModified(by: event) { - isChanged = true - stopObservingDatabaseChangesUntilNextTransaction() - } - } - - func databaseDidCommit(_ db: Database) { - guard isChanged else { return } - isChanged = false - - // Grab future fetched values from the database writer queue - let future = fetch(db, reducer) - - // Wait for future fetched values 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 { [weak self] in - guard let strongSelf = self else { return } - - do { - if let value = try strongSelf.reducer.value(future.wait()) { - if let queue = strongSelf.notificationQueue { - queue.async { - guard let strongSelf = self else { return } - strongSelf.onChange(value) - } - } else { - strongSelf.onChange(value) - } - } - } catch { - guard strongSelf.onError != nil else { - // TODO: how can we let the user know about the error? - return - } - if let queue = strongSelf.notificationQueue { - queue.async { - guard let strongSelf = self else { return } - strongSelf.onError?(error) - } - } else { - strongSelf.onError?(error) - } - } - } - } - - func databaseDidRollback(_ db: Database) { - isChanged = false - } -} - /// A future value. public class Future { private var consumed = false diff --git a/GRDB/Core/SchedulingWatchdog.swift b/GRDB/Core/SchedulingWatchdog.swift index f7e83e13f..165abfb05 100644 --- a/GRDB/Core/SchedulingWatchdog.swift +++ b/GRDB/Core/SchedulingWatchdog.swift @@ -22,7 +22,7 @@ import Dispatch /// - preconditionValidQueue() crashes whenever a database is used in an invalid /// dispatch queue. final class SchedulingWatchdog { - private static let specificKey = DispatchSpecificKey() + private static let watchDogKey = DispatchSpecificKey() private(set) var allowedDatabases: [Database] var databaseObservationBroker: DatabaseObservationBroker? @@ -30,11 +30,10 @@ final class SchedulingWatchdog { allowedDatabases = [database] } - static func makeSerializedQueue(allowingDatabase database: Database, label: String) -> DispatchQueue { - let queue = DispatchQueue(label: label) + static func allowDatabase(_ database: Database, onQueue queue: DispatchQueue) { + precondition(queue.getSpecific(key: watchDogKey) == nil) let watchdog = SchedulingWatchdog(allowedDatabase: database) - queue.setSpecific(key: specificKey, value: watchdog) - return queue + queue.setSpecific(key: watchDogKey, value: watchdog) } func inheritingAllowedDatabases(from other: SchedulingWatchdog, execute body: () throws -> T) rethrows -> T { @@ -49,7 +48,7 @@ final class SchedulingWatchdog { } static var current: SchedulingWatchdog? { - return DispatchQueue.getSpecific(key: specificKey) + return DispatchQueue.getSpecific(key: watchDogKey) } func allows(_ db: Database) -> Bool { diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 9efa3762f..2a804e965 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -16,7 +16,7 @@ final class SerializedDatabase { /// The dispatch queue private let queue: DispatchQueue - init(path: String, configuration: Configuration = Configuration(), schemaCache: DatabaseSchemaCache, label: String) throws { + init(path: String, configuration: Configuration = Configuration(), schemaCache: DatabaseSchemaCache, defaultLabel: String, purpose: String? = nil) throws { // According to https://www.sqlite.org/threadsafe.html // // > SQLite support three different threading modes: @@ -37,9 +37,10 @@ final class SerializedDatabase { var config = configuration config.threadingMode = .multiThread - db = try Database(path: path, configuration: config, schemaCache: schemaCache) - queue = SchedulingWatchdog.makeSerializedQueue(allowingDatabase: db, label: label) self.path = path + self.db = try Database(path: path, configuration: config, schemaCache: schemaCache) + self.queue = configuration.makeDispatchQueue(defaultLabel: defaultLabel, purpose: purpose) + SchedulingWatchdog.allowDatabase(db, onQueue: queue) try queue.sync { try db.setup() } diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index 7a2750e43..0c9957878 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -49,18 +49,18 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { switch actionCode { case SQLITE_DROP_TABLE, SQLITE_DROP_VTABLE, SQLITE_DROP_TEMP_TABLE, - SQLITE_DROP_INDEX, SQLITE_DROP_TEMP_INDEX: + SQLITE_DROP_INDEX, SQLITE_DROP_TEMP_INDEX, + SQLITE_DROP_VIEW, SQLITE_DROP_TEMP_VIEW, + SQLITE_DROP_TRIGGER, SQLITE_DROP_TEMP_TRIGGER: isDropStatement = true invalidatesDatabaseSchemaCache = true return SQLITE_OK - case SQLITE_DROP_VIEW, SQLITE_DROP_TEMP_VIEW, - SQLITE_DROP_TRIGGER, SQLITE_CREATE_TEMP_TRIGGER: - isDropStatement = true - return SQLITE_OK - - case SQLITE_DETACH, SQLITE_ALTER_TABLE, - SQLITE_CREATE_INDEX, SQLITE_CREATE_TEMP_INDEX: + case SQLITE_ALTER_TABLE, SQLITE_DETACH, + SQLITE_CREATE_INDEX, SQLITE_CREATE_TABLE, + SQLITE_CREATE_TEMP_INDEX, SQLITE_CREATE_TEMP_TABLE, + SQLITE_CREATE_TEMP_TRIGGER, SQLITE_CREATE_TEMP_VIEW, + SQLITE_CREATE_TRIGGER, SQLITE_CREATE_VIEW: invalidatesDatabaseSchemaCache = true return SQLITE_OK diff --git a/GRDB/Core/ValueObservation.swift b/GRDB/Core/ValueObservation.swift deleted file mode 100644 index e777c96f6..000000000 --- a/GRDB/Core/ValueObservation.swift +++ /dev/null @@ -1,919 +0,0 @@ -// -// ValueObservation.swift -// GRDB -// -// Created by Gwendal Roué on 23/10/2018. -// Copyright © 2018 Gwendal Roué. All rights reserved. -// - -import Dispatch - -// MARK: - ValueScheduling - -/// ValueScheduling controls how ValueObservation schedules the notifications -/// of fresh values to your application. -public enum ValueScheduling { - /// All values are notified on the main queue. - /// - /// If the observation starts on the main queue, an initial value is - /// notified right upon subscription, synchronously: - /// - /// // On main queue - /// let observation = ValueObservation.trackingAll(Player.all()) - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("fresh players: \(players)") - /// } - /// // <- here "fresh players" is already printed. - /// - /// If the observation does not start on the main queue, an initial value - /// is also notified on the main queue, but asynchronously: - /// - /// // Not on the main queue: "fresh players" is eventually printed - /// // on the main queue. - /// let observation = ValueObservation.trackingAll(Player.all()) - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("fresh players: \(players)") - /// } - /// - /// When the database changes, fresh values are asynchronously notified on - /// the main queue: - /// - /// // Eventually prints "fresh players" on the main queue - /// try dbQueue.write { db in - /// try Player(...).insert(db) - /// } - case mainQueue - - /// All values are asychronously notified on the specified queue. - /// - /// An initial value is fetched and notified if `startImmediately` - /// is true. - case onQueue(DispatchQueue, startImmediately: Bool) - - /// Values are not all notified on the same dispatch queue. - /// - /// If `startImmediately` is true, an initial value is notified right upon - /// subscription, synchronously, on the dispatch queue which starts - /// the observation. - /// - /// // On any queue - /// var observation = ValueObservation.trackingAll(Player.all()) - /// observation.scheduling = .unsafe(startImmediately: true) - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("fresh players: \(players)") - /// } - /// // <- here "fresh players" is already printed. - /// - /// When the database changes, other values are notified on - /// unspecified queues. - case unsafe(startImmediately: Bool) -} - -extension DispatchQueue { - private static var mainKey: DispatchSpecificKey<()> = { - let key = DispatchSpecificKey<()>() - DispatchQueue.main.setSpecific(key: key, value: ()) - return key - }() - - static var isMain: Bool { - return DispatchQueue.getSpecific(key: mainKey) != nil - } -} - -// MARK: - ValueReducer - -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// The ValueReducer protocol supports ValueObservation. -public protocol ValueReducer { - /// The type of fetched database values - associatedtype Fetched - - /// The type of observed values - associatedtype Value - - /// Feches database values upon changes in an observed database region. - func fetch(_ db: Database) throws -> Fetched - - /// Transforms a fetched value into an eventual observed value. Returns nil - /// when observer should not be notified. - /// - /// This method runs inside a private dispatch queue. - mutating func value(_ fetched: Fetched) -> Value? -} - -extension ValueReducer { - /// Returns a reducer which transforms the values returned by this reducer. - public func map(_ transform: @escaping (Value) -> T?) -> MapValueReducer { - return MapValueReducer(self, transform) - } -} - -/// A ValueReducer whose values consist of those in a Base ValueReducer passed -/// through a transform function. -/// -/// See ValueReducer.map(_:) -/// -/// :nodoc: -public struct MapValueReducer: ValueReducer { - private var base: Base - private let transform: (Base.Value) -> T? - - init(_ base: Base, _ transform: @escaping (Base.Value) -> T?) { - self.base = base - self.transform = transform - } - - public func fetch(_ db: Database) throws -> Base.Fetched { - return try base.fetch(db) - } - - public mutating func value(_ fetched: Base.Fetched) -> T? { - guard let value = base.value(fetched) else { return nil } - return transform(value) - } -} - -/// A type-erased ValueReducer. -/// -/// An AnyValueReducer forwards its operations to an underlying reducer, -/// hiding its specifics. -public struct AnyValueReducer: ValueReducer { - private var _fetch: (Database) throws -> Fetched - private var _value: (Fetched) -> Value? - - /// Creates a reducer whose `fetch(_:)` and `value(_:)` methods wrap and - /// forward operations the argument closures. - /// - /// For example, this reducer counts the number of a times the player table - /// is modified: - /// - /// var count = 0 - /// let reducer = AnyValueReducer( - /// fetch: { _ in }, - /// value: { _ -> Int? in - /// count += 1 - /// return count - /// }) - /// let observer = ValueObservation - /// .tracking(Player.all(), reducer: reducer) - /// .start(in: dbQueue) { count: Int in - /// print("Players have been modified \(count) times.") - /// } - public init(fetch: @escaping (Database) throws -> Fetched, value: @escaping (Fetched) -> Value?) { - self._fetch = fetch - self._value = value - } - - /// Creates a reducer that wraps and forwards operations to `reducer`. - public init(_ reducer: Base) where Base.Fetched == Fetched, Base.Value == Value { - var reducer = reducer - self._fetch = { try reducer.fetch($0) } - self._value = { reducer.value($0) } - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> Fetched { - return try _fetch(db) - } - - /// :nodoc: - public func value(_ fetched: Fetched) -> Value? { - return _value(fetched) - } -} - -public enum ValueReducers { - /// A reducer which outputs raw database values, without any processing. - public struct Raw: ValueReducer { - private let _fetch: (Database) throws -> Value - - init(_ fetch: @escaping (Database) throws -> Value) { - self._fetch = fetch - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> Value { - return try _fetch(db) - } - - /// :nodoc: - public func value(_ fetched: Value) -> Value? { - return fetched - } - } - - /// A reducer which outputs raw database values, filtering out consecutive - /// values that are equal. - public struct Distinct: ValueReducer { - private let _fetch: (Database) throws -> Value - private var previousValue: Value?? - - init(_ fetch: @escaping (Database) throws -> Value) { - self._fetch = fetch - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> Value { - return try _fetch(db) - } - - /// :nodoc: - public mutating func value(_ value: Value) -> Value? { - if let previousValue = previousValue, previousValue == value { - // Don't notify consecutive identical values - return nil - } - self.previousValue = value - return value - } - } - - /// A reducer which outputs arrays of records, filtering out consecutive - /// identical database rows. - public struct Records: ValueReducer { - private let _fetch: (Database) throws -> [Row] - private var previousRows: [Row]? - - init(_ fetch: @escaping (Database) throws -> [Row]) { - self._fetch = fetch - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> [Row] { - return try _fetch(db) - } - - /// :nodoc: - public mutating func value(_ rows: [Row]) -> [Record]? { - if let previousRows = previousRows, previousRows == rows { - // Don't notify consecutive identical row arrays - return nil - } - self.previousRows = rows - return rows.map(Record.init(row:)) - } - } - - /// A reducer which outputs optional records, filtering out consecutive - /// identical database rows. - public struct Record: ValueReducer { - private let _fetch: (Database) throws -> Row? - private var previousRow: Row?? - - init(_ fetch: @escaping (Database) throws -> Row?) { - self._fetch = fetch - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> Row? { - return try _fetch(db) - } - - /// :nodoc: - public mutating func value(_ row: Row?) -> Record?? { - if let previousRow = previousRow, previousRow == row { - // Don't notify consecutive identical rows - return nil - } - self.previousRow = row - return .some(row.map(Record.init(row:))) - } - } - - /// A reducer which outputs arrays of values, filtering out consecutive - /// identical database values. - public struct Values: ValueReducer { - private let _fetch: (Database) throws -> [DatabaseValue] - private var previousDbValues: [DatabaseValue]? - - init(_ fetch: @escaping (Database) throws -> [DatabaseValue]) { - self._fetch = fetch - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> [DatabaseValue] { - return try _fetch(db) - } - - /// :nodoc: - public mutating func value(_ dbValues: [DatabaseValue]) -> [T]? { - if let previousDbValues = previousDbValues, previousDbValues == dbValues { - // Don't notify consecutive identical dbValue arrays - return nil - } - self.previousDbValues = dbValues - return dbValues.map { - T.decode(from: $0, conversionContext: nil) - } - } - } - - /// A reducer which outputs optional values, filtering out consecutive - /// identical database values. - public struct Value: ValueReducer { - private let _fetch: (Database) throws -> DatabaseValue? - private var previousDbValue: DatabaseValue?? - private var previousValueWasNil = false - - init(_ fetch: @escaping (Database) throws -> DatabaseValue?) { - self._fetch = fetch - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> DatabaseValue? { - return try _fetch(db) - } - - /// :nodoc: - public mutating func value(_ dbValue: DatabaseValue?) -> T?? { - if let previousDbValue = previousDbValue, previousDbValue == dbValue { - // Don't notify consecutive identical dbValue - return nil - } - self.previousDbValue = dbValue - if let dbValue = dbValue, - let value = T.decodeIfPresent(from: dbValue, conversionContext: nil) - { - previousValueWasNil = false - return .some(value) - } else if previousValueWasNil { - // Don't notify consecutive nil values - return nil - } else { - previousValueWasNil = true - return .some(nil) - } - } - } - - /// A reducer which outputs arrays of optional values, filtering out consecutive - /// identical database values. - public struct OptionalValues: ValueReducer { - private let _fetch: (Database) throws -> [DatabaseValue] - private var previousDbValues: [DatabaseValue]? - - init(_ fetch: @escaping (Database) throws -> [DatabaseValue]) { - self._fetch = fetch - } - - /// :nodoc: - public func fetch(_ db: Database) throws -> [DatabaseValue] { - return try _fetch(db) - } - - /// :nodoc: - public mutating func value(_ dbValues: [DatabaseValue]) -> [T?]? { - if let previousDbValues = previousDbValues, previousDbValues == dbValues { - // Don't notify consecutive identical dbValue arrays - return nil - } - self.previousDbValues = dbValues - return dbValues.map { - T.decodeIfPresent(from: $0, conversionContext: nil) - } - } - } -} - -// MARK: - ValueObservation - -/// ValueObservation tracks changes in the results of database requests, and -/// notifies fresh values whenever the database changes. -/// -/// For example: -/// -/// let observation = ValueObservation.trackingAll(Player.all) -/// let observer = try observation.start(in: dbQueue) { players: [Player] in -/// print("Players have changed.") -/// } -public struct ValueObservation { - /// A closure that is evaluated when the observation starts, and returns - /// the observed database region. - var observedRegion: (Database) throws -> DatabaseRegion - - /// The reducer is triggered upon each database change in *observedRegion*. - var reducer: 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. - /// - /// Don't set this flag to true unless you really need it. A read/write - /// observation is less efficient than a read-only observation. - public var requiresWriteAccess: Bool = false - - /// The extent of the database observation. The default is - /// `.observerLifetime`: the observation lasts until the - /// observer returned by the `start(in:onError:onChange:)` method - /// is deallocated. - public var extent = Database.TransactionObservationExtent.observerLifetime - - /// `scheduling` controls how fresh values are notified. Default - /// is `.mainQueue`. - /// - /// - `.mainQueue`: all values are notified on the main queue. - /// - /// If the observation starts on the main queue, an initial value is - /// notified right upon subscription, synchronously:: - /// - /// // On main queue - /// let observation = ValueObservation.trackingAll(Player.all()) - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("fresh players: \(players)") - /// } - /// // <- here "fresh players" is already printed. - /// - /// If the observation does not start on the main queue, an initial - /// value is also notified on the main queue, but asynchronously: - /// - /// // Not on the main queue: "fresh players" is eventually printed - /// // on the main queue. - /// let observation = ValueObservation.trackingAll(Player.all()) - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("fresh players: \(players)") - /// } - /// - /// When the database changes, fresh values are asynchronously notified: - /// - /// // Eventually prints "fresh players" on the main queue - /// try dbQueue.write { db in - /// try Player(...).insert(db) - /// } - /// - /// - `.onQueue(_:startImmediately:)`: all values are asychronously notified - /// on the specified queue. - /// - /// An initial value is fetched and notified if `startImmediately` - /// is true. - /// - /// - `unsafe(startImmediately:)`: values are not all notified on the same - /// dispatch queue. - /// - /// If `startImmediately` is true, an initial value is notified right - /// upon subscription, synchronously, on the dispatch queue which starts - /// the observation. - /// - /// // On any queue - /// var observation = ValueObservation.trackingAll(Player.all()) - /// observation.scheduling = .unsafe(startImmediately: true) - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("fresh players: \(players)") - /// } - /// // <- here "fresh players" is already printed. - /// - /// When the database changes, other values are notified on - /// unspecified queues. - public var scheduling: ValueScheduling = .mainQueue - - /// The dispatch queue where change callbacks are called. - var notificationQueue: DispatchQueue? { - switch scheduling { - case .mainQueue: - return DispatchQueue.main - case .onQueue(let queue, startImmediately: _): - return queue - case .unsafe: - return nil - } - } - - // Not public. See ValueObservation.tracking(_:reducer:) - init( - tracking region: @escaping (Database) throws -> DatabaseRegion, - reducer: Reducer) - { - self.observedRegion = region - self.reducer = reducer - } - - /// Returs a ValueObservation which observes *regions*, and notifies the - /// values returned by the *reducer* whenever one of the observed - /// regions is modified by a database transaction. - /// - /// This method is the most fundamental way to create a ValueObservation. - /// - /// For example, this observation counts the number of a times the player - /// table is modified: - /// - /// var count = 0 - /// let reducer = AnyValueReducer( - /// fetch: { _ in }, - /// value: { _ -> Int? in - /// count += 1 - /// return count - /// }) - /// let observation = ValueObservation.tracking(Player.all(), reducer: reducer) - /// let observer = observation.start(in: dbQueue) { count: Int in - /// print("Players have been modified \(count) times.") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter regions: A list of observed regions. - /// - parameter reducer: A reducer that turns database changes in the - /// modified regions into fresh values. Currently only reducers that adopt - /// the ValueReducer protocol are supported. - public static func tracking( - _ regions: DatabaseRegionConvertible..., - reducer: Reducer) - -> ValueObservation - { - return ValueObservation(tracking: union(regions), reducer: reducer) - } -} - -extension ValueObservation where Reducer: ValueReducer { - /// Returns a ValueObservation which transforms the values returned by - /// this ValueObservation. - public func map(_ transform: @escaping (Reducer.Value) -> T) - -> ValueObservation> - { - return ValueObservation>( - tracking: observedRegion, - reducer: reducer.map(transform)) - } -} - -extension ValueObservation where Reducer == Void { - /// Creates a ValueObservation which observes *regions*, and notifies the - /// values returned by the *fetch* closure whenever one of the observed - /// regions is modified by a database transaction. - /// - /// For example: - /// - /// let observation = ValueObservation.tracking( - /// Player.all(), - /// fetch: { db in return try Player.fetchAll(db) }) - /// - /// let observer = try observation.start(in: dbQueue) { player: [Player] in - /// print("Players have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter regions: A list of observed regions. - /// - parameter fetch: A closure that fetches a value. - public static func tracking( - _ regions: DatabaseRegionConvertible..., - fetch: @escaping (Database) throws -> Value) - -> ValueObservation> - { - return ValueObservation>( - tracking: union(regions), - reducer: ValueReducers.Raw(fetch)) - } - - /// Creates a ValueObservation which observes *regions*, and notifies the - /// values returned by the *fetch* closure whenever one of the observed - /// regions is modified by a database transaction. Consecutive equal values - /// are filtered out. - /// - /// For example: - /// - /// let observation = ValueObservation.tracking( - /// Player.all(), - /// fetchDistinct: { db in return try Player.fetchAll(db) }) - /// - /// let observer = try observation.start(in: dbQueue) { player: [Player] in - /// print("Players have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter regions: A list of observed regions. - /// - parameter fetch: A closure that fetches a value. - public static func tracking( - _ regions: DatabaseRegionConvertible..., - fetchDistinct fetch: @escaping (Database) throws -> Value) - -> ValueObservation> - where Value: Equatable - { - return ValueObservation>( - tracking: union(regions), - reducer: ValueReducers.Distinct(fetch)) - } -} - -private func union(_ regions: [DatabaseRegionConvertible]) -> (Database) throws -> DatabaseRegion { - return { db in - try regions.reduce(into: DatabaseRegion()) { union, region in - try union.formUnion(region.databaseRegion(db)) - } - } -} - -// MARK: - Starting Observation - -extension ValueObservation where Reducer: ValueReducer { - /// Starts the value observation in the provided database reader (such as - /// a database queue or database pool), and returns a transaction observer. - /// - /// - parameter reader: A DatabaseReader. - /// - parameter onError: A closure that is provided eventual errors that - /// happen during observation - /// - parameter onChange: A closure that is provided fresh values - /// - returns: a TransactionObserver - public func start( - in reader: DatabaseReader, - onError: ((Error) -> Void)? = nil, - onChange: @escaping (Reducer.Value) -> Void) throws -> TransactionObserver - { - return try reader.add(observation: self, onError: onError, onChange: onChange) - } -} - -// MARK: - Count Observation - -extension ValueObservation where Reducer == Void { - /// Creates a ValueObservation which observes *request*, and notifies its - /// count whenever it is modified by a database transaction. - /// - /// For example: - /// - /// let request = Player.all() - /// let observation = ValueObservation.trackingCount(request) - /// - /// let observer = try observation.start(in: dbQueue) { count: Int in - /// print("Number of players has changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - public static func trackingCount(_ request: Request) - -> ValueObservation> - { - return ValueObservation.tracking(request, fetchDistinct: request.fetchCount) - } -} - -// MARK: - Row Observation - -extension ValueObservation where Reducer == Void { - /// Creates a ValueObservation which observes *request*, and notifies - /// fresh rows whenever the request is modified by a database transaction. - /// - /// For example: - /// - /// let request = SQLRequest("SELECT * FROM player") - /// let observation = ValueObservation.trackingAll(request) - /// - /// let observer = try observation.start(in: dbQueue) { rows: [Row] in - /// print("Players have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - public static func trackingAll(_ request: Request) - -> ValueObservation> - where Request.RowDecoder == Row - { - return ValueObservation.tracking(request, fetchDistinct: request.fetchAll) - } - - /// Creates a ValueObservation which observes *request*, and notifies a - /// fresh row whenever the request is modified by a database transaction. - /// - /// For example: - /// - /// let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1]) - /// let observation = ValueObservation.trackingOne(request) - /// - /// let observer = try observation.start(in: dbQueue) { row: Row? in - /// print("Players have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - public static func trackingOne(_ request: Request) - -> ValueObservation> - where Request.RowDecoder == Row - { - return ValueObservation.tracking(request, fetchDistinct: request.fetchOne) - } -} - -// MARK: - FetchableRecord Observation - -extension ValueObservation where Reducer == Void { - /// Creates a ValueObservation which observes *request*, and notifies - /// fresh records whenever the request is modified by a - /// database transaction. - /// - /// For example: - /// - /// let request = Player.all() - /// let observation = ValueObservation.trackingAll(request) - /// - /// let observer = try observation.start(in: dbQueue) { players: [Player] in - /// print("Players have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - public static func trackingAll(_ request: Request) - -> ValueObservation> - where Request.RowDecoder: FetchableRecord - { - return ValueObservation>.tracking( - request, - reducer: ValueReducers.Records { try Row.fetchAll($0, request) }) - } - - /// Creates a ValueObservation which observes *request*, and notifies a - /// fresh record whenever the request is modified by a database transaction. - /// - /// For example: - /// - /// let request = Player.filter(key: 1) - /// let observation = ValueObservation.trackingOne(request) - /// - /// let observer = try observation.start(in: dbQueue) { player: Player? in - /// print("Player has changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - public static func trackingOne(_ request: Request) -> - ValueObservation> - where Request.RowDecoder: FetchableRecord - { - return ValueObservation>.tracking( - request, - reducer: ValueReducers.Record { try Row.fetchOne($0, request) }) - } -} - -// MARK: - DatabaseValueConvertible Observation - -extension ValueObservation where Reducer == Void { - /// Creates a ValueObservation which observes *request*, and notifies - /// fresh values whenever the request is modified by a - /// database transaction. - /// - /// For example: - /// - /// let request = Player.select(Column("name"), as: String.self) - /// let observation = ValueObservation.trackingAll(request) - /// - /// let observer = try observation.start(in: dbQueue) { names: [String] in - /// print("Player names have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - public static func trackingAll(_ request: Request) - -> ValueObservation> - where Request.RowDecoder: DatabaseValueConvertible - { - return ValueObservation>.tracking( - request, - reducer: ValueReducers.Values { try DatabaseValue.fetchAll($0, request) }) - } - - /// Creates a ValueObservation which observes *request*, and notifies a - /// fresh value whenever the request is modified by a database transaction. - /// - /// For example: - /// - /// let request = Player.select(max(Column("score")), as: Int.self) - /// let observation = ValueObservation.trackingOne(request) - /// - /// let observer = try observation.start(in: dbQueue) { maxScore: Int? in - /// print("Maximum score has changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - public static func trackingOne(_ request: Request) - -> ValueObservation> - where Request.RowDecoder: DatabaseValueConvertible - { - return ValueObservation>.tracking( - request, - reducer: ValueReducers.Value { try DatabaseValue.fetchOne($0, request) }) - } -} - -// MARK: - Optional DatabaseValueConvertible Observation - -extension ValueObservation where Reducer == Void { - /// Creates a ValueObservation which observes *request*, and notifies - /// fresh values whenever the request is modified by a - /// database transaction. - /// - /// For example: - /// - /// let request = Player.select(Column("name"), as: Optional.self) - /// let observation = ValueObservation.trackingAll(request) - /// - /// let observer = try observation.start(in: dbQueue) { names: [String?] in - /// print("Player names have changed") - /// } - /// - /// The returned observation has the default configuration: - /// - /// - When started with the `start(in:onError:onChange:)` method, a fresh - /// value is immediately notified on the main queue. - /// - Upon subsequent database changes, fresh values are notified on the - /// main queue. - /// - The observation lasts until the observer returned by - /// `start` is deallocated. - /// - /// - parameter request: the observed request. - /// - returns: a ValueObservation. - public static func trackingAll(_ request: Request) - -> ValueObservation> - where Request.RowDecoder: _OptionalProtocol, - Request.RowDecoder._Wrapped: DatabaseValueConvertible - { - return ValueObservation>.tracking( - request, - reducer: ValueReducers.OptionalValues { try DatabaseValue.fetchAll($0, request) }) - } -} diff --git a/GRDB/QueryInterface/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Association/AssociationAggregate.swift index 6b4ce2bc7..faeb31476 100644 --- a/GRDB/QueryInterface/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Association/AssociationAggregate.swift @@ -1,11 +1,3 @@ -// -// AssociationAggregate.swift -// GRDB -// -// Created by Gwendal Roué on 30/09/2018. -// Copyright © 2018 Gwendal Roué. All rights reserved. -// - import Foundation /// An AssociationAggregate is able to compute aggregated values from a diff --git a/GRDB/QueryInterface/TableDefinition.swift b/GRDB/QueryInterface/TableDefinition.swift index ca8b231df..41fefb83c 100644 --- a/GRDB/QueryInterface/TableDefinition.swift +++ b/GRDB/QueryInterface/TableDefinition.swift @@ -216,6 +216,30 @@ extension Database { public func drop(index name: String) throws { try execute("DROP INDEX \(name.quotedDatabaseIdentifier)") } + + /// Delete and recreate from scratch all indices that use this collation. + /// + /// This method is useful when the definition of a collation sequence + /// has changed. + /// + /// See https://www.sqlite.org/lang_reindex.html + /// + /// - throws: A DatabaseError whenever an SQLite error occurs. + public func reindex(collation: Database.CollationName) throws { + try execute("REINDEX \(collation.rawValue)") + } + + /// Delete and recreate from scratch all indices that use this collation. + /// + /// This method is useful when the definition of a collation sequence + /// has changed. + /// + /// See https://www.sqlite.org/lang_reindex.html + /// + /// - throws: A DatabaseError whenever an SQLite error occurs. + public func reindex(collation: DatabaseCollation) throws { + try reindex(collation: Database.CollationName(collation.name)) + } } /// The TableDefinition class lets you define table columns and constraints. diff --git a/GRDB/Record/PersistableRecord+Encodable.swift b/GRDB/Record/PersistableRecord+Encodable.swift index 7533695dc..b3abf3782 100644 --- a/GRDB/Record/PersistableRecord+Encodable.swift +++ b/GRDB/Record/PersistableRecord+Encodable.swift @@ -140,6 +140,10 @@ private class RecordEncoder: Encoder { // error happens, we'll switch to JSON encoding. let encoder = ColumnEncoder(recordEncoder: self, key: key) try value.encode(to: encoder) + if encoder.requiresJSON { + // Here we handle empty arrays and dictionaries. + throw JSONRequiredError() + } } catch is JSONRequiredError { // Encode to JSON let jsonData = try Record.databaseJSONEncoder(for: key.stringValue).encode(value) @@ -159,11 +163,12 @@ private class RecordEncoder: Encoder { // MARK: - ColumnEncoder /// The encoder that encodes into a database column -private struct ColumnEncoder: Encoder { +private class ColumnEncoder: Encoder { var recordEncoder: RecordEncoder var key: CodingKey var codingPath: [CodingKey] { return [key] } var userInfo: [CodingUserInfoKey: Any] { return Record.databaseEncodingUserInfo } + var requiresJSON = false init(recordEncoder: RecordEncoder, key: CodingKey) { self.recordEncoder = recordEncoder @@ -174,6 +179,7 @@ private struct ColumnEncoder: Encoder { // Keyed values require JSON encoding: we need to throw // JSONRequiredError. Since we can't throw right from here, let's // delegate the job to a dedicated container. + requiresJSON = true let container = JSONRequiredEncoder.KeyedContainer(codingPath: codingPath) return KeyedEncodingContainer(container) } @@ -182,6 +188,7 @@ private struct ColumnEncoder: Encoder { // Keyed values require JSON encoding: we need to throw // JSONRequiredError. Since we can't throw right from here, let's // delegate the job to a dedicated container. + requiresJSON = true return JSONRequiredEncoder(codingPath: codingPath) } diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index 9c4197a91..47a33a7ff 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -521,28 +521,62 @@ extension MutablePersistableRecord { try update(db, columns: Set(columns.map { $0.name })) } - /// If the record has differences from the other record, executes an UPDATE - /// statement so that those changes and only those changes are saved in - /// the database. + /// If the record has any difference from the other record, executes an + /// UPDATE statement so that those differences and only those difference are + /// saved in the database. /// - /// This method is guaranteed to have saved the eventual changes in the + /// This method is guaranteed to have saved the eventual differences in the /// database if it returns without error. /// + /// For example: + /// + /// if let oldPlayer = try Player.fetchOne(db, key: 42) { + /// var newPlayer = oldPlayer + /// newPlayer.score += 10 + /// newPlayer.hasAward = true + /// try newPlayer.updateChanges(db, from: oldRecord) + /// } + /// /// - parameter db: A database connection. - /// - parameter columns: The columns to update. + /// - parameter record: The comparison record. + /// - returns: Whether the record had changes. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database and record could not be updated. + /// - SeeAlso: updateChanges(_:with:) + @discardableResult + public func updateChanges(_ db: Database, from record: MutablePersistableRecord) throws -> Bool { + return try updateChanges(db, from: PersistenceContainer(record)) + } + + /// Mutates the record according to the provided closure, and then, if the + /// record has any difference from its previous version, executes an + /// UPDATE statement so that those differences and only those difference are + /// saved in the database. + /// + /// This method is guaranteed to have saved the eventual differences in the + /// database if it returns without error. + /// + /// For example: + /// + /// if var player = try Player.fetchOne(db, key: 42) { + /// try player.updateChanges(db) { + /// $0.score += 10 + /// $0.hasAward = true + /// } + /// } + /// + /// - parameter db: A database connection. + /// - parameter change: A closure that modifies the record. /// - returns: Whether the record had changes. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database and record could not be updated. @discardableResult - public func updateChanges(_ db: Database, from record: MutablePersistableRecord) throws -> Bool { - let changedColumns = Set(databaseChanges(from: record).keys) - if changedColumns.isEmpty { - return false - } else { - try update(db, columns: changedColumns) - return true - } + public mutating func updateChanges(_ db: Database, with change: (inout Self) throws -> Void) throws -> Bool { + let container = PersistenceContainer(self) + try change(&self) + return try updateChanges(db, from: container) } /// Executes an INSERT or an UPDATE statement so that `self` is saved in @@ -574,7 +608,7 @@ extension MutablePersistableRecord { /// Returns a boolean indicating whether this record and the other record /// have the same database representation. public func databaseEquals(_ record: Self) -> Bool { - return databaseChangesIterator(from: record).next() == nil + return databaseChangesIterator(from: PersistenceContainer(record)).next() == nil } /// A dictionary of values changed from the other record. @@ -586,16 +620,15 @@ extension MutablePersistableRecord { /// same set of columns in their `encode(to:)` method, only the columns /// defined by the receiver record are considered. public func databaseChanges(from record: MutablePersistableRecord) -> [String: DatabaseValue] { - return Dictionary(uniqueKeysWithValues: databaseChangesIterator(from: record)) + return Dictionary(uniqueKeysWithValues: databaseChangesIterator(from: PersistenceContainer(record))) } - fileprivate func databaseChangesIterator(from record: MutablePersistableRecord) -> AnyIterator<(String, DatabaseValue)> { - let oldContainer = PersistenceContainer(record) + private func databaseChangesIterator(from container: PersistenceContainer) -> AnyIterator<(String, DatabaseValue)> { var newValueIterator = PersistenceContainer(self).makeIterator() return AnyIterator { // Loop until we find a change, or exhaust columns: while let (column, newValue) = newValueIterator.next() { - let oldValue = oldContainer[caseInsensitive: column] + let oldValue = container[caseInsensitive: column] let oldDbValue = oldValue?.databaseValue ?? .null let newDbValue = newValue?.databaseValue ?? .null if newDbValue != oldDbValue { @@ -606,6 +639,17 @@ extension MutablePersistableRecord { } } + @discardableResult + fileprivate func updateChanges(_ db: Database, from container: PersistenceContainer) throws -> Bool { + let changes = databaseChangesIterator(from: container) + let changedColumns: Set = changes.reduce(into: []) { $0.insert($1.0) } + if changedColumns.isEmpty { + return false + } + try update(db, columns: changedColumns) + return true + } + // MARK: - CRUD Internals /// Return true if record has a non-null primary key @@ -929,6 +973,36 @@ extension PersistableRecord { try performSave(db) } + /// Mutates the record according to the provided closure, and then, if the + /// record has any difference from its previous version, executes an + /// UPDATE statement so that those differences and only those difference are + /// saved in the database. + /// + /// This method is guaranteed to have saved the eventual differences in the + /// database if it returns without error. + /// + /// For example: + /// + /// if let player = try Player.fetchOne(db, key: 42) { + /// try player.updateChanges(db) { + /// $0.score += 10 + /// $0.hasAward = true + /// } + /// } + /// + /// - parameter db: A database connection. + /// - parameter change: A closure that modifies the record. + /// - returns: Whether the record had changes. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + /// PersistenceError.recordNotFound is thrown if the primary key does not + /// match any row in the database and record could not be updated. + @discardableResult + public func updateChanges(_ db: Database, with change: (Self) throws -> Void) throws -> Bool { + let container = PersistenceContainer(self) + try change(self) + return try updateChanges(db, from: container) + } + // MARK: - Immutable CRUD Internals diff --git a/GRDB/Utils/Inflections.swift b/GRDB/Utils/Inflections.swift index fc19958ec..d5f1f8637 100644 --- a/GRDB/Utils/Inflections.swift +++ b/GRDB/Utils/Inflections.swift @@ -1,11 +1,3 @@ -// -// Inflections.swift -// GRDB -// -// Created by Gwendal Roué on 01/10/2018. -// Copyright © 2018 Gwendal Roué. All rights reserved. -// - import Foundation extension String { diff --git a/GRDB/Utils/OrderedDictionary.swift b/GRDB/Utils/OrderedDictionary.swift index bf00bb3d5..6fc1cfc4b 100644 --- a/GRDB/Utils/OrderedDictionary.swift +++ b/GRDB/Utils/OrderedDictionary.swift @@ -1,11 +1,3 @@ -// -// OrderedDictionary.swift -// GRDB -// -// Created by Gwendal Roué on 29/09/2018. -// Copyright © 2018 Gwendal Roué. All rights reserved. -// - struct OrderedDictionary { private var keys: [Key] private var values: [Key: Value] diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index fa808dca4..484dab35c 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -69,3 +69,15 @@ extension Array { } } } + +extension DispatchQueue { + private static var mainKey: DispatchSpecificKey<()> = { + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + return key + }() + + static var isMain: Bool { + return DispatchQueue.getSpecific(key: mainKey) != nil + } +} diff --git a/GRDB/ValueObservation/ValueObservation+Combine.swift b/GRDB/ValueObservation/ValueObservation+Combine.swift new file mode 100644 index 000000000..da06efc20 --- /dev/null +++ b/GRDB/ValueObservation/ValueObservation+Combine.swift @@ -0,0 +1,273 @@ +extension ValueObservation where Reducer == Void { + public static func combine( + _ o1: ValueObservation, + _ o2: ValueObservation) + -> ValueObservation> + { + return ValueObservation>( + tracking: { try DatabaseRegion.union( + o1.observedRegion($0), + o2.observedRegion($0)) }, + reducer: { try _combine( + o1.makeReducer($0), + o2.makeReducer($0)) }) + } + + public static func combine( + _ o1: ValueObservation, + _ o2: ValueObservation, + _ o3: ValueObservation) + -> ValueObservation> + { + return ValueObservation>( + tracking: { try DatabaseRegion.union( + o1.observedRegion($0), + o2.observedRegion($0), + o3.observedRegion($0)) }, + reducer: { try _combine( + o1.makeReducer($0), + o2.makeReducer($0), + o3.makeReducer($0)) }) + } + + public static func combine( + _ o1: ValueObservation, + _ o2: ValueObservation, + _ o3: ValueObservation, + _ o4: ValueObservation) + -> ValueObservation> + { + return ValueObservation>( + tracking: { try DatabaseRegion.union( + o1.observedRegion($0), + o2.observedRegion($0), + o3.observedRegion($0), + o4.observedRegion($0)) }, + reducer: { try _combine( + o1.makeReducer($0), + o2.makeReducer($0), + o3.makeReducer($0), + o4.makeReducer($0)) }) + } + + public static func combine( + _ o1: ValueObservation, + _ o2: ValueObservation, + _ o3: ValueObservation, + _ o4: ValueObservation, + _ o5: ValueObservation) + -> ValueObservation> + { + return ValueObservation>( + tracking: { try DatabaseRegion.union( + o1.observedRegion($0), + o2.observedRegion($0), + o3.observedRegion($0), + o4.observedRegion($0), + o5.observedRegion($0)) }, + reducer: { try _combine( + o1.makeReducer($0), + o2.makeReducer($0), + o3.makeReducer($0), + o4.makeReducer($0), + o5.makeReducer($0)) }) + } +} + +private func _combine( + _ r1: R1, + _ r2: R2) + -> AnyValueReducer< + (R1.Fetched, R2.Fetched), + (R1.Value, R2.Value)> +{ + var r1 = r1 + var r2 = r2 + var prev1: R1.Value? + var prev2: R2.Value? + func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched) { + return try ( + r1.fetch(db), + r2.fetch(db)) + } + func value(tuple: (R1.Fetched, R2.Fetched)) -> (R1.Value, R2.Value)? { + let v1 = r1.value(tuple.0) + let v2 = r2.value(tuple.1) + defer { + if let v1 = v1 { prev1 = v1 } + if let v2 = v2 { prev2 = v2 } + } + if v1 != nil || v2 != nil, + let c1 = v1 ?? prev1, + let c2 = v2 ?? prev2 + { + return (c1, c2) + } else { + return nil + } + } + return AnyValueReducer(fetch: fetch, value: value) +} + +private func _combine( + _ r1: R1, + _ r2: R2, + _ r3: R3) + -> AnyValueReducer< + (R1.Fetched, R2.Fetched, R3.Fetched), + (R1.Value, R2.Value, R3.Value)> +{ + var r1 = r1 + var r2 = r2 + var r3 = r3 + var prev1: R1.Value? + var prev2: R2.Value? + var prev3: R3.Value? + func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched, R3.Fetched) { + return try ( + r1.fetch(db), + r2.fetch(db), + r3.fetch(db)) + } + func value(tuple: (R1.Fetched, R2.Fetched, R3.Fetched)) -> (R1.Value, R2.Value, R3.Value)? { + let v1 = r1.value(tuple.0) + let v2 = r2.value(tuple.1) + let v3 = r3.value(tuple.2) + defer { + if let v1 = v1 { prev1 = v1 } + if let v2 = v2 { prev2 = v2 } + if let v3 = v3 { prev3 = v3 } + } + if v1 != nil || v2 != nil || v3 != nil, + let c1 = v1 ?? prev1, + let c2 = v2 ?? prev2, + let c3 = v3 ?? prev3 + { + return (c1, c2, c3) + } else { + return nil + } + } + return AnyValueReducer(fetch: fetch, value: value) +} + +private func _combine( + _ r1: R1, + _ r2: R2, + _ r3: R3, + _ r4: R4) + -> AnyValueReducer< + (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched), + (R1.Value, R2.Value, R3.Value, R4.Value)> +{ + var r1 = r1 + var r2 = r2 + var r3 = r3 + var r4 = r4 + var prev1: R1.Value? + var prev2: R2.Value? + var prev3: R3.Value? + var prev4: R4.Value? + func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched) { + return try ( + r1.fetch(db), + r2.fetch(db), + r3.fetch(db), + r4.fetch(db)) + } + func value(tuple: (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched)) -> (R1.Value, R2.Value, R3.Value, R4.Value)? { + let v1 = r1.value(tuple.0) + let v2 = r2.value(tuple.1) + let v3 = r3.value(tuple.2) + let v4 = r4.value(tuple.3) + defer { + if let v1 = v1 { prev1 = v1 } + if let v2 = v2 { prev2 = v2 } + if let v3 = v3 { prev3 = v3 } + if let v4 = v4 { prev4 = v4 } + } + if v1 != nil || v2 != nil || v3 != nil || v4 != nil, + let c1 = v1 ?? prev1, + let c2 = v2 ?? prev2, + let c3 = v3 ?? prev3, + let c4 = v4 ?? prev4 + { + return (c1, c2, c3, c4) + } else { + return nil + } + } + return AnyValueReducer(fetch: fetch, value: value) +} + +private func _combine( + _ r1: R1, + _ r2: R2, + _ r3: R3, + _ r4: R4, + _ r5: R5) + -> AnyValueReducer< + (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched), + (R1.Value, R2.Value, R3.Value, R4.Value, R5.Value)> +{ + var r1 = r1 + var r2 = r2 + var r3 = r3 + var r4 = r4 + var r5 = r5 + var prev1: R1.Value? + var prev2: R2.Value? + var prev3: R3.Value? + var prev4: R4.Value? + var prev5: R5.Value? + func fetch(db: Database) throws -> (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched) { + return try ( + r1.fetch(db), + r2.fetch(db), + r3.fetch(db), + r4.fetch(db), + r5.fetch(db)) + } + func value(tuple: (R1.Fetched, R2.Fetched, R3.Fetched, R4.Fetched, R5.Fetched)) -> (R1.Value, R2.Value, R3.Value, R4.Value, R5.Value)? { + let v1 = r1.value(tuple.0) + let v2 = r2.value(tuple.1) + let v3 = r3.value(tuple.2) + let v4 = r4.value(tuple.3) + let v5 = r5.value(tuple.4) + defer { + if let v1 = v1 { prev1 = v1 } + if let v2 = v2 { prev2 = v2 } + if let v3 = v3 { prev3 = v3 } + if let v4 = v4 { prev4 = v4 } + if let v5 = v5 { prev5 = v5 } + } + if v1 != nil || v2 != nil || v3 != nil || v4 != nil || v5 != nil, + let c1 = v1 ?? prev1, + let c2 = v2 ?? prev2, + let c3 = v3 ?? prev3, + let c4 = v4 ?? prev4, + let c5 = v5 ?? prev5 + { + return (c1, c2, c3, c4, c5) + } else { + return nil + } + } + return AnyValueReducer(fetch: fetch, value: value) +} diff --git a/GRDB/ValueObservation/ValueObservation+CompactMap.swift b/GRDB/ValueObservation/ValueObservation+CompactMap.swift new file mode 100644 index 000000000..5778b5ab5 --- /dev/null +++ b/GRDB/ValueObservation/ValueObservation+CompactMap.swift @@ -0,0 +1,44 @@ +extension ValueObservation where Reducer: ValueReducer { + /// Returns a ValueObservation which notifies the non-nil results of calling + /// the given transformation which each element notified by this + /// value observation. + public func compactMap(_ transform: @escaping (Reducer.Value) -> T?) + -> ValueObservation> + { + return mapReducer { $1.compactMap(transform) } + } +} + +extension ValueReducer { + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// Returns a reducer which outputs the non-nil results of calling the given + /// transformation which each element emitted by this reducer. + public func compactMap(_ transform: @escaping (Value) -> T?) -> CompactMapValueReducer { + return CompactMapValueReducer(self, transform) + } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// See ValueReducer.compactMap(_:) +/// +/// :nodoc: +public struct CompactMapValueReducer: ValueReducer { + private var base: Base + private let transform: (Base.Value) -> T? + + init(_ base: Base, _ transform: @escaping (Base.Value) -> T?) { + self.base = base + self.transform = transform + } + + public func fetch(_ db: Database) throws -> Base.Fetched { + return try base.fetch(db) + } + + public mutating func value(_ fetched: Base.Fetched) -> T? { + guard let value = base.value(fetched) else { return nil } + return transform(value) + } +} diff --git a/GRDB/ValueObservation/ValueObservation+Count.swift b/GRDB/ValueObservation/ValueObservation+Count.swift new file mode 100644 index 000000000..a702fc933 --- /dev/null +++ b/GRDB/ValueObservation/ValueObservation+Count.swift @@ -0,0 +1,34 @@ +extension ValueObservation where Reducer == Void { + + // MARK: - Count Observation + + /// Creates a ValueObservation which observes *request*, and notifies its + /// count whenever it is modified by a database transaction. + /// + /// For example: + /// + /// let request = Player.all() + /// let observation = ValueObservation.trackingCount(request) + /// + /// let observer = try observation.start(in: dbQueue) { count: Int in + /// print("Number of players has changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter request: the observed request. + /// - returns: a ValueObservation. + public static func trackingCount(_ request: Request) + -> ValueObservation>> + { + // TODO: Remove distinctUntilChanged in GRDB 4 + return ValueObservation.tracking(request, fetch: request.fetchCount).distinctUntilChanged() + } +} diff --git a/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift new file mode 100644 index 000000000..de4b240d6 --- /dev/null +++ b/GRDB/ValueObservation/ValueObservation+DatabaseValueConvertible.swift @@ -0,0 +1,214 @@ +extension ValueObservation where Reducer == Void { + + // MARK: - DatabaseValueConvertible Observation + + /// Creates a ValueObservation which observes *request*, and notifies + /// fresh values whenever the request is modified by a + /// database transaction. + /// + /// For example: + /// + /// let request = Player.select(Column("name"), as: String.self) + /// let observation = ValueObservation.trackingAll(request) + /// + /// let observer = try observation.start(in: dbQueue) { names: [String] in + /// print("Player names have changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter request: the observed request. + /// - returns: a ValueObservation. + public static func trackingAll(_ request: Request) + -> ValueObservation> + where Request.RowDecoder: DatabaseValueConvertible + { + return ValueObservation>.tracking(request, reducer: { _ in + DatabaseValuesReducer(request: request) } + ) + } + + /// Creates a ValueObservation which observes *request*, and notifies a + /// fresh value whenever the request is modified by a database transaction. + /// + /// For example: + /// + /// let request = Player.select(max(Column("score")), as: Int.self) + /// let observation = ValueObservation.trackingOne(request) + /// + /// let observer = try observation.start(in: dbQueue) { maxScore: Int? in + /// print("Maximum score has changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter request: the observed request. + /// - returns: a ValueObservation. + public static func trackingOne(_ request: Request) + -> ValueObservation> + where Request.RowDecoder: DatabaseValueConvertible + { + return ValueObservation>.tracking(request, reducer: { _ in DatabaseValueReducer(request: request) + }) + } + + /// Creates a ValueObservation which observes *request*, and notifies + /// fresh values whenever the request is modified by a + /// database transaction. + /// + /// For example: + /// + /// let request = Player.select(Column("name"), as: Optional.self) + /// let observation = ValueObservation.trackingAll(request) + /// + /// let observer = try observation.start(in: dbQueue) { names: [String?] in + /// print("Player names have changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter request: the observed request. + /// - returns: a ValueObservation. + public static func trackingAll(_ request: Request) + -> ValueObservation> + where Request.RowDecoder: _OptionalProtocol, + Request.RowDecoder._Wrapped: DatabaseValueConvertible + { + return ValueObservation>.tracking(request, reducer: { _ in + OptionalDatabaseValuesReducer(request: request) + }) + } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A reducer which outputs arrays of values, filtering out consecutive +/// identical database values. +/// +/// :nodoc: +public struct DatabaseValuesReducer: ValueReducer + where Request.RowDecoder: DatabaseValueConvertible +{ + public let request: Request + private var previousDbValues: [DatabaseValue]? + + init(request: Request) { + self.request = request + } + + public func fetch(_ db: Database) throws -> [DatabaseValue] { + return try DatabaseValue.fetchAll(db, request) + } + + public mutating func value(_ dbValues: [DatabaseValue]) -> [Request.RowDecoder]? { + if let previousDbValues = previousDbValues, previousDbValues == dbValues { + // Don't notify consecutive identical dbValue arrays + // TODO: Remove this implicit `distinctUntilDatabaseChanged` in GRDB 4 + return nil + } + self.previousDbValues = dbValues + return dbValues.map { + Request.RowDecoder.decode(from: $0, conversionContext: nil) + } + } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A reducer which outputs optional values, filtering out consecutive +/// identical database values. +/// +/// :nodoc: +public struct DatabaseValueReducer: ValueReducer + where Request.RowDecoder: DatabaseValueConvertible +{ + public let request: Request + private var previousDbValue: DatabaseValue?? + private var previousValueWasNil = false + + init(request: Request) { + self.request = request + } + + public func fetch(_ db: Database) throws -> DatabaseValue? { + return try DatabaseValue.fetchOne(db, request) + } + + public mutating func value(_ dbValue: DatabaseValue?) -> Request.RowDecoder?? { + if let previousDbValue = previousDbValue, previousDbValue == dbValue { + // Don't notify consecutive identical dbValue + // TODO: Remove this implicit `distinctUntilDatabaseChanged` in GRDB 4 + return nil + } + self.previousDbValue = dbValue + if let dbValue = dbValue, + let value = Request.RowDecoder.decodeIfPresent(from: dbValue, conversionContext: nil) + { + previousValueWasNil = false + return .some(value) + } else if previousValueWasNil { + // Don't notify consecutive nil values + // TODO: Remove this implicit `distinctUntilDatabaseChanged` in GRDB 4 + return nil + } else { + previousValueWasNil = true + return .some(nil) + } + } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A reducer which outputs arrays of optional values, filtering out consecutive +/// identical database values. +/// +/// :nodoc: +public struct OptionalDatabaseValuesReducer: ValueReducer + where + Request.RowDecoder: _OptionalProtocol, + Request.RowDecoder._Wrapped: DatabaseValueConvertible +{ + public let request: Request + private var previousDbValues: [DatabaseValue]? + + init(request: Request) { + self.request = request + } + + public func fetch(_ db: Database) throws -> [DatabaseValue] { + return try DatabaseValue.fetchAll(db, request) + } + + public mutating func value(_ dbValues: [DatabaseValue]) -> [Request.RowDecoder._Wrapped?]? { + if let previousDbValues = previousDbValues, previousDbValues == dbValues { + // Don't notify consecutive identical dbValue arrays + // TODO: Remove this implicit `distinctUntilDatabaseChanged` in GRDB 4 + return nil + } + self.previousDbValues = dbValues + return dbValues.map { + Request.RowDecoder._Wrapped.decodeIfPresent(from: $0, conversionContext: nil) + } + } +} diff --git a/GRDB/ValueObservation/ValueObservation+DistinctUntilChanged.swift b/GRDB/ValueObservation/ValueObservation+DistinctUntilChanged.swift new file mode 100644 index 000000000..a15102a71 --- /dev/null +++ b/GRDB/ValueObservation/ValueObservation+DistinctUntilChanged.swift @@ -0,0 +1,47 @@ +extension ValueObservation where Reducer: ValueReducer, Reducer.Value: Equatable { + /// Returns a ValueObservation which filters out consecutive equal values. + public func distinctUntilChanged() + -> ValueObservation> + { + return mapReducer { $1.distinctUntilChanged() } + } +} + +extension ValueReducer where Value: Equatable { + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// Returns a ValueReducer which filters out consecutive equal values. + public func distinctUntilChanged() -> DistinctUntilChangedValueReducer { + return DistinctUntilChangedValueReducer(self) + } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// See ValueReducer.distinctUntilChanged() +/// +/// :nodoc: +public struct DistinctUntilChangedValueReducer: ValueReducer where Base.Value: Equatable { + private var base: Base + private var previousValue: Base.Value? + + init(_ base: Base) { + self.base = base + } + + public func fetch(_ db: Database) throws -> Base.Fetched { + return try base.fetch(db) + } + + public mutating func value(_ fetched: Base.Fetched) -> Base.Value? { + guard let value = base.value(fetched) else { + return nil + } + if let previousValue = previousValue, previousValue == value { + // Don't notify consecutive identical values + return nil + } + self.previousValue = value + return value + } +} diff --git a/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift new file mode 100644 index 000000000..2a3ac9d7c --- /dev/null +++ b/GRDB/ValueObservation/ValueObservation+FetchableRecord.swift @@ -0,0 +1,131 @@ +extension ValueObservation where Reducer == Void { + + // MARK: - FetchableRecord Observation + + /// Creates a ValueObservation which observes *request*, and notifies + /// fresh records whenever the request is modified by a + /// database transaction. + /// + /// For example: + /// + /// let request = Player.all() + /// let observation = ValueObservation.trackingAll(request) + /// + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("Players have changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter request: the observed request. + /// - returns: a ValueObservation. + public static func trackingAll(_ request: Request) + -> ValueObservation> + where Request.RowDecoder: FetchableRecord + { + return ValueObservation>.tracking(request, reducer: { _ in + FetchableRecordsReducer(request: request) + }) + } + + /// Creates a ValueObservation which observes *request*, and notifies a + /// fresh record whenever the request is modified by a database transaction. + /// + /// For example: + /// + /// let request = Player.filter(key: 1) + /// let observation = ValueObservation.trackingOne(request) + /// + /// let observer = try observation.start(in: dbQueue) { player: Player? in + /// print("Player has changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter request: the observed request. + /// - returns: a ValueObservation. + public static func trackingOne(_ request: Request) -> + ValueObservation> + where Request.RowDecoder: FetchableRecord + { + return ValueObservation>.tracking(request, reducer: { _ in + FetchableRecordReducer(request: request) + }) + } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A reducer which outputs arrays of records, filtering out consecutive +/// identical database rows. +/// +/// :nodoc: +public struct FetchableRecordsReducer: ValueReducer + where Request.RowDecoder: FetchableRecord +{ + public let request: Request + private var previousRows: [Row]? + + init(request: Request) { + self.request = request + } + + public func fetch(_ db: Database) throws -> [Row] { + return try Row.fetchAll(db, request) + } + + public mutating func value(_ rows: [Row]) -> [Request.RowDecoder]? { + if let previousRows = previousRows, previousRows == rows { + // Don't notify consecutive identical row arrays + // TODO: Remove this implicit `distinctUntilDatabaseChanged` in GRDB 4 + return nil + } + self.previousRows = rows + return rows.map(Request.RowDecoder.init(row:)) + } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A reducer which outputs optional records, filtering out consecutive +/// identical database rows. +/// +/// :nodoc: +public struct FetchableRecordReducer: ValueReducer + where Request.RowDecoder: FetchableRecord +{ + public let request: Request + private var previousRow: Row?? + + init(request: Request) { + self.request = request + } + + public func fetch(_ db: Database) throws -> Row? { + return try Row.fetchOne(db, request) + } + + public mutating func value(_ row: Row?) -> Request.RowDecoder?? { + if let previousRow = previousRow, previousRow == row { + // Don't notify consecutive identical rows + // TODO: Remove this implicit `distinctUntilDatabaseChanged` in GRDB 4 + return nil + } + self.previousRow = row + return .some(row.map(Request.RowDecoder.init(row:))) + } +} diff --git a/GRDB/ValueObservation/ValueObservation+Map.swift b/GRDB/ValueObservation/ValueObservation+Map.swift new file mode 100644 index 000000000..cefd648b5 --- /dev/null +++ b/GRDB/ValueObservation/ValueObservation+Map.swift @@ -0,0 +1,47 @@ +extension ValueObservation where Reducer: ValueReducer { + /// Returns a ValueObservation which notifies the results of calling the + /// given transformation which each element notified by this + /// value observation. + public func map(_ transform: @escaping (Reducer.Value) -> T) + -> ValueObservation> + { + return mapReducer { $1.map(transform) } + } +} + +extension ValueReducer { + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// Returns a reducer which outputs the results of calling the given + /// transformation which each element emitted by this reducer. + public func map(_ transform: @escaping (Value) -> T) -> MapValueReducer { + return MapValueReducer(self, transform) + } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A ValueReducer whose values consist of those in a Base ValueReducer passed +/// through a transform function. +/// +/// See ValueReducer.map(_:) +/// +/// :nodoc: +public struct MapValueReducer: ValueReducer { + private var base: Base + private let transform: (Base.Value) -> T + + init(_ base: Base, _ transform: @escaping (Base.Value) -> T) { + self.base = base + self.transform = transform + } + + public func fetch(_ db: Database) throws -> Base.Fetched { + return try base.fetch(db) + } + + public mutating func value(_ fetched: Base.Fetched) -> T? { + guard let value = base.value(fetched) else { return nil } + return transform(value) + } +} diff --git a/GRDB/ValueObservation/ValueObservation+MapReducer.swift b/GRDB/ValueObservation/ValueObservation+MapReducer.swift new file mode 100644 index 000000000..baea470b8 --- /dev/null +++ b/GRDB/ValueObservation/ValueObservation+MapReducer.swift @@ -0,0 +1,15 @@ +extension ValueObservation { + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// Returns a ValueObservation with a transformed reducer. + public func mapReducer(_ transform: @escaping (Database, Reducer) throws -> R) -> ValueObservation { + let makeReducer = self.makeReducer + var observation = ValueObservation( + tracking: observedRegion, + reducer: { db in try transform(db, makeReducer(db)) }) + observation.extent = extent + observation.scheduling = scheduling + observation.requiresWriteAccess = requiresWriteAccess + return observation + } +} diff --git a/GRDB/ValueObservation/ValueObservation+Row.swift b/GRDB/ValueObservation/ValueObservation+Row.swift new file mode 100644 index 000000000..e3c1f55ba --- /dev/null +++ b/GRDB/ValueObservation/ValueObservation+Row.swift @@ -0,0 +1,129 @@ +extension ValueObservation where Reducer == Void { + + // MARK: - Row Observation + + /// Creates a ValueObservation which observes *request*, and notifies + /// fresh rows whenever the request is modified by a database transaction. + /// + /// For example: + /// + /// let request = SQLRequest("SELECT * FROM player") + /// let observation = ValueObservation.trackingAll(request) + /// + /// let observer = try observation.start(in: dbQueue) { rows: [Row] in + /// print("Players have changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter request: the observed request. + /// - returns: a ValueObservation. + public static func trackingAll(_ request: Request) + -> ValueObservation> + where Request.RowDecoder == Row + { + return ValueObservation>.tracking(request, reducer: { _ in + RowsReducer(request: request) + }) + } + + /// Creates a ValueObservation which observes *request*, and notifies a + /// fresh row whenever the request is modified by a database transaction. + /// + /// For example: + /// + /// let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1]) + /// let observation = ValueObservation.trackingOne(request) + /// + /// let observer = try observation.start(in: dbQueue) { row: Row? in + /// print("Players have changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter request: the observed request. + /// - returns: a ValueObservation. + public static func trackingOne(_ request: Request) + -> ValueObservation> + where Request.RowDecoder == Row + { + return ValueObservation>.tracking(request, reducer: { _ in + RowReducer(request: request) + }) + } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A reducer which outputs arrays of database rows, filtering out +/// consecutive identical arrays. +/// +/// :nodoc: +public struct RowsReducer: ValueReducer + where Request.RowDecoder == Row +{ + public let request: Request + private var previousRows: [Row]? + + init(request: Request) { + self.request = request + } + + public func fetch(_ db: Database) throws -> [Row] { + return try request.fetchAll(db) + } + + public mutating func value(_ rows: [Row]) -> [Row]? { + if let previousRows = previousRows, previousRows == rows { + // Don't notify consecutive identical row arrays + return nil + } + self.previousRows = rows + return rows + } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A reducer which outputs optional records, filtering out consecutive +/// identical database rows. +/// +/// :nodoc: +public struct RowReducer: ValueReducer + where Request.RowDecoder == Row +{ + public let request: Request + private var previousRow: Row?? + + init(request: Request) { + self.request = request + } + + public func fetch(_ db: Database) throws -> Row? { + return try request.fetchOne(db) + } + + public mutating func value(_ row: Row?) -> Row?? { + if let previousRow = previousRow, previousRow == row { + // Don't notify consecutive identical rows + // TODO: Remove this implicit `distinctUntilDatabaseChanged` in GRDB 4 + return nil + } + self.previousRow = row + return row + } +} diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift new file mode 100644 index 000000000..b142571df --- /dev/null +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -0,0 +1,445 @@ +import Dispatch + +// MARK: - ValueScheduling + +/// ValueScheduling controls how ValueObservation schedules the notifications +/// of fresh values to your application. +public enum ValueScheduling { + /// All values are notified on the main queue. + /// + /// If the observation starts on the main queue, an initial value is + /// notified right upon subscription, synchronously: + /// + /// // On main queue + /// let observation = ValueObservation.trackingAll(Player.all()) + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("fresh players: \(players)") + /// } + /// // <- here "fresh players" is already printed. + /// + /// If the observation does not start on the main queue, an initial value + /// is also notified on the main queue, but asynchronously: + /// + /// // Not on the main queue: "fresh players" is eventually printed + /// // on the main queue. + /// let observation = ValueObservation.trackingAll(Player.all()) + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("fresh players: \(players)") + /// } + /// + /// When the database changes, fresh values are asynchronously notified on + /// the main queue: + /// + /// // Eventually prints "fresh players" on the main queue + /// try dbQueue.write { db in + /// try Player(...).insert(db) + /// } + case mainQueue + + /// All values are asychronously notified on the specified queue. + /// + /// An initial value is fetched and notified if `startImmediately` + /// is true. + case onQueue(DispatchQueue, startImmediately: Bool) + + /// Values are not all notified on the same dispatch queue. + /// + /// If `startImmediately` is true, an initial value is notified right upon + /// subscription, synchronously, on the dispatch queue which starts + /// the observation. + /// + /// // On any queue + /// var observation = ValueObservation.trackingAll(Player.all()) + /// observation.scheduling = .unsafe(startImmediately: true) + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("fresh players: \(players)") + /// } + /// // <- here "fresh players" is already printed. + /// + /// When the database changes, other values are notified on + /// unspecified queues. + case unsafe(startImmediately: Bool) +} + +// MARK: - ValueObservation + +/// ValueObservation tracks changes in the results of database requests, and +/// notifies fresh values whenever the database changes. +/// +/// For example: +/// +/// let observation = ValueObservation.trackingAll(Player.all) +/// let observer = try observation.start(in: dbQueue) { players: [Player] in +/// print("Players have changed.") +/// } +public struct ValueObservation { + /// A closure that is evaluated when the observation starts, and returns + /// the observed database region. + var observedRegion: (Database) throws -> DatabaseRegion + + /// The reducer is created when observation starts, and is triggered upon + /// each database change in *observedRegion*. + var makeReducer: (Database) throws -> 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. + /// + /// Don't set this flag to true unless you really need it. A read/write + /// observation is less efficient than a read-only observation. + public var requiresWriteAccess: Bool = false + + /// The extent of the database observation. The default is + /// `.observerLifetime`: the observation lasts until the + /// observer returned by the `start(in:onError:onChange:)` method + /// is deallocated. + public var extent = Database.TransactionObservationExtent.observerLifetime + + /// `scheduling` controls how fresh values are notified. Default + /// is `.mainQueue`. + /// + /// - `.mainQueue`: all values are notified on the main queue. + /// + /// If the observation starts on the main queue, an initial value is + /// notified right upon subscription, synchronously:: + /// + /// // On main queue + /// let observation = ValueObservation.trackingAll(Player.all()) + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("fresh players: \(players)") + /// } + /// // <- here "fresh players" is already printed. + /// + /// If the observation does not start on the main queue, an initial + /// value is also notified on the main queue, but asynchronously: + /// + /// // Not on the main queue: "fresh players" is eventually printed + /// // on the main queue. + /// let observation = ValueObservation.trackingAll(Player.all()) + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("fresh players: \(players)") + /// } + /// + /// When the database changes, fresh values are asynchronously notified: + /// + /// // Eventually prints "fresh players" on the main queue + /// try dbQueue.write { db in + /// try Player(...).insert(db) + /// } + /// + /// - `.onQueue(_:startImmediately:)`: all values are asychronously notified + /// on the specified queue. + /// + /// An initial value is fetched and notified if `startImmediately` + /// is true. + /// + /// - `unsafe(startImmediately:)`: values are not all notified on the same + /// dispatch queue. + /// + /// If `startImmediately` is true, an initial value is notified right + /// upon subscription, synchronously, on the dispatch queue which starts + /// the observation. + /// + /// // On any queue + /// var observation = ValueObservation.trackingAll(Player.all()) + /// observation.scheduling = .unsafe(startImmediately: true) + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("fresh players: \(players)") + /// } + /// // <- here "fresh players" is already printed. + /// + /// When the database changes, other values are notified on + /// unspecified queues. + public var scheduling: ValueScheduling = .mainQueue + + /// The dispatch queue where change callbacks are called. + var notificationQueue: DispatchQueue? { + switch scheduling { + case .mainQueue: + return DispatchQueue.main + case .onQueue(let queue, startImmediately: _): + return queue + case .unsafe: + return nil + } + } + + // Not public because we foster DatabaseRegionConvertible. + // See ValueObservation.tracking(_:reducer:) + init( + tracking region: @escaping (Database) throws -> DatabaseRegion, + reducer: @escaping (Database) throws -> Reducer) + { + self.observedRegion = { db in + // Remove views from the observed region. + // + // We can do it because we are only interested in modifications in + // actual tables. And we want to do it because we have a fast path + // for simple regions that span a single table. + let views = try db.schema().names(ofType: .view) + return try region(db).ignoring(views) + } + self.makeReducer = reducer + } +} + +extension ValueObservation where Reducer: ValueReducer { + + // MARK: - Starting Observation + + /// Starts the value observation in the provided database reader (such as + /// a database queue or database pool), and returns a transaction observer. + /// + /// - parameter reader: A DatabaseReader. + /// - parameter onError: A closure that is provided eventual errors that + /// happen during observation + /// - parameter onChange: A closure that is provided fresh values + /// - returns: a TransactionObserver + public func start( + in reader: DatabaseReader, + onError: ((Error) -> Void)? = nil, + onChange: @escaping (Reducer.Value) -> Void) throws -> TransactionObserver + { + return try reader.add(observation: self, onError: onError, onChange: onChange) + } +} + +extension ValueObservation { + + // MARK: - Creating ValueObservation from ValueReducer + + /// Returns a ValueObservation which observes *regions*, and notifies the + /// values returned by the *reducer* whenever one of the observed + /// regions is modified by a database transaction. + /// + /// This method is the most fundamental way to create a ValueObservation. + /// + /// For example, this observation counts the number of a times the player + /// table is modified: + /// + /// var count = 0 + /// let reducer = AnyValueReducer( + /// fetch: { _ in }, + /// value: { _ -> Int? in + /// count += 1 + /// return count }) + /// let observation = ValueObservation.tracking(Player.all(), reducer: reducer) + /// let observer = observation.start(in: dbQueue) { count: Int in + /// print("Players have been modified \(count) times.") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter regions: A list of observed regions. + /// - parameter reducer: A reducer that turns database changes in the + /// modified regions into fresh values. Currently only reducers that adopt + /// the ValueReducer protocol are supported. + @available(*, deprecated, message: "Provide the reducer in a (Database) -> Reducer closure") + public static func tracking( + _ regions: DatabaseRegionConvertible..., + reducer: Reducer) + -> ValueObservation + { + return ValueObservation.tracking(regions, reducer: { _ in reducer }) + } + + /// Returns a ValueObservation which observes *regions*, and notifies the + /// values returned by the *reducer* whenever one of the observed + /// regions is modified by a database transaction. + /// + /// This method is the most fundamental way to create a ValueObservation. + /// + /// For example, this observation counts the number of a times the player + /// table is modified: + /// + /// var count = 0 + /// let reducer = AnyValueReducer( + /// fetch: { _ in /* don't fetch anything */ }, + /// value: { _ -> Int? in + /// defer { count += 1 } + /// return count }) + /// let observation = ValueObservation.tracking(Player.all(), reducer: { db in reducer }) + /// let observer = observation.start(in: dbQueue) { count: Int in + /// print("Players have been modified \(count) times.") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter regions: A list of observed regions. + /// - parameter reducer: A reducer that turns database changes in the + /// modified regions into fresh values. Currently only reducers that adopt + /// the ValueReducer protocol are supported. + public static func tracking( + _ regions: DatabaseRegionConvertible..., + reducer: @escaping (Database) throws -> Reducer) + -> ValueObservation + { + return ValueObservation.tracking(regions, reducer: reducer) + } + + /// Returns a ValueObservation which observes *regions*, and notifies the + /// values returned by the *reducer* whenever one of the observed + /// regions is modified by a database transaction. + /// + /// This method is the most fundamental way to create a ValueObservation. + /// + /// For example, this observation counts the number of a times the player + /// table is modified: + /// + /// var count = 0 + /// let reducer = AnyValueReducer( + /// fetch: { _ in /* don't fetch anything */ }, + /// value: { _ -> Int? in + /// defer { count += 1 } + /// return count }) + /// let observation = ValueObservation.tracking([Player.all()], reducer: { db in reducer }) + /// let observer = observation.start(in: dbQueue) { count: Int in + /// print("Players have been modified \(count) times.") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter regions: A list of observed regions. + /// - parameter reducer: A reducer that turns database changes in the + /// modified regions into fresh values. Currently only reducers that adopt + /// the ValueReducer protocol are supported. + public static func tracking( + _ regions: [DatabaseRegionConvertible], + reducer: @escaping (Database) throws -> Reducer) + -> ValueObservation + { + return ValueObservation( + tracking: DatabaseRegion.union(regions), + reducer: reducer) + } +} + +extension ValueObservation where Reducer == Void { + + // MARK: - Creating ValueObservation from Fetch Closures + + /// Creates a ValueObservation which observes *regions*, and notifies the + /// values returned by the *fetch* closure whenever one of the observed + /// regions is modified by a database transaction. + /// + /// For example: + /// + /// let observation = ValueObservation.tracking( + /// Player.all(), + /// fetch: { db in return try Player.fetchAll(db) }) + /// + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("Players have changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter regions: A list of observed regions. + /// - parameter fetch: A closure that fetches a value. + public static func tracking( + _ regions: DatabaseRegionConvertible..., + fetch: @escaping (Database) throws -> Value) + -> ValueObservation> + { + return ValueObservation.tracking(regions, fetch: fetch) + } + + /// Creates a ValueObservation which observes *regions*, and notifies the + /// values returned by the *fetch* closure whenever one of the observed + /// regions is modified by a database transaction. + /// + /// For example: + /// + /// let observation = ValueObservation.tracking( + /// [Player.all()], + /// fetch: { db in return try Player.fetchAll(db) }) + /// + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("Players have changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter regions: A list of observed regions. + /// - parameter fetch: A closure that fetches a value. + public static func tracking( + _ regions: [DatabaseRegionConvertible], + fetch: @escaping (Database) throws -> Value) + -> ValueObservation> + { + return ValueObservation>( + tracking: DatabaseRegion.union(regions), + reducer: { _ in RawValueReducer(fetch) }) + } + + /// Creates a ValueObservation which observes *regions*, and notifies the + /// values returned by the *fetch* closure whenever one of the observed + /// regions is modified by a database transaction. Consecutive equal values + /// are filtered out. + /// + /// For example: + /// + /// let observation = ValueObservation.tracking( + /// Player.all(), + /// fetchDistinct: { db in return try Player.fetchAll(db) }) + /// + /// let observer = try observation.start(in: dbQueue) { players: [Player] in + /// print("Players have changed") + /// } + /// + /// The returned observation has the default configuration: + /// + /// - When started with the `start(in:onError:onChange:)` method, a fresh + /// value is immediately notified on the main queue. + /// - Upon subsequent database changes, fresh values are notified on the + /// main queue. + /// - The observation lasts until the observer returned by + /// `start` is deallocated. + /// + /// - parameter regions: A list of observed regions. + /// - parameter fetch: A closure that fetches a value. + @available(*, deprecated, message: "Use distinctUntilChanged() instead") + public static func tracking( + _ regions: DatabaseRegionConvertible..., + fetchDistinct fetch: @escaping (Database) throws -> Value) + -> ValueObservation>> + where Value: Equatable + { + return ValueObservation.tracking(regions, fetch: fetch).distinctUntilChanged() + } +} diff --git a/GRDB/ValueObservation/ValueObserver.swift b/GRDB/ValueObservation/ValueObserver.swift new file mode 100644 index 000000000..b261383a8 --- /dev/null +++ b/GRDB/ValueObservation/ValueObserver.swift @@ -0,0 +1,89 @@ +import Foundation + +/// Support for ValueObservation. +/// See DatabaseWriter.add(observation:onError:onChange:) +class ValueObserver: TransactionObserver { + /* private */ let region: DatabaseRegion // Internal for testability + private var reducer: Reducer + private let fetch: (Database, Reducer) -> Future + private let notificationQueue: DispatchQueue? + private let onError: ((Error) -> Void)? + private let onChange: (Reducer.Value) -> Void + private let reduceQueue: DispatchQueue + private var isChanged = false + + init( + region: DatabaseRegion, + reducer: Reducer, + configuration: Configuration, + fetch: @escaping (Database, Reducer) -> Future, + notificationQueue: DispatchQueue?, + onError: ((Error) -> Void)?, + onChange: @escaping (Reducer.Value) -> Void) + { + self.region = region + self.reducer = reducer + self.fetch = fetch + self.notificationQueue = notificationQueue + self.onChange = onChange + self.onError = onError + self.reduceQueue = configuration.makeDispatchQueue(defaultLabel: "GRDB", purpose: "ValueObservation.reducer") + } + + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { + return region.isModified(byEventsOfKind: eventKind) + } + + func databaseDidChange(with event: DatabaseEvent) { + if region.isModified(by: event) { + isChanged = true + stopObservingDatabaseChangesUntilNextTransaction() + } + } + + func databaseDidCommit(_ db: Database) { + guard isChanged else { return } + isChanged = false + + // Grab future fetched values from the database writer queue + let future = fetch(db, reducer) + + // Wait for future fetched values 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 { [weak self] in + guard let strongSelf = self else { return } + + do { + if let value = try strongSelf.reducer.value(future.wait()) { + if let queue = strongSelf.notificationQueue { + queue.async { + guard let strongSelf = self else { return } + strongSelf.onChange(value) + } + } else { + strongSelf.onChange(value) + } + } + } catch { + guard strongSelf.onError != nil else { + // TODO: how can we let the user know about the error? + return + } + if let queue = strongSelf.notificationQueue { + queue.async { + guard let strongSelf = self else { return } + strongSelf.onError?(error) + } + } else { + strongSelf.onError?(error) + } + } + } + } + + func databaseDidRollback(_ db: Database) { + isChanged = false + } +} diff --git a/GRDB/ValueObservation/ValueReducer.swift b/GRDB/ValueObservation/ValueReducer.swift new file mode 100644 index 000000000..198e3af36 --- /dev/null +++ b/GRDB/ValueObservation/ValueReducer.swift @@ -0,0 +1,92 @@ +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// The ValueReducer protocol supports ValueObservation. +public protocol ValueReducer { + /// The type of fetched database values + associatedtype Fetched + + /// The type of observed values + associatedtype Value + + /// Feches database values upon changes in an observed database region. + func fetch(_ db: Database) throws -> Fetched + + /// Transforms a fetched value into an eventual observed value. Returns nil + /// when observer should not be notified. + /// + /// This method runs inside a private dispatch queue. + mutating func value(_ fetched: Fetched) -> Value? +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A type-erased ValueReducer. +/// +/// An AnyValueReducer forwards its operations to an underlying reducer, +/// hiding its specifics. +public struct AnyValueReducer: ValueReducer { + private var _fetch: (Database) throws -> Fetched + private var _value: (Fetched) -> Value? + + /// Creates a reducer whose `fetch(_:)` and `value(_:)` methods wrap and + /// forward operations the argument closures. + /// + /// For example, this reducer counts the number of a times the player table + /// is modified: + /// + /// var count = 0 + /// let reducer = AnyValueReducer( + /// fetch: { _ in }, + /// value: { _ -> Int? in + /// count += 1 + /// return count + /// }) + /// let observer = ValueObservation + /// .tracking(Player.all(), reducer: reducer) + /// .start(in: dbQueue) { count: Int in + /// print("Players have been modified \(count) times.") + /// } + public init(fetch: @escaping (Database) throws -> Fetched, value: @escaping (Fetched) -> Value?) { + self._fetch = fetch + self._value = value + } + + /// Creates a reducer that wraps and forwards operations to `reducer`. + public init(_ reducer: Base) where Base.Fetched == Fetched, Base.Value == Value { + var reducer = reducer + self._fetch = { try reducer.fetch($0) } + self._value = { reducer.value($0) } + } + + /// :nodoc: + public func fetch(_ db: Database) throws -> Fetched { + return try _fetch(db) + } + + /// :nodoc: + public func value(_ fetched: Fetched) -> Value? { + return _value(fetched) + } +} + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A reducer which outputs raw values. +/// +/// :nodoc: +public struct RawValueReducer: ValueReducer { + private let _fetch: (Database) throws -> Value + + public init(_ fetch: @escaping (Database) throws -> Value) { + self._fetch = fetch + } + + public func fetch(_ db: Database) throws -> Value { + return try _fetch(db) + } + + public func value(_ fetched: Value) -> Value? { + return fetched + } +} + diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index f6541248d..3f14b05e5 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -89,6 +89,26 @@ 560FC5A71CB00B880014AA8E /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; }; 560FC5B21CB031E30014AA8E /* StatementColumnConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */; }; 560FC5B31CB031EA0014AA8E /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; }; + 5613ED7B21A95E8400DC7A68 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7321A95E8400DC7A68 /* ValueObservation.swift */; }; + 5613ED7C21A95E8400DC7A68 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7321A95E8400DC7A68 /* ValueObservation.swift */; }; + 5613ED7D21A95E8400DC7A68 /* ValueObservation+Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7421A95E8400DC7A68 /* ValueObservation+Combine.swift */; }; + 5613ED7E21A95E8400DC7A68 /* ValueObservation+Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7421A95E8400DC7A68 /* ValueObservation+Combine.swift */; }; + 5613ED7F21A95E8400DC7A68 /* ValueObservation+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7521A95E8400DC7A68 /* ValueObservation+Map.swift */; }; + 5613ED8021A95E8400DC7A68 /* ValueObservation+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7521A95E8400DC7A68 /* ValueObservation+Map.swift */; }; + 5613ED8121A95E8400DC7A68 /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7621A95E8400DC7A68 /* ValueObservation+Row.swift */; }; + 5613ED8221A95E8400DC7A68 /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7621A95E8400DC7A68 /* ValueObservation+Row.swift */; }; + 5613ED8321A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7721A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift */; }; + 5613ED8421A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7721A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift */; }; + 5613ED8521A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7821A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; }; + 5613ED8621A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7821A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; }; + 5613ED8721A95E8400DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7921A95E8400DC7A68 /* ValueReducer.swift */; }; + 5613ED8821A95E8400DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7921A95E8400DC7A68 /* ValueReducer.swift */; }; + 5613ED8921A95E8400DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7A21A95E8400DC7A68 /* ValueObservation+Count.swift */; }; + 5613ED8A21A95E8400DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED7A21A95E8400DC7A68 /* ValueObservation+Count.swift */; }; + 5613ED9E21A96A6F00DC7A68 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED9D21A96A6F00DC7A68 /* ValueObservationCombineTests.swift */; }; + 5613ED9F21A96A6F00DC7A68 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED9D21A96A6F00DC7A68 /* ValueObservationCombineTests.swift */; }; + 5613EDA021A96A6F00DC7A68 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED9D21A96A6F00DC7A68 /* ValueObservationCombineTests.swift */; }; + 5613EDA121A96A6F00DC7A68 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED9D21A96A6F00DC7A68 /* ValueObservationCombineTests.swift */; }; 561667021D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; 561667031D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; 561667061D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; @@ -180,8 +200,6 @@ 5634B10C1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */; }; 5636E9BD1D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; 5636E9C01D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; - 563B06B6217F3C5A00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06B4217F3C5900B38F35 /* ValueObservation.swift */; }; - 563B06B7217F3C5A00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06B4217F3C5900B38F35 /* ValueObservation.swift */; }; 563B06E12185E07200B38F35 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06DC2185E07100B38F35 /* ValueObservationExtentTests.swift */; }; 563B06E22185E07200B38F35 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06DC2185E07100B38F35 /* ValueObservationExtentTests.swift */; }; 563B06E32185E07300B38F35 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06DC2185E07100B38F35 /* ValueObservationExtentTests.swift */; }; @@ -242,6 +260,28 @@ 5644DE8320F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE8120F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift */; }; 5644DE8420F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE8120F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift */; }; 5644DE8520F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE8120F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift */; }; + 564CE44021AA957000652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43F21AA957000652B19 /* ValueObserver.swift */; }; + 564CE44121AA957000652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43F21AA957000652B19 /* ValueObserver.swift */; }; + 564CE4DD21B2DEF700652B19 /* ValueObservation+CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4DC21B2DEF700652B19 /* ValueObservation+CompactMap.swift */; }; + 564CE4DE21B2DEF700652B19 /* ValueObservation+CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4DC21B2DEF700652B19 /* ValueObservation+CompactMap.swift */; }; + 564CE4EC21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4EB21B2E08200652B19 /* ValueObservationCompactMapTests.swift */; }; + 564CE4ED21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4EB21B2E08200652B19 /* ValueObservationCompactMapTests.swift */; }; + 564CE4EE21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4EB21B2E08200652B19 /* ValueObservationCompactMapTests.swift */; }; + 564CE4EF21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4EB21B2E08200652B19 /* ValueObservationCompactMapTests.swift */; }; + 564CE4F121B2E08A00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */; }; + 564CE4F221B2E08A00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */; }; + 564CE4F321B2E08A00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */; }; + 564CE4F421B2E08A00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */; }; + 564CE52621B312B500652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */; }; + 564CE52721B312B700652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */; }; + 564CE5A621B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; + 564CE5A721B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; + 564CE5BB21B8FBFD00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B921B8FBFD00652B19 /* DatabaseRegionObservation.swift */; }; + 564CE5BC21B8FBFD00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B921B8FBFD00652B19 /* DatabaseRegionObservation.swift */; }; + 564CE5C121B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5C021B8FFD800652B19 /* DatabaseRegionObservationTests.swift */; }; + 564CE5C221B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5C021B8FFD800652B19 /* DatabaseRegionObservationTests.swift */; }; + 564CE5C321B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5C021B8FFD800652B19 /* DatabaseRegionObservationTests.swift */; }; + 564CE5C421B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5C021B8FFD800652B19 /* DatabaseRegionObservationTests.swift */; }; 564E73EF203DA2A2000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; }; 564E73F0203DA2A3000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; }; 564E73F1203DA2A3000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; }; @@ -998,6 +1038,15 @@ 560FC54D1CB003810014AA8E /* GRDBCipher.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDBCipher.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 560FC5501CB004AD0014AA8E /* sqlcipher.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = sqlcipher.xcodeproj; path = SQLCipher/src/sqlcipher.xcodeproj; sourceTree = ""; }; 560FC5B01CB00B880014AA8E /* GRDBCipherOSXTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCipherOSXTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 5613ED7321A95E8400DC7A68 /* ValueObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservation.swift; sourceTree = ""; }; + 5613ED7421A95E8400DC7A68 /* ValueObservation+Combine.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Combine.swift"; sourceTree = ""; }; + 5613ED7521A95E8400DC7A68 /* ValueObservation+Map.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Map.swift"; sourceTree = ""; }; + 5613ED7621A95E8400DC7A68 /* ValueObservation+Row.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Row.swift"; sourceTree = ""; }; + 5613ED7721A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+FetchableRecord.swift"; sourceTree = ""; }; + 5613ED7821A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DatabaseValueConvertible.swift"; sourceTree = ""; }; + 5613ED7921A95E8400DC7A68 /* ValueReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueReducer.swift; sourceTree = ""; }; + 5613ED7A21A95E8400DC7A68 /* ValueObservation+Count.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Count.swift"; sourceTree = ""; }; + 5613ED9D21A96A6F00DC7A68 /* ValueObservationCombineTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCombineTests.swift; sourceTree = ""; }; 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; 5616AAF8207CD5A900AC3664 /* RequestProtocols.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; @@ -1026,7 +1075,6 @@ 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReleaseMemoryTests.swift; sourceTree = ""; }; 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverSavepointsTests.swift; sourceTree = ""; }; 5636E9BB1D22574100B9B05F /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = ""; }; - 563B06B4217F3C5900B38F35 /* ValueObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservation.swift; sourceTree = ""; }; 563B06DC2185E07100B38F35 /* ValueObservationExtentTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationExtentTests.swift; sourceTree = ""; }; 563B06DD2185E07200B38F35 /* ValueObservationReadonlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationReadonlyTests.swift; sourceTree = ""; }; 563B06DE2185E07200B38F35 /* ValueObservationFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationFetchTests.swift; sourceTree = ""; }; @@ -1045,6 +1093,14 @@ 5644DE7A20F8C903001FFDDE /* DatabaseValueConversion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversion.swift; sourceTree = ""; }; 5644DE8120F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; + 564CE43F21AA957000652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = ""; }; + 564CE4DC21B2DEF700652B19 /* ValueObservation+CompactMap.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+CompactMap.swift"; sourceTree = ""; }; + 564CE4EB21B2E08200652B19 /* ValueObservationCompactMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCompactMapTests.swift; sourceTree = ""; }; + 564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; + 564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; + 564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = ""; }; + 564CE5B921B8FBFD00652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = ""; }; + 564CE5C021B8FFD800652B19 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = ""; }; 564E73EB203DA29B000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1434,6 +1490,25 @@ name = Products; sourceTree = ""; }; + 5613ED7221A95E8400DC7A68 /* ValueObservation */ = { + isa = PBXGroup; + children = ( + 5613ED7321A95E8400DC7A68 /* ValueObservation.swift */, + 5613ED7421A95E8400DC7A68 /* ValueObservation+Combine.swift */, + 564CE4DC21B2DEF700652B19 /* ValueObservation+CompactMap.swift */, + 5613ED7A21A95E8400DC7A68 /* ValueObservation+Count.swift */, + 5613ED7821A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */, + 564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */, + 5613ED7721A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift */, + 5613ED7521A95E8400DC7A68 /* ValueObservation+Map.swift */, + 564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */, + 5613ED7621A95E8400DC7A68 /* ValueObservation+Row.swift */, + 564CE43F21AA957000652B19 /* ValueObserver.swift */, + 5613ED7921A95E8400DC7A68 /* ValueReducer.swift */, + ); + path = ValueObservation; + sourceTree = ""; + }; 56176C581EACC2D8000F3F2B /* GRDBTests */ = { isa = PBXGroup; children = ( @@ -1447,6 +1522,7 @@ 56300B5C1C53C38F005A543B /* QueryInterface */, 56A238251B9C74A90082EB20 /* Record */, 56176C9F1EACEE15000F3F2B /* Support */, + 563B06F52185E07C00B38F35 /* ValueObservation */, ); path = GRDBTests; sourceTree = ""; @@ -1570,10 +1646,13 @@ 563B06F52185E07C00B38F35 /* ValueObservation */ = { isa = PBXGroup; children = ( + 5613ED9D21A96A6F00DC7A68 /* ValueObservationCombineTests.swift */, + 564CE4EB21B2E08200652B19 /* ValueObservationCompactMapTests.swift */, 563B06F921861D8B00B38F35 /* ValueObservationCountTests.swift */, 563B071D21862F5D00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */, 563B06DC2185E07100B38F35 /* ValueObservationExtentTests.swift */, 563B06DE2185E07200B38F35 /* ValueObservationFetchTests.swift */, + 564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */, 563B06DD2185E07200B38F35 /* ValueObservationReadonlyTests.swift */, 563B070C21862C3500B38F35 /* ValueObservationRecordTests.swift */, 563B06DF2185E07200B38F35 /* ValueObservationReducerTests.swift */, @@ -1719,6 +1798,7 @@ 560A37A91C90084600949E71 /* DatabasePool */, 563363BB1C93FD32000BE133 /* DatabaseQueue */, 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */, + 564CE5C021B8FFD800652B19 /* DatabaseRegionObservationTests.swift */, 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */, 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */, 56A238131B9C74A90082EB20 /* DatabaseTests.swift */, @@ -1739,7 +1819,6 @@ 56A238201B9C74A90082EB20 /* Statement */, 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */, 5607EFD11BB8253300605DE3 /* TransactionObserver */, - 563B06F52185E07C00B38F35 /* ValueObservation */, ); name = Core; sourceTree = ""; @@ -1817,6 +1896,7 @@ 56A238741B9C75030082EB20 /* DatabaseQueue.swift */, 563363BF1C942C04000BE133 /* DatabaseReader.swift */, 569EF0E8200D387000A9FA45 /* DatabaseRegion.swift */, + 564CE5B921B8FBFD00652B19 /* DatabaseRegionObservation.swift */, 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */, 566A842720413D6E00E50BFD /* DatabaseSnapshot.swift */, 56A238751B9C75030082EB20 /* DatabaseValue.swift */, @@ -1833,7 +1913,6 @@ 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, 5605F1471C672E4000235C62 /* Support */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, - 563B06B4217F3C5900B38F35 /* ValueObservation.swift */, ); path = Core; sourceTree = ""; @@ -1971,6 +2050,7 @@ 56A2389F1B9C753B0082EB20 /* Record */, DC37743319C8CFCE004FCF85 /* Supporting Files */, 5659F4861EA8D94E004A4992 /* Utils */, + 5613ED7221A95E8400DC7A68 /* ValueObservation */, ); path = GRDB; sourceTree = ""; @@ -2256,17 +2336,21 @@ 560FC51C1CB003810014AA8E /* QueryInterfaceRequest.swift in Sources */, 560FC51D1CB003810014AA8E /* SQLCollatedExpression.swift in Sources */, 5653EB9920961FC000F46237 /* ForeignKeyRequest.swift in Sources */, + 5613ED8121A95E8400DC7A68 /* ValueObservation+Row.swift in Sources */, 566B91341FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215B1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, + 5613ED8921A95E8400DC7A68 /* ValueObservation+Count.swift in Sources */, 566475D41D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 5653EB9120961FC000F46237 /* HasOneAssociation.swift in Sources */, 56CEB5621EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FB1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD361DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, + 564CE5A621B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */, 566B91141FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 560FC51F1CB003810014AA8E /* CGFloat.swift in Sources */, 5674A7091F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 5653EC17209873A400F46237 /* SQLExpression+QueryInterface.swift in Sources */, + 564CE52621B312B500652B19 /* ValueObservation+MapReducer.swift in Sources */, 5659F4A11EA8D997004A4992 /* Result.swift in Sources */, 560FC5201CB003810014AA8E /* Date.swift in Sources */, 560FC5221CB003810014AA8E /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, @@ -2290,6 +2374,7 @@ 56B964B21DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, 560FC5261CB003810014AA8E /* SerializedDatabase.swift in Sources */, 560FC5271CB003810014AA8E /* NSString.swift in Sources */, + 564CE4DD21B2DEF700652B19 /* ValueObservation+CompactMap.swift in Sources */, 560FC5291CB003810014AA8E /* DatabaseValueConvertible.swift in Sources */, 56A8C2311D1914540096E9D4 /* UUID.swift in Sources */, 56CEB5021EAA2F4D00BFAF62 /* FTS4.swift in Sources */, @@ -2299,6 +2384,7 @@ 5656BF5E20C7248700F98521 /* QueryOrdering.swift in Sources */, 56D51D011EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 566475BB1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, + 5613ED8721A95E8400DC7A68 /* ValueReducer.swift in Sources */, 560FC52B1CB003810014AA8E /* DatabaseValue.swift in Sources */, 5671FC211DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 560FC52E1CB003810014AA8E /* Record.swift in Sources */, @@ -2307,10 +2393,10 @@ 560FC5311CB003810014AA8E /* TableRecord.swift in Sources */, 56DAA2DC1DE9C827006E10C8 /* Cursor.swift in Sources */, 5674A6F11F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, + 5613ED8321A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, 5644DE7C20F8C903001FFDDE /* DatabaseValueConversion.swift in Sources */, 560FC5321CB003810014AA8E /* DatabasePool.swift in Sources */, 560FC5331CB003810014AA8E /* Migration.swift in Sources */, - 563B06B6217F3C5A00B38F35 /* ValueObservation.swift in Sources */, 560FC5341CB003810014AA8E /* QueryInterfaceQuery.swift in Sources */, 566B912C1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 560FC5351CB003810014AA8E /* Statement.swift in Sources */, @@ -2326,19 +2412,25 @@ 560FC5391CB003810014AA8E /* DatabaseReader.swift in Sources */, 560FC53A1CB003810014AA8E /* NSNull.swift in Sources */, 56CEB51A1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, + 564CE44021AA957000652B19 /* ValueObserver.swift in Sources */, 5674A7011F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 5698AC791DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 560FC53B1CB003810014AA8E /* Database.swift in Sources */, 566AD8B31D5318F4002EC1A8 /* TableDefinition.swift in Sources */, + 5613ED7F21A95E8400DC7A68 /* ValueObservation+Map.swift in Sources */, 5698AD221DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, + 564CE5BB21B8FBFD00652B19 /* DatabaseRegionObservation.swift in Sources */, 560FC53C1CB003810014AA8E /* DatabaseQueue.swift in Sources */, 5653EB9720961FC000F46237 /* ForeignKey.swift in Sources */, 569A98FC2039B72D008D7DBF /* Fixits-3.0.swift in Sources */, + 5613ED8521A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 5653EB9520961FC000F46237 /* HasManyAssociation.swift in Sources */, 560FC53D1CB003810014AA8E /* NSNumber.swift in Sources */, + 5613ED7B21A95E8400DC7A68 /* ValueObservation.swift in Sources */, 567071F8208A00D4006AD95A /* SQLiteDateParser.swift in Sources */, 560FC53F1CB003810014AA8E /* Row.swift in Sources */, 560FC5401CB003810014AA8E /* StandardLibrary.swift in Sources */, + 5613ED7D21A95E8400DC7A68 /* ValueObservation+Combine.swift in Sources */, 5653EC1A209873E600F46237 /* SQLGenerationContext.swift in Sources */, 560FC5411CB003810014AA8E /* PersistableRecord.swift in Sources */, 566475A31D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, @@ -2447,6 +2539,7 @@ 5653EBB820961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */, 560FC5841CB00B880014AA8E /* PersistableRecordTests.swift in Sources */, 560FC5871CB00B880014AA8E /* RecordSubClassTests.swift in Sources */, + 5613ED9E21A96A6F00DC7A68 /* ValueObservationCombineTests.swift in Sources */, 5653EBBC20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 560FC5891CB00B880014AA8E /* TransactionObserverTests.swift in Sources */, 5674A72C1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, @@ -2482,7 +2575,9 @@ 565EFAEF1D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, 560FC5961CB00B880014AA8E /* DatabaseValueConvertibleFetchTests.swift in Sources */, 5653EBC420961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, + 564CE5C121B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */, 560FC5971CB00B880014AA8E /* DatabaseErrorTests.swift in Sources */, + 564CE4EC21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */, 560FC5991CB00B880014AA8E /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, 564F9C1F1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, 562393731DEE104400A6B01F /* MapCursorTests.swift in Sources */, @@ -2508,6 +2603,7 @@ 560FC5A21CB00B880014AA8E /* DatabaseFunctionTests.swift in Sources */, 560FC5A41CB00B880014AA8E /* RecordWithColumnNameManglingTests.swift in Sources */, 5674A7221F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, + 564CE4F121B2E08A00652B19 /* ValueObservationMapTests.swift in Sources */, 5690C3271D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */, 560FC5A51CB00B880014AA8E /* CGFloatTests.swift in Sources */, 56FF45571D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, @@ -2623,6 +2719,7 @@ 5653EBB920961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */, 567156461CB16729007DC145 /* TransactionObserverTests.swift in Sources */, 567A80551D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, + 5613ED9F21A96A6F00DC7A68 /* ValueObservationCombineTests.swift in Sources */, 5653EBBD20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 567156481CB16729007DC145 /* DatabaseValueTests.swift in Sources */, 5674A72E1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, @@ -2658,7 +2755,9 @@ 561667031D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */, 565EFAF01D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, 5653EBC520961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, + 564CE5C221B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */, 567156551CB16729007DC145 /* DatabaseValueConvertibleFetchTests.swift in Sources */, + 564CE4ED21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */, 567156561CB16729007DC145 /* DatabaseErrorTests.swift in Sources */, 564F9C201F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, 562393741DEE104400A6B01F /* MapCursorTests.swift in Sources */, @@ -2684,6 +2783,7 @@ 5698ACD01DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 569178481CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */, 5674A7241F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, + 564CE4F221B2E08A00652B19 /* ValueObservationMapTests.swift in Sources */, 5634B1091CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, 567156601CB16729007DC145 /* DatabaseFunctionTests.swift in Sources */, 567156611CB16729007DC145 /* RecordWithColumnNameManglingTests.swift in Sources */, @@ -2724,17 +2824,21 @@ 56AFC9F11CB1A8BB00F48B96 /* QueryInterfaceRequest.swift in Sources */, 56AFC9F21CB1A8BB00F48B96 /* SQLCollatedExpression.swift in Sources */, 5653EB9A20961FC000F46237 /* ForeignKeyRequest.swift in Sources */, + 5613ED8221A95E8400DC7A68 /* ValueObservation+Row.swift in Sources */, 566B91371FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215E1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, + 5613ED8A21A95E8400DC7A68 /* ValueObservation+Count.swift in Sources */, 566475D71D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 5653EB9220961FC000F46237 /* HasOneAssociation.swift in Sources */, 56CEB5651EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FE1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD391DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, + 564CE5A721B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */, 566B91171FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 56AFC9F31CB1A8BB00F48B96 /* Database.swift in Sources */, 5674A7061F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 5653EC18209873A400F46237 /* SQLExpression+QueryInterface.swift in Sources */, + 564CE52721B312B700652B19 /* ValueObservation+MapReducer.swift in Sources */, 5659F4A41EA8D997004A4992 /* Result.swift in Sources */, 56AFC9F41CB1A8BB00F48B96 /* CGFloat.swift in Sources */, 56AFC9F51CB1A8BB00F48B96 /* Date.swift in Sources */, @@ -2758,6 +2862,7 @@ 56B964B51DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, 56AFC9FB1CB1A8BB00F48B96 /* SerializedDatabase.swift in Sources */, 56AFC9FC1CB1A8BB00F48B96 /* DatabaseMigrator.swift in Sources */, + 564CE4DE21B2DEF700652B19 /* ValueObservation+CompactMap.swift in Sources */, 56AFC9FD1CB1A8BB00F48B96 /* NSString.swift in Sources */, 56A8C2341D1914540096E9D4 /* UUID.swift in Sources */, 56CEB5051EAA2F4D00BFAF62 /* FTS4.swift in Sources */, @@ -2767,6 +2872,7 @@ 5656BF5F20C7248700F98521 /* QueryOrdering.swift in Sources */, 56D51D041EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 566475BE1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, + 5613ED8821A95E8400DC7A68 /* ValueReducer.swift in Sources */, 56AFCA001CB1A8BB00F48B96 /* Record.swift in Sources */, 5671FC241DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56AFCA031CB1A8BB00F48B96 /* TableRecord.swift in Sources */, @@ -2775,10 +2881,10 @@ 56AFCA061CB1A8BB00F48B96 /* Configuration.swift in Sources */, 56DAA2DF1DE9C827006E10C8 /* Cursor.swift in Sources */, 5674A6EE1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, + 5613ED8421A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, 5644DE7D20F8C903001FFDDE /* DatabaseValueConversion.swift in Sources */, 56AFCA071CB1A8BB00F48B96 /* DatabasePool.swift in Sources */, 56AFCA081CB1A8BB00F48B96 /* Statement.swift in Sources */, - 563B06B7217F3C5A00B38F35 /* ValueObservation.swift in Sources */, 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceQuery.swift in Sources */, 566B912F1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56AFCA0A1CB1A8BB00F48B96 /* Migration.swift in Sources */, @@ -2794,19 +2900,25 @@ 56AFCA0F1CB1A8BB00F48B96 /* NSNull.swift in Sources */, 56AFCA101CB1A8BB00F48B96 /* DatabaseQueue.swift in Sources */, 56CEB51D1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, + 564CE44121AA957000652B19 /* ValueObserver.swift in Sources */, 5674A6FE1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 5698AC7C1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56AFCA111CB1A8BB00F48B96 /* DatabaseError.swift in Sources */, 566AD8B61D5318F4002EC1A8 /* TableDefinition.swift in Sources */, + 5613ED8021A95E8400DC7A68 /* ValueObservation+Map.swift in Sources */, 5698AD251DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, + 564CE5BC21B8FBFD00652B19 /* DatabaseRegionObservation.swift in Sources */, 56AFCA121CB1A8BB00F48B96 /* NSNumber.swift in Sources */, 5653EB9820961FC000F46237 /* ForeignKey.swift in Sources */, 569A98FD2039B72D008D7DBF /* Fixits-3.0.swift in Sources */, + 5613ED8621A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 5653EB9620961FC000F46237 /* HasManyAssociation.swift in Sources */, 56AFCA141CB1A8BB00F48B96 /* StandardLibrary.swift in Sources */, + 5613ED7C21A95E8400DC7A68 /* ValueObservation.swift in Sources */, 56AFCA151CB1A8BB00F48B96 /* PersistableRecord.swift in Sources */, 567071F9208A00D4006AD95A /* SQLiteDateParser.swift in Sources */, 56AFCA161CB1A8BB00F48B96 /* StatementColumnConvertible.swift in Sources */, + 5613ED7E21A95E8400DC7A68 /* ValueObservation+Combine.swift in Sources */, 5653EC1B209873E600F46237 /* SQLGenerationContext.swift in Sources */, 566475A61D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABD1D107001006283EF /* NSData.swift in Sources */, @@ -2915,6 +3027,7 @@ 5653EBBA20961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */, 56176C761EACCCCA000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, 5623935C1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, + 5613EDA021A96A6F00DC7A68 /* ValueObservationCombineTests.swift in Sources */, 5653EBBE20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 5698AC851DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, 5698AC451DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, @@ -2950,7 +3063,9 @@ 56AFCA631CB1AA9900F48B96 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 5698AC8E1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 5653EBC620961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, + 564CE5C321B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */, 56AFCA641CB1AA9900F48B96 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, + 564CE4EE21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */, 56A8C24A1D1918F10096E9D4 /* FoundationUUIDTests.swift in Sources */, 56AFCA651CB1AA9900F48B96 /* DatabaseErrorTests.swift in Sources */, 564F9C231F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, @@ -2976,6 +3091,7 @@ 56AFCA6D1CB1AA9900F48B96 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 56AFCA6E1CB1AA9900F48B96 /* FoundationNSDateTests.swift in Sources */, 5674A7211F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, + 564CE4F321B2E08A00652B19 /* ValueObservationMapTests.swift in Sources */, 56AFCA6F1CB1AA9900F48B96 /* DatabaseTests.swift in Sources */, 56AFCA701CB1AA9900F48B96 /* QueryInterfaceRequestTests.swift in Sources */, 5634B10B1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, @@ -3091,6 +3207,7 @@ 5653EBBB20961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */, 56176C7C1EACCCCB000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, 5698AC861DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, + 5613EDA121A96A6F00DC7A68 /* ValueObservationCombineTests.swift in Sources */, 5653EBBF20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 5698AC461DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 56AF74711D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, @@ -3126,7 +3243,9 @@ 56AFCAB81CB1ABC800F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */, 5698AC8F1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 5653EBC720961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, + 564CE5C421B8FFD800652B19 /* DatabaseRegionObservationTests.swift in Sources */, 56AFCAB91CB1ABC800F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */, + 564CE4EF21B2E08300652B19 /* ValueObservationCompactMapTests.swift in Sources */, 56AFCABA1CB1ABC800F48B96 /* RecordEditedTests.swift in Sources */, 56AFCABB1CB1ABC800F48B96 /* DatabasePoolSchemaCacheTests.swift in Sources */, 564F9C241F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, @@ -3152,6 +3271,7 @@ 56AFCAC71CB1ABC800F48B96 /* FoundationNSDateTests.swift in Sources */, 56AFCAC81CB1ABC800F48B96 /* DatabaseTests.swift in Sources */, 5674A71E1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, + 564CE4F421B2E08A00652B19 /* ValueObservationMapTests.swift in Sources */, 56AFCAC91CB1ABC800F48B96 /* QueryInterfaceRequestTests.swift in Sources */, 5691784B1CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */, 56AFCACB1CB1ABC800F48B96 /* DatabaseFunctionTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 7b4462c5f..91458697c 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -8,6 +8,24 @@ /* Begin PBXBuildFile section */ 56071A501DB54ED300CA6E47 /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; + 5613ED6121A95E6100DC7A68 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */; }; + 5613ED6221A95E6100DC7A68 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */; }; + 5613ED6321A95E6100DC7A68 /* ValueObservation+Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5A21A95E6100DC7A68 /* ValueObservation+Combine.swift */; }; + 5613ED6421A95E6100DC7A68 /* ValueObservation+Combine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5A21A95E6100DC7A68 /* ValueObservation+Combine.swift */; }; + 5613ED6521A95E6100DC7A68 /* ValueObservation+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5B21A95E6100DC7A68 /* ValueObservation+Map.swift */; }; + 5613ED6621A95E6100DC7A68 /* ValueObservation+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5B21A95E6100DC7A68 /* ValueObservation+Map.swift */; }; + 5613ED6721A95E6100DC7A68 /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5C21A95E6100DC7A68 /* ValueObservation+Row.swift */; }; + 5613ED6821A95E6100DC7A68 /* ValueObservation+Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5C21A95E6100DC7A68 /* ValueObservation+Row.swift */; }; + 5613ED6921A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5D21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift */; }; + 5613ED6A21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5D21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift */; }; + 5613ED6B21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5E21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; }; + 5613ED6C21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5E21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */; }; + 5613ED6D21A95E6100DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5F21A95E6100DC7A68 /* ValueReducer.swift */; }; + 5613ED6E21A95E6100DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5F21A95E6100DC7A68 /* ValueReducer.swift */; }; + 5613ED6F21A95E6100DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED6021A95E6100DC7A68 /* ValueObservation+Count.swift */; }; + 5613ED7021A95E6100DC7A68 /* ValueObservation+Count.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED6021A95E6100DC7A68 /* ValueObservation+Count.swift */; }; + 5613EDA321A96A8100DC7A68 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613EDA221A96A8000DC7A68 /* ValueObservationCombineTests.swift */; }; + 5613EDA421A96A8100DC7A68 /* ValueObservationCombineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613EDA221A96A8000DC7A68 /* ValueObservationCombineTests.swift */; }; 561667041D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; 561667081D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; 5616AAF6207CD59400AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF4207CD59300AC3664 /* RequestProtocols.swift */; }; @@ -43,8 +61,6 @@ 562EA8361F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; }; 5636E9BE1D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; 5636E9C11D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; - 563B06BA217F3C6E00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06B8217F3C6E00B38F35 /* ValueObservation.swift */; }; - 563B06BB217F3C6E00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06B8217F3C6E00B38F35 /* ValueObservation.swift */; }; 563B06D12185E04600B38F35 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CC2185E04500B38F35 /* ValueObservationExtentTests.swift */; }; 563B06D22185E04600B38F35 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CC2185E04500B38F35 /* ValueObservationExtentTests.swift */; }; 563B06D32185E04600B38F35 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CD2185E04600B38F35 /* ValueObservationReadonlyTests.swift */; }; @@ -79,6 +95,22 @@ 5644DE7920F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7620F8C8E9001FFDDE /* DatabaseValueConversion.swift */; }; 5644DE7F20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */; }; 5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */; }; + 564CE43C21AA955B00652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueObserver.swift */; }; + 564CE43D21AA955B00652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueObserver.swift */; }; + 564CE4DA21B2DEEB00652B19 /* ValueObservation+CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4D921B2DEEB00652B19 /* ValueObservation+CompactMap.swift */; }; + 564CE4DB21B2DEEB00652B19 /* ValueObservation+CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4D921B2DEEB00652B19 /* ValueObservation+CompactMap.swift */; }; + 564CE4E021B2E04500652B19 /* ValueObservationCompactMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4DF21B2E04500652B19 /* ValueObservationCompactMapTests.swift */; }; + 564CE4E121B2E04500652B19 /* ValueObservationCompactMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4DF21B2E04500652B19 /* ValueObservationCompactMapTests.swift */; }; + 564CE4E321B2E05400652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */; }; + 564CE4E421B2E05400652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */; }; + 564CE52421B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */; }; + 564CE52521B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */; }; + 564CE5A221B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; + 564CE5A321B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */; }; + 564CE5B721B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */; }; + 564CE5B821B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */; }; + 564CE5C621B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */; }; + 564CE5C721B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */; }; 564E73F3203DA2AC000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; }; 564E73F4203DA2AD000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; }; 564F9C211F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; }; @@ -641,6 +673,15 @@ 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = ""; }; 560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = ""; }; 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; + 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservation.swift; sourceTree = ""; }; + 5613ED5A21A95E6100DC7A68 /* ValueObservation+Combine.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Combine.swift"; sourceTree = ""; }; + 5613ED5B21A95E6100DC7A68 /* ValueObservation+Map.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Map.swift"; sourceTree = ""; }; + 5613ED5C21A95E6100DC7A68 /* ValueObservation+Row.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Row.swift"; sourceTree = ""; }; + 5613ED5D21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+FetchableRecord.swift"; sourceTree = ""; }; + 5613ED5E21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DatabaseValueConvertible.swift"; sourceTree = ""; }; + 5613ED5F21A95E6100DC7A68 /* ValueReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueReducer.swift; sourceTree = ""; }; + 5613ED6021A95E6100DC7A68 /* ValueObservation+Count.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+Count.swift"; sourceTree = ""; }; + 5613EDA221A96A8000DC7A68 /* ValueObservationCombineTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCombineTests.swift; sourceTree = ""; }; 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; 5616AAF4207CD59300AC3664 /* RequestProtocols.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; @@ -669,7 +710,6 @@ 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReleaseMemoryTests.swift; sourceTree = ""; }; 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverSavepointsTests.swift; sourceTree = ""; }; 5636E9BB1D22574100B9B05F /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = ""; }; - 563B06B8217F3C6E00B38F35 /* ValueObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservation.swift; sourceTree = ""; }; 563B06CC2185E04500B38F35 /* ValueObservationExtentTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationExtentTests.swift; sourceTree = ""; }; 563B06CD2185E04600B38F35 /* ValueObservationReadonlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationReadonlyTests.swift; sourceTree = ""; }; 563B06CE2185E04600B38F35 /* ValueObservationFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationFetchTests.swift; sourceTree = ""; }; @@ -688,6 +728,14 @@ 5644DE7620F8C8E9001FFDDE /* DatabaseValueConversion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversion.swift; sourceTree = ""; }; 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; + 564CE43B21AA955B00652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = ""; }; + 564CE4D921B2DEEB00652B19 /* ValueObservation+CompactMap.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+CompactMap.swift"; sourceTree = ""; }; + 564CE4DF21B2E04500652B19 /* ValueObservationCompactMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCompactMapTests.swift; sourceTree = ""; }; + 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; + 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = ""; }; + 564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = ""; }; + 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = ""; }; + 564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = ""; }; 564E73E7203DA278000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; @@ -1043,6 +1091,25 @@ name = PersistableRecord; sourceTree = ""; }; + 5613ED5821A95E6100DC7A68 /* ValueObservation */ = { + isa = PBXGroup; + children = ( + 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */, + 5613ED5A21A95E6100DC7A68 /* ValueObservation+Combine.swift */, + 564CE4D921B2DEEB00652B19 /* ValueObservation+CompactMap.swift */, + 5613ED6021A95E6100DC7A68 /* ValueObservation+Count.swift */, + 5613ED5E21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */, + 564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */, + 5613ED5D21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift */, + 5613ED5B21A95E6100DC7A68 /* ValueObservation+Map.swift */, + 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */, + 5613ED5C21A95E6100DC7A68 /* ValueObservation+Row.swift */, + 564CE43B21AA955B00652B19 /* ValueObserver.swift */, + 5613ED5F21A95E6100DC7A68 /* ValueReducer.swift */, + ); + path = ValueObservation; + sourceTree = ""; + }; 5614DEEE1BA9D6F9003163B3 /* Frameworks */ = { isa = PBXGroup; children = ( @@ -1063,6 +1130,7 @@ 56300B5C1C53C38F005A543B /* QueryInterface */, 56A238251B9C74A90082EB20 /* Record */, 56176C9F1EACEE15000F3F2B /* Support */, + 563B06DB2185E04E00B38F35 /* ValueObservation */, ); path = GRDBTests; sourceTree = ""; @@ -1186,10 +1254,13 @@ 563B06DB2185E04E00B38F35 /* ValueObservation */ = { isa = PBXGroup; children = ( + 5613EDA221A96A8000DC7A68 /* ValueObservationCombineTests.swift */, + 564CE4DF21B2E04500652B19 /* ValueObservationCompactMapTests.swift */, 563B06FE21861D9D00B38F35 /* ValueObservationCountTests.swift */, 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */, 563B06CC2185E04500B38F35 /* ValueObservationExtentTests.swift */, 563B06CE2185E04600B38F35 /* ValueObservationFetchTests.swift */, + 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */, 563B06CD2185E04600B38F35 /* ValueObservationReadonlyTests.swift */, 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */, 563B06CF2185E04600B38F35 /* ValueObservationReducerTests.swift */, @@ -1335,6 +1406,7 @@ 560A37A91C90084600949E71 /* DatabasePool */, 563363BB1C93FD32000BE133 /* DatabaseQueue */, 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */, + 564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */, 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */, 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */, 56A238131B9C74A90082EB20 /* DatabaseTests.swift */, @@ -1355,7 +1427,6 @@ 56A238201B9C74A90082EB20 /* Statement */, 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */, 5607EFD11BB8253300605DE3 /* TransactionObserver */, - 563B06DB2185E04E00B38F35 /* ValueObservation */, ); name = Core; sourceTree = ""; @@ -1433,6 +1504,7 @@ 56A238741B9C75030082EB20 /* DatabaseQueue.swift */, 563363BF1C942C04000BE133 /* DatabaseReader.swift */, 569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */, + 564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */, 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */, 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */, 56A238751B9C75030082EB20 /* DatabaseValue.swift */, @@ -1449,7 +1521,6 @@ 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, 5605F1471C672E4000235C62 /* Support */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, - 563B06B8217F3C6E00B38F35 /* ValueObservation.swift */, ); path = Core; sourceTree = ""; @@ -1586,6 +1657,7 @@ 56A2389F1B9C753B0082EB20 /* Record */, DC37743319C8CFCE004FCF85 /* Supporting Files */, 5659F4861EA8D94E004A4992 /* Utils */, + 5613ED5821A95E6100DC7A68 /* ValueObservation */, ); path = GRDB; sourceTree = ""; @@ -1901,17 +1973,21 @@ 56BB6EAE1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, F3BA801A1CFB2876003DC1BA /* StatementColumnConvertible.swift in Sources */, 5653EB4C20961F6100F46237 /* ForeignKeyRequest.swift in Sources */, + 5613ED6821A95E6100DC7A68 /* ValueObservation+Row.swift in Sources */, 566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215F1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, + 5613ED7021A95E6100DC7A68 /* ValueObservation+Count.swift in Sources */, 566475D81D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 5653EB4420961F6100F46237 /* HasOneAssociation.swift in Sources */, 56CEB5661EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FF1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD3A1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, + 564CE5A321B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */, 566B91181FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, F3BA80181CFB2876003DC1BA /* SerializedDatabase.swift in Sources */, 5674A7051F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 5659F4A51EA8D997004A4992 /* Result.swift in Sources */, + 564CE52521B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */, F3BA800D1CFB2871003DC1BA /* DatabasePool.swift in Sources */, F3BA800B1CFB286D003DC1BA /* Database.swift in Sources */, F3BA80341CFB28A4003DC1BA /* Record.swift in Sources */, @@ -1935,6 +2011,7 @@ F3BA80131CFB2876003DC1BA /* DatabaseValue.swift in Sources */, 56B964B61DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, F3BA80171CFB2876003DC1BA /* RowAdapter.swift in Sources */, + 564CE4DB21B2DEEB00652B19 /* ValueObservation+CompactMap.swift in Sources */, F3BA802F1CFB289B003DC1BA /* QueryInterfaceQuery.swift in Sources */, 56CEB5061EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 56CEB55F1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, @@ -1944,6 +2021,7 @@ 5656BF5B20C7247100F98521 /* QueryOrdering.swift in Sources */, 56D51D051EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, F3BA80151CFB2876003DC1BA /* DatabaseWriter.swift in Sources */, + 5613ED6E21A95E6100DC7A68 /* ValueReducer.swift in Sources */, F3BA800A1CFB286A003DC1BA /* Configuration.swift in Sources */, 566475BF1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 5671FC251DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, @@ -1952,10 +2030,10 @@ F3BA801D1CFB288C003DC1BA /* DatabaseDateComponents.swift in Sources */, 5674A6ED1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 5657AB141D10899D006283EF /* URL.swift in Sources */, + 5613ED6A21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, 5644DE7920F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */, 56DAA2E01DE9C827006E10C8 /* Cursor.swift in Sources */, F3BA800C1CFB286F003DC1BA /* DatabaseError.swift in Sources */, - 563B06BB217F3C6E00B38F35 /* ValueObservation.swift in Sources */, 566B91301FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA80221CFB288C003DC1BA /* NSNumber.swift in Sources */, 5653EB4620961F6100F46237 /* AssociationQuery.swift in Sources */, @@ -1971,19 +2049,25 @@ 56B964BE1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */, 56CEB51E1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, + 564CE43D21AA955B00652B19 /* ValueObserver.swift in Sources */, 5674A6FD1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */, 5698AC7D1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 566AD8B71D5318F4002EC1A8 /* TableDefinition.swift in Sources */, + 5613ED6621A95E6100DC7A68 /* ValueObservation+Map.swift in Sources */, 5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, + 564CE5B821B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */, F3BA802C1CFB289B003DC1BA /* SQLCollatedExpression.swift in Sources */, 5653EB4A20961F6100F46237 /* ForeignKey.swift in Sources */, 569A98F92039B716008D7DBF /* Fixits-3.0.swift in Sources */, + 5613ED6C21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 5653EB4820961F6100F46237 /* HasManyAssociation.swift in Sources */, F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */, + 5613ED6221A95E6100DC7A68 /* ValueObservation.swift in Sources */, F3BA80361CFB28A4003DC1BA /* TableRecord.swift in Sources */, 567071F5208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, F3BA80271CFB2891003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, + 5613ED6421A95E6100DC7A68 /* ValueObservation+Combine.swift in Sources */, 5653EC092098737400F46237 /* SQLGenerationContext.swift in Sources */, 566475A71D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABE1D107001006283EF /* NSData.swift in Sources */, @@ -2092,6 +2176,7 @@ 5653EB6920961FB200F46237 /* AssociationParallelSQLTests.swift in Sources */, F3BA80B71CFB2FCD003DC1BA /* DatabaseErrorTests.swift in Sources */, 5698ACCC1DA62A2D0056AF8C /* FTS5TokenizerTests.swift in Sources */, + 5613EDA421A96A8100DC7A68 /* ValueObservationCombineTests.swift in Sources */, 5653EB6B20961FB200F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 5690C33E1D23E7D200E59934 /* FoundationDateTests.swift in Sources */, 567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, @@ -2127,7 +2212,9 @@ F3BA812B1CFB3063003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */, 5698ACA51DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, 5653EB6F20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, + 564CE5C721B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */, F3BA80B11CFB2FC4003DC1BA /* DatabaseTests.swift in Sources */, + 564CE4E121B2E04500652B19 /* ValueObservationCompactMapTests.swift in Sources */, 56A8C24E1D1918F30096E9D4 /* FoundationUUIDTests.swift in Sources */, 564F9C251F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, 5657AB3D1D108BA9006283EF /* FoundationDataTests.swift in Sources */, @@ -2153,6 +2240,7 @@ 5657AB5D1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, F3BA81241CFB3063003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 5674A71F1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, + 564CE4E421B2E05400652B19 /* ValueObservationMapTests.swift in Sources */, F3BA80E81CFB3016003DC1BA /* RowFromDictionaryTests.swift in Sources */, 562393671DEE06D300A6B01F /* CursorTests.swift in Sources */, F3BA80B41CFB2FC9003DC1BA /* DatabaseQueueReadOnlyTests.swift in Sources */, @@ -2193,17 +2281,21 @@ 56BB6EAB1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, F3BA80761CFB2E55003DC1BA /* StatementColumnConvertible.swift in Sources */, 5653EB4B20961F6100F46237 /* ForeignKeyRequest.swift in Sources */, + 5613ED6721A95E6100DC7A68 /* ValueObservation+Row.swift in Sources */, 566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215C1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, + 5613ED6F21A95E6100DC7A68 /* ValueObservation+Count.swift in Sources */, 566475D51D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 5653EB4320961F6100F46237 /* HasOneAssociation.swift in Sources */, 56CEB5631EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD371DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, + 564CE5A221B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */, 566B91151FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, F3BA80741CFB2E55003DC1BA /* SerializedDatabase.swift in Sources */, 5674A7041F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 5659F4A21EA8D997004A4992 /* Result.swift in Sources */, + 564CE52421B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */, F3BA80691CFB2E55003DC1BA /* DatabasePool.swift in Sources */, F3BA80671CFB2E55003DC1BA /* Database.swift in Sources */, F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */, @@ -2227,6 +2319,7 @@ F3BA806F1CFB2E55003DC1BA /* DatabaseValue.swift in Sources */, 56B964B31DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, F3BA80731CFB2E55003DC1BA /* RowAdapter.swift in Sources */, + 564CE4DA21B2DEEB00652B19 /* ValueObservation+CompactMap.swift in Sources */, F3BA808B1CFB2E70003DC1BA /* QueryInterfaceQuery.swift in Sources */, 56CEB5031EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 56CEB55C1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, @@ -2236,6 +2329,7 @@ 5656BF5A20C7247100F98521 /* QueryOrdering.swift in Sources */, 56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, F3BA80711CFB2E55003DC1BA /* DatabaseWriter.swift in Sources */, + 5613ED6D21A95E6100DC7A68 /* ValueReducer.swift in Sources */, F3BA80661CFB2E55003DC1BA /* Configuration.swift in Sources */, 566475BC1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 5671FC221DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, @@ -2244,10 +2338,10 @@ F3BA80791CFB2E61003DC1BA /* DatabaseDateComponents.swift in Sources */, 5674A6EC1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 5657AB111D10899D006283EF /* URL.swift in Sources */, + 5613ED6921A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */, 5644DE7820F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */, 56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */, F3BA80681CFB2E55003DC1BA /* DatabaseError.swift in Sources */, - 563B06BA217F3C6E00B38F35 /* ValueObservation.swift in Sources */, 566B912D1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA807E1CFB2E61003DC1BA /* NSNumber.swift in Sources */, 5653EB4520961F6100F46237 /* AssociationQuery.swift in Sources */, @@ -2263,19 +2357,25 @@ 56B964BB1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */, 56CEB51B1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, + 564CE43C21AA955B00652B19 /* ValueObserver.swift in Sources */, 5674A6FC1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */, 5698AC7A1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 566AD8B41D5318F4002EC1A8 /* TableDefinition.swift in Sources */, + 5613ED6521A95E6100DC7A68 /* ValueObservation+Map.swift in Sources */, 5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, + 564CE5B721B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */, F3BA80881CFB2E70003DC1BA /* SQLCollatedExpression.swift in Sources */, 5653EB4920961F6100F46237 /* ForeignKey.swift in Sources */, 569A98F82039B716008D7DBF /* Fixits-3.0.swift in Sources */, + 5613ED6B21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */, 5653EB4720961F6100F46237 /* HasManyAssociation.swift in Sources */, F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */, + 5613ED6121A95E6100DC7A68 /* ValueObservation.swift in Sources */, F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */, 567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, + 5613ED6321A95E6100DC7A68 /* ValueObservation+Combine.swift in Sources */, 5653EC082098737400F46237 /* SQLGenerationContext.swift in Sources */, 566475A41D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABB1D107001006283EF /* NSData.swift in Sources */, @@ -2384,6 +2484,7 @@ 5653EB6820961FB200F46237 /* AssociationParallelSQLTests.swift in Sources */, F3BA80F21CFB301A003DC1BA /* DatabaseSavepointTests.swift in Sources */, F3BA80B81CFB2FCD003DC1BA /* DatabaseErrorTests.swift in Sources */, + 5613EDA321A96A8100DC7A68 /* ValueObservationCombineTests.swift in Sources */, 5653EB6A20961FB200F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 5698AC061D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, F3BA80FA1CFB3021003DC1BA /* SelectStatementTests.swift in Sources */, @@ -2419,7 +2520,9 @@ F3BA81311CFB3064003DC1BA /* RecordPrimaryKeySingleTests.swift in Sources */, 5698AC431DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 5653EB6E20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, + 564CE5C621B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */, F3BA80E11CFB300F003DC1BA /* DatabaseValueConversionTests.swift in Sources */, + 564CE4E021B2E04500652B19 /* ValueObservationCompactMapTests.swift in Sources */, 5623931B1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 564F9C211F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, F3BA80ED1CFB3017003DC1BA /* RowFromDictionaryTests.swift in Sources */, @@ -2445,6 +2548,7 @@ 56741EAB1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56B964D61DA521450002DA19 /* FTS5TableBuilderTests.swift in Sources */, 5674A71D1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, + 564CE4E321B2E05400652B19 /* ValueObservationMapTests.swift in Sources */, 562393511DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, F3BA812D1CFB3064003DC1BA /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, 5698AC831DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, diff --git a/README.md b/README.md index ba7ab2927..2f7014917 100644 --- a/README.md +++ b/README.md @@ -359,9 +359,6 @@ The repository comes with a [demo application](DemoApps/GRDBDemoiOS/README.md) t - how to define a simple [Codable Record](#codable-records) - how to track database changes with [ValueObservation] and [FetchedRecordsController]. -

- -

Database Connections ==================== @@ -2061,7 +2058,7 @@ Before jumping in the low-level wagon, here is the list of all SQLite APIs used - `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/3.5/Structs/Configuration.html) - `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/3.5/Classes/Database.html) - `sqlite3_close`, `sqlite3_close_v2`, `sqlite3_next_stmt`, `sqlite3_open_v2`: see [Database Connections](#database-connections) -- `sqlite3_commit_hook`, `sqlite3_rollback_hook`, `sqlite3_update_hook`: see [TransactionObserver Protocol](#transactionobserver-protocol), [ValueObservation], [FetchedRecordsController] +- `sqlite3_commit_hook`, `sqlite3_rollback_hook`, `sqlite3_update_hook`: see [TransactionObserver Protocol](#transactionobserver-protocol), [DatabaseRegionObservation], [ValueObservation], [FetchedRecordsController] - `sqlite3_config`: see [Error Log](#error-log) - `sqlite3_create_collation_v2`: see [String Comparison](#string-comparison) - `sqlite3_db_release_memory`: see [Memory Management](#memory-management) @@ -2177,8 +2174,10 @@ It is possible to [avoid useless updates](#record-comparison): ```swift if let player = try Player.fetchOne(db, key: 1) { - player.score = 1000 - try player.updateChanges(db) // does nothing if score has not changed + // does not hit the database if score has not changed + try player.updateChanges(db) { + $0.score = 1000 + } } ``` @@ -2581,6 +2580,7 @@ try place.insert(db) // INSERT try place.update(db) // UPDATE try place.update(db, columns: ...) // UPDATE try place.updateChanges(db, from: ...) // Maybe UPDATE +try place.updateChanges(db) { ... } // Maybe UPDATE try place.updateChanges(db) // Maybe UPDATE (Record class only) try place.delete(db) // DELETE try place.exists(db) @@ -2936,39 +2936,72 @@ class Place: Record { ## Record Comparison -**Records can compare against other records, or against previous versions of themselves.** +**Records that adopt a [PersistableRecord] protocol can compare against other records, or against previous versions of themselves.** This helps avoiding costly UPDATE statements when a record has not been edited. -You can use the `updateChanges` method, available on the [PersistableRecord] protocol, which performs an update of the changed columns only (and does nothing if record has no change): +- [The `updateChanges` Methods](#the-updatechanges-methods) +- [The `databaseEquals` Method](#the-databaseequals-method) +- [The `databaseChanges` and `hasDatabaseChanges` Methods](#the-databasechanges-and-hasdatabasechanges-methods) -```swift -let oldPlayer = try Player.fetchOne(db, ...) -var newPlayer = oldPlayer -newPlayer.score = 100 -if try newPlayer.updateChanges(db, from: oldPlayer) { - print("player was modified, and updated in the database") -} else { - print("player was not modified") -} -``` -> :point_up: **Note**: The comparison is performed on the database representation of records. As long as your record type adopts a PersistableRecord protocol, you don't need to care about Equatable. +### The `updateChanges` Methods -The [Record](#record-class) class is able to compare against itself, and knows if it has changes that have not been saved since it was last fetched or persisted: +The `updateChanges` methods perform a database update of the changed columns only (and does nothing if record has no change). -```swift -// Record class only -let player = try Player.fetchOne(db, ...) -player.score = 100 -if try player.updateChanges(db) { - print("player was modified, and updated in the database") -} else { - print("player was not modified") -} -``` +- `updateChanges(_:from:)` -You can also use the `databaseEquals` method, which returns whether two records have the same database representation: + This method lets you compare two records: + + ```swift + if let oldPlayer = try Player.fetchOne(db, key: 42) { + var newPlayer = oldPlayer + newPlayer.score = 100 + if try newPlayer.updateChanges(db, from: oldPlayer) { + print("player was modified, and updated in the database") + } else { + print("player was not modified, and database was not hit") + } + } + ``` + +- `updateChanges(_:with:)` + + This method lets you update a record in place: + + ```swift + if var player = try Player.fetchOne(db, key: 42) { + let modified = player.updateChanges(db) { + $0.score = 100 + } + if modified { + print("player was modified, and updated in the database") + } else { + print("player was not modified, and database was not hit") + } + } + ``` + +- `updateChanges(_:)` (Record class only) + + Instances of the [Record](#record-class) class are able to compare against themselves, and know if they have changes that have not been saved since the last fetch or saving: + + ```swift + // Record class only + if let player = try Player.fetchOne(db, key: 42) { + player.score = 100 + if try player.updateChanges(db) { + print("player was modified, and updated in the database") + } else { + print("player was not modified, and database was not hit") + } + } + ``` + + +### The `databaseEquals` Method + +This method returns whether two records have the same database representation: ```swift let oldPlayer: Player = ... @@ -2978,11 +3011,40 @@ if newPlayer.databaseEquals(oldPlayer) == false { } ``` -Again, [Record](#record-class) instances can compare against themselves, with the `hasDatabaseChanges` property: +> :point_up: **Note**: The comparison is performed on the database representation of records. As long as your record type adopts a PersistableRecord protocol, you don't need to care about Equatable. + + +### The `databaseChanges` and `hasDatabaseChanges` Methods + +`databaseChanges(from:)` returns a dictionary of differences between two records: + +```swift +let oldPlayer = Player(id: 1, name: "Arthur", score: 100) +let newPlayer = Player(id: 1, name: "Arthur", score: 1000) +for (column, oldValue) in newPlayer.databaseChanges(from: oldPlayer) { + print("\(column) was \(oldValue)") +} +// prints "score was 100" +``` + +The [Record](#record-class) class is able to compare against itself: ```swift // Record class only -player.score = 100 +let player = Player(id: 1, name: "Arthur", score: 100) +try player.insert(db) +player.score = 1000 +for (column, oldValue) in player.databaseChanges { + print("\(column) was \(oldValue)") +} +// prints "score was 100" +``` + +[Record](#record-class) instances also have a `hasDatabaseChanges` property: + +```swift +// Record class only +player.score = 1000 if player.hasDatabaseChanges { try player.save(db) } @@ -3429,6 +3491,7 @@ This is the list of record methods, along with their required protocols. The [Re | `record.update(db)` | [PersistableRecord] | | | `record.update(db, columns:...)` | [PersistableRecord] | | | `record.updateChanges(db, from:...)` | [PersistableRecord] | [*](#record-comparison) | +| `record.updateChanges(db) { ... }` | [PersistableRecord] | [*](#record-comparison) | | `record.updateChanges(db)` | [Record](#record-class) | [*](#record-comparison) | | **Delete Records** | | | | `record.delete(db)` | [PersistableRecord] | | @@ -3465,6 +3528,7 @@ This is the list of record methods, along with their required protocols. The [Re | `record.databaseEquals(...)` | [PersistableRecord] | | | `record.databaseChanges(from:...)` | [PersistableRecord] | | | `record.updateChanges(db, from:...)` | [PersistableRecord] | | +| `record.updateChanges(db) { ... }` | [PersistableRecord] | | | `record.hasDatabaseChanges` | [Record](#record-class) | | | `record.databaseChanges` | [Record](#record-class) | | | `record.updateChanges(db)` | [Record](#record-class) | | @@ -4507,7 +4571,7 @@ The `prepare` method returns a prepared statement and an optional row adapter. T The `fetchCount` method has a default implementation that builds a correct but naive SQL query from the statement returned by `prepare`: `SELECT COUNT(*) FROM (...)`. Adopting types can refine the counting SQL by customizing their `fetchCount` implementation. -The base `DatabaseRegionConvertible` protocol is involved in [database observation](#database-changes-observation). For more information, see [DatabaseRegion](#databaseregion), and [ValueObservation]. +The base `DatabaseRegionConvertible` protocol is involved in [database observation](#database-changes-observation). For more information, see [DatabaseRegion], [DatabaseRegionObservation], and [ValueObservation]. The FetchRequest protocol is adopted, for example, by [query interface requests](#requests): @@ -5782,10 +5846,10 @@ Database Changes Observation GRDB puts this SQLite feature to some good use, and lets you observe the database in various ways: -- [After Commit Hook](#after-commit-hook): The simplest way to handle successful transactions. +- [After Commit Hook](#after-commit-hook): Handle successful transactions one by one. +- [ValueObservation and DatabaseRegionObservation]: Automated tracking of database requests. +- [FetchedRecordsController]: Animate table views according to database changes. - [TransactionObserver Protocol](#transactionobserver-protocol): Low-level database observation. -- [ValueObservation]: Automated tracking of database changes. -- [FetchedRecordsController]: Automated tracking of database changes, with table view animations. - [RxGRDB]: Automated tracking of database changes, with [RxSwift](https://github.com/ReactiveX/RxSwift). Database observation requires that a single [database queue](#database-queues) or [pool](#database-pools) is kept open for all the duration of the database usage. @@ -5850,344 +5914,46 @@ try dbQueue.write { db in ``` -## TransactionObserver Protocol +## ValueObservation and DatabaseRegionObservation -The `TransactionObserver` protocol lets you **observe database changes and transactions**: +**ValueObservation and DatabaseRegionObservation** are two database observations tools that track changes in database [requests](#requests). ```swift -protocol TransactionObserver : class { - /// Notifies a database change: - /// - event.kind (insert, update, or delete) - /// - event.tableName - /// - event.rowID - /// - /// For performance reasons, the event is only valid for the duration of - /// this method call. If you need to keep it longer, store a copy: - /// event.copy(). - func databaseDidChange(with event: DatabaseEvent) - - /// Filters the database changes that should be notified to the - /// `databaseDidChange(with:)` method. - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool - - /// An opportunity to rollback pending changes by throwing an error. - func databaseWillCommit() throws - - /// Database changes have been committed. - func databaseDidCommit(_ db: Database) - - /// Database changes have been rollbacked. - func databaseDidRollback(_ db: Database) -} +// Let's observe all players! +let request = Player.all() ``` -- [Activate a Transaction Observer](#activate-a-transaction-observer) -- [Database Changes And Transactions](#database-changes-and-transactions) -- [Filtering Database Events](#filtering-database-events) -- [Observation Extent](#observation-extent) -- [DatabaseRegion](#databaseregion) -- [Support for SQLite Pre-Update Hooks](#support-for-sqlite-pre-update-hooks) - - -### Activate a Transaction Observer - -**To activate a transaction observer, add it to the database queue or pool:** +[ValueObservation] notifies your application with **fresh values** (this is what most applications need :+1:): ```swift -let observer = MyObserver() -dbQueue.add(transactionObserver: observer) -``` - -By default, database holds weak references to its transaction observers: they are not retained, and stop getting notifications after they are deallocated. See [Observation Extent](#observation-extent) for more options. - - -### Database Changes And Transactions - -**A transaction observer is notified of all database changes**: inserts, updates and deletes. This includes indirect changes triggered by ON DELETE and ON UPDATE actions associated to [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions), and [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). - -> :point_up: **Note**: the changes that are not notified are changes to internal system tables (such as `sqlite_master`), changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables, and the deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite). - -Notified changes are not actually written to disk until the [transaction](#transactions-and-savepoints) commits, and the `databaseDidCommit` callback is called. On the other side, `databaseDidRollback` confirms their invalidation: - -```swift -try dbQueue.write { db in - try db.execute("INSERT ...") // 1. didChange - try db.execute("UPDATE ...") // 2. didChange -} // 3. willCommit, 4. didCommit - -try dbQueue.inTransaction { db in - try db.execute("INSERT ...") // 1. didChange - try db.execute("UPDATE ...") // 2. didChange - return .rollback // 3. didRollback +let observation = ValueObservation.trackingAll(request) +let observer = observation.start(in: dbQueue) { players: [Player]? in + let names = players.map { $0.name }.joined(separator: ", ") + print("Fresh players: \(names)") } try dbQueue.write { db in - try db.execute("INSERT ...") // 1. didChange - throw SomeError() -} // 2. didRollback -``` - -Database statements that are executed outside of any transaction do not drop off the radar: - -```swift -try dbQueue.inDatabase { db in - try db.execute("INSERT ...") // 1. didChange, 2. willCommit, 3. didCommit - try db.execute("UPDATE ...") // 4. didChange, 5. willCommit, 6. didCommit + try Player(name: "Arthur").insert(db) } +// Prints "Fresh players: Arthur, ..." ``` -Changes that are on hold because of a [savepoint](https://www.sqlite.org/lang_savepoint.html) are only notified after the savepoint has been released. This makes sure that notified events are only events that have an opportunity to be committed: +[DatabaseRegionObservation] notifies your application with **database connections**, right after an impactful database transaction has been committed (reserved for more advanced use cases :nerd_face:): ```swift -try dbQueue.inTransaction { db in - try db.execute("INSERT ...") // 1. didChange - - try db.execute("SAVEPOINT foo") - try db.execute("UPDATE ...") // delayed - try db.execute("UPDATE ...") // delayed - try db.execute("RELEASE SAVEPOINT foo") // 2. didChange, 3. didChange - - try db.execute("SAVEPOINT foo") - try db.execute("UPDATE ...") // not notified - try db.execute("ROLLBACK TO SAVEPOINT foo") - - return .commit // 4. willCommit, 5. didCommit +let observation = DatabaseRegionObservation(tracking: request) +let observer = observation.start(in: dbQueue) { db: Database in + print("Player have changed.") } -``` - -**Eventual errors** thrown from `databaseWillCommit` are exposed to the application code: - -```swift -do { - try dbQueue.inTransaction { db in - ... - return .commit // 1. willCommit (throws), 2. didRollback - } -} catch { - // 3. The error thrown by the transaction observer. -} -``` - -> :point_up: **Note**: all callbacks are called in a protected dispatch queue, and serialized with all database updates. -> -> :point_up: **Note**: the databaseDidChange(with:) and databaseWillCommit() callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument. - - -[ValueObservation], [FetchedRecordsController], and [RxGRDB] are based on the TransactionObserver protocol. - -See also [TableChangeObserver.swift](https://gist.github.com/groue/2e21172719e634657dfd), which shows a transaction observer that notifies of modified database tables with NSNotificationCenter. - - -### Filtering Database Events - -**Transaction observers can avoid being notified of database changes they are not interested in.** - -The filtering happens in the `observes(eventsOfKind:)` method, which tells whether the observer wants notification of specific kinds of changes, or not. For example, here is how an observer can focus on the changes that happen on the "player" database table: - -```swift -class PlayerObserver: TransactionObserver { - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - // Only observe changes to the "player" table. - return eventKind.tableName == "player" - } - - func databaseDidChange(with event: DatabaseEvent) { - // This method is only called for changes that happen to - // the "player" table. - } -} -``` - -Generally speaking, the `observes(eventsOfKind:)` method can distinguish insertions from deletions and updates, and is also able to inspect the columns that are about to be changed: - -```swift -class PlayerScoreObserver: TransactionObserver { - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - // Only observe changes to the "score" column of the "player" table. - switch eventKind { - case .insert(let tableName): - return tableName == "player" - case .delete(let tableName): - return tableName == "player" - case .update(let tableName, let columnNames): - return tableName == "player" && columnNames.contains("score") - } - } -} -``` - -When the `observes(eventsOfKind:)` method returns false for all event kinds, the observer is still notified of commits and rollbacks: - -```swift -class PureTransactionObserver: TransactionObserver { - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - // Ignore all individual changes - return false - } - - func databaseDidChange(with event: DatabaseEvent) { /* Never called */ } - func databaseWillCommit() throws { /* Called before commit */ } - func databaseDidRollback(_ db: Database) { /* Called on rollback */ } - func databaseDidCommit(_ db: Database) { /* Called on commit */ } -} -``` - -For more information about event filtering, see [DatabaseRegion](#databaseregion). - - -### Observation Extent - -**You can specify how long an observer is notified of database changes and transactions.** - -The `remove(transactionObserver:)` method explicitly stops notifications, at any time: - -```swift -// From a database queue or pool: -dbQueue.remove(transactionObserver: observer) - -// From a database connection: -dbQueue.inDatabase { db in - db.remove(transactionObserver: observer) -} -``` - -Alternatively, use the `extent` parameter of the `add(transactionObserver:extent:)` method: - -```swift -let observer = MyObserver() - -// On a database queue or pool: -dbQueue.add(transactionObserver: observer) // default extent -dbQueue.add(transactionObserver: observer, extent: .observerLifetime) -dbQueue.add(transactionObserver: observer, extent: .nextTransaction) -dbQueue.add(transactionObserver: observer, extent: .databaseLifetime) - -// On a database connection: -dbQueue.inDatabase { db in - db.add(transactionObserver: ...) -} -``` - -- The default extent is `.observerLifetime`: the database holds a weak reference to the observer, and the observation automatically ends when the observer is deallocated. Meanwhile, observer is notified of all changes and transactions. - -- `.nextTransaction` activates the observer until the current or next transaction completes. The database keeps a strong reference to the observer until its `databaseDidCommit` or `databaseDidRollback` method is eventually called. Hereafter the observer won't get any further notification. - -- `.databaseLifetime` has the database retain and notify the observer until the database connection is closed. - -Finally, an observer may ignore all database changes until the end of the current transaction: - -```swift -class PlayerObserver: TransactionObserver { - var playerTableWasModified = false - - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - return eventKind.tableName == "player" - } - - func databaseDidChange(with event: DatabaseEvent) { - playerTableWasModified = true - - // It is pointless to keep on tracking further changes: - stopObservingDatabaseChangesUntilNextTransaction() - } -} -``` - -After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChange(with:)` method will not be notified of any change for the remaining duration of the current transaction. This helps GRDB optimize database observation. - - -### DatabaseRegion - -**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/3.5/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**. - -A request knows which database modifications can impact its results. It can communicate this information to a transaction observer by the way of a database region. - -You start by building regions: - -```swift try dbQueue.write { db in - let teamRegion = try Team.filter(key: 1).databaseRegion(db) - let playersRegion = try SQLRequest("SELECT * FROM player").databaseRegion(db) - let maxScoreRegion = try Player.select(max(Column("score"))).databaseRegion(db) + try Player(name: "Barbara").insert(db) +} +// Prints "Players have changed." ``` -You can group regions: - -```swift - let region = teamRegion.union(playersRegion).union(maxScoreRegion) -} -``` - -There are two special regions: `DatabaseRegion()` (the empty region), and `DatabaseRegion.fullDatabase` (the region that spans the whole database). - -Regions feed the `observes(eventsOfKind:)` and `databaseDidChange(with:)` methods of transaction observers. For example: - -```swift -// A transaction observer which notifies all changes to a database region. -class DatabaseRegionObserver: TransactionObserver { - let region: DatabaseRegion - var regionIsModified = false - - init(region: DatabaseRegion) { - self.region = region - } - - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - return region.isModified(byEventsOfKind: eventKind) - } - - func databaseDidChange(with event: DatabaseEvent) { - if region.isModified(by: event) { - regionIsModified = true - stopObservingDatabaseChangesUntilNextTransaction() - } - } - - func databaseDidRollback(_ db: Database) { - regionIsModified = false - } - - func databaseDidCommit(_ db: Database) { - if regionIsModified == false { return } - regionIsModified = false - - // You'll customize your handling of changes here: - print("Region has been modified.") - } -} - -// Observe a region -try dbQueue.write { db in - observer = DatabaseRegionObserver(region: region) - db.add(transactionObserver: observer) -} -``` - -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. - -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. - -Similarly, observing the region of `Country.filter(key: "FR")` will notify all changes that happen to the whole `country` table. That is because SQLite only notifies the numerical [rowid](https://www.sqlite.org/rowidtable.html) of changed rows, and we can't check if it is the row "FR" that has been changed, or another. This limitation does not apply to tables whose primary key *is* the rowid: `Player.filter(key: 42)` will only notify of changes performed on the row with id 42. - - -### Support for SQLite Pre-Update Hooks - -A [custom SQLite build](Documentation/CustomSQLiteBuilds.md) can activate [SQLite "preupdate hooks"](https://sqlite.org/c3ref/preupdate_count.html). In this case, TransactionObserverType gets an extra callback which lets you observe individual column values in the rows modified by a transaction: - -```swift -protocol TransactionObserverType : class { - #if SQLITE_ENABLE_PREUPDATE_HOOK - /// Notifies before a database change (insert, update, or delete) - /// with change information (initial / final values for the row's - /// columns). - /// - /// The event is only valid for the duration of this method call. If you - /// need to keep it longer, store a copy: event.copy(). - func databaseWillChange(with event: DatabasePreUpdateEvent) - #endif -} -``` +- [ValueObservation] +- [DatabaseRegionObservation] ## ValueObservation @@ -6196,6 +5962,18 @@ protocol TransactionObserverType : class { Changes are only notified after they have been committed in the database. No insertion, update, or deletion in tracked tables is missed. This includes indirect changes triggered by [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). + +- **[ValueObservation Usage](#valueobservation-usage)** +- [ValueObservation.trackingCount, trackingOne, trackingAll](#valueobservationtrackingcount-trackingone-trackingall) +- [ValueObservation.tracking(_:fetch:)](#valueobservationtracking_fetch) +- [ValueObservation Transformations](#valueobservation-transformations): [map](#valueobservationmap), [compactMap](#valueobservationcompactmap), ... +- [ValueObservation Error Handling](#valueobservation-error-handling) +- [ValueObservation Options](#valueobservation-options) +- [Advanced: ValueObservation.tracking(_:reducer:)](#advanced-valueobservationtracking_reducer) + + +### ValueObservation Usage + Here is a typical UIViewController which observes the database in order to keep its view up-to-date: ```swift @@ -6236,11 +6014,6 @@ The observer returned by the `start` method is stored in a property of the view > :bulb: **Tip**: see the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for a sample app that uses ValueObservation. -- [ValueObservation.trackingCount, trackingOne, trackingAll](#valueobservationtrackingcount-trackingone-trackingall) -- [ValueObservation.tracking(_:fetch:)](#valueobservationtracking_fetch) -- [ValueObservation.tracking(_:reducer:)](#valueobservationtracking_reducer) -- [ValueObservation Options](#valueobservation-options) - ### ValueObservation.trackingCount, trackingOne, trackingAll @@ -6303,95 +6076,113 @@ Those observations match the `fetchCount`, `fetchOne`, and `fetchAll` request me } ``` +> :point_up: **Note**: the observations returned by the [ValueObservation.trackingCount, trackingOne, and trackingAll](#valueobservationtrackingcount-trackingone-trackingall) methods perform a filtering of consecutive identical values, based on raw database values. + ### ValueObservation.tracking(_:fetch:) -Sometimes you need to observe several requests at the same time. For example, you need to observe changes in both a team and its players. +Observing the database is not always easy to express with simple requests, as above. -When this happens, you create a ValueObservation with the `ValueObservation.tracking(_:fetch:)` method, which accepts two parameters: - -1. The list of observed requests. -2. A closure that fetches a fresh value whenever one of the observed requests are modified. - -The fetch closure is granted an immutable view of the last committed state of the database: this means that fetched values are guaranteed to be **consistent**. - -For example: +For example, let's say that we have a struct that defines a "Hall of Fame": ```swift -// The two observed requests (the team and its players) -let teamRequest = Team.filter(key: 1) -let playersRequest = Player.filter(Column("teamId") == 1) +struct HallOfFame { + var totalPlayerCount: Int + var bestPlayers: [Player] -// The fetched value + /// Fetch a HallOfFame + static fetch(_ db: Database) throws -> HallOfFame { + let totalPlayerCount = try Player.fetchCount(db) + let bestPlayers = try Player + .order(Column("score").desc) + .limit(10) + .fetchAll(db) + return HallOfFame( + totalPlayerCount: totalPlayerCount, + bestPlayers: bestPlayers) + } +} + +let hallOfFame = try dbQueue.read { db in try HallOfFame.fetch(db) } +print(""" + Best players out of \(hallOfFame.totalPlayerCount): + \(hallOfFame.bestPlayers) + """) +``` + +In order to track changes in the Hall of Fame, we'll use the `ValueObservation.tracking(_:fetch:)` method. It accepts two parameters: + +1. A list of observed requests. +2. A closure that fetches a fresh value whenever one of the observed requests are modified. + +In our case, any change to the `player` table can impact the Hall of Fame. We thus track the request for all players, `Player.all()`, and fetch a new Hall of Fame whenever players change: + +```swift +let observation = ValueObservation.tracking(Player.all(), fetch: { db in + try HallOfFame.fetch(db) +}) + +let observer = observation.start(in: dbQueue) { hallOfFame: HallOfFame in + print(""" + Best players out of \(hallOfFame.totalPlayerCount): + \(hallOfFame.bestPlayers) + """) +} +``` + + +#### Filtering out Consecutive Identical Values + +It may happen that a database change does not modify the observed values. The Hall of Fame, for example, is not affected by changes that happen to the worst players. + +When such a database change happens, `ValueObservation.tracking(_:fetch:)` is triggered, just in case the best players would be modified, and ends up notifying identical consecutive values. + +You can filter out those duplicates with the [ValueObservation.distinctUntilChanged](#valueobservationdistinctuntilchanged) method. It requires the observed value to adopt the Equatable protocol: + +```swift +extension HallOfFame: Equatable { ... } + +let observation = ValueObservation + .tracking(Player.all(), fetch: HallOfFame.fetch) + .distinctUntilChanged() + +let observer = observation.start(in: dbQueue) { hallOfFame: HallOfFame in + print(""" + Best players out of \(hallOfFame.totalPlayerCount): + \(hallOfFame.bestPlayers) + """) +} +``` + + +#### DatabaseRegionConvertible Observation + +The initial parameter of the `ValueObservation.tracking(_:fetch:)` method can be fed with requests, and generally speaking, values that adopt the [DatabaseRegionConvertible] protocol. + +Thanks to DatabaseRegionConvertible, `TeamInfoRequest` below is not only able to fetch a team and its players, but also to be observed. + +```swift +/// A team and its players struct TeamInfo { var team: Team var players: [Player] } -let observation = ValueObservation.tracking( - teamRequest, playersRequest, - fetch: { db -> TeamInfo? in - guard let team = try teamRequest.fetchOne(db) else { - return nil - } - let players = try playersRequest.fetchAll(db) - return TeamInfo(team: team, players: players) - }) - -let observer = observation.start(in: dbQueue) { teamInfo: TeamInfo? in - print("Team and players have changed.") -} -``` - -It may happen that a database change does not modify the fetched values. In this case, you'll be notified with consecutive identical values. You can filter out those duplicates with the `ValueObservation.tracking(_:fetchDistinct:)` method. It requires the fetched value to adopt the Equatable protocol: - -```swift -// When the `player` table is changed, fetch the total number of players, and -// the ten best ones: -struct HallOfFame: Equatable { - var count: Int - var players: [Player] -} - -let observation = ValueObservation.tracking( - Player.all(), - fetchDistinct: { db -> HallOfFame in - let count = try Player.fetchCount(db) - let players = try Player - .order(Column("score").desc) - .limit(10) - .fetchAll(db) - return HallOfFame(count: count, players: players) - }) - -let observer = observation.start(in: dbQueue) { hallOfFame: HallOfFame in - print("Best players out of \(hallOfFame.count): \(hallOfFame.players)") -} -``` - -The initial parameter of the `ValueObservation.tracking(_:fetch:)` and `ValueObservation.tracking(_:fetchDistinct:)` methods can be fed with requests, and generally speaking, values that adopt the **DatabaseRegionConvertible** protocol. - -Use this protocol when you want to encapsulate your complex requests in a dedicated type. Our example above can be rewritten as below: - -```swift -struct TeamInfoRequest: DatabaseRegionConvertible { +/// A request that can fetch TeamInfo, given a team id. +struct TeamInfoRequest { var teamId: Int64 + /// The request for the team private var teamRequest: QueryInterfaceRequest { return Team.filter(key: teamId) } + /// The request for the players private var playersRequest: QueryInterfaceRequest { return Player.filter(Column("teamId") == teamId) } - // DatabaseRegionConvertible adoption - func databaseRegion(_ db: Database) throws -> DatabaseRegion { - let teamRegion = try teamRequest.databaseRegion(db) - let playersRegion = try playersRequest.databaseRegion(db) - return teamRegion.union(playersRegion) - } - + /// Fetch a TeamInfo func fetch(_ db: Database) throws -> TeamInfo? { guard let team = try teamRequest.fetchOne(db) else { return nil @@ -6401,53 +6192,146 @@ struct TeamInfoRequest: DatabaseRegionConvertible { } } +/// Make TeamInfoRequest observable +extension TeamInfoRequest: DatabaseRegionConvertible { + func databaseRegion(_ db: Database) throws -> DatabaseRegion { + // Returns the union of the team region and the players region + let teamRegion = try teamRequest.databaseRegion(db) + let playersRegion = try playersRequest.databaseRegion(db) + return teamRegion.union(playersRegion) + } +} + let request = TeamInfoRequest(teamId: 1) + +// Simple fetch +let teamInfo: TeamInfo? = try dbQueue.read(request.fetch) + +// Observation let observer = ValueObservation .tracking(request, fetch: request.fetch) .start(in: dbQueue) { teamInfo: TeamInfo? in - print("Team and players have hanged.") + print("Team and its players have hanged.") } ``` -See [DatabaseRegion](#databaseregion) for more information. + +### ValueObservation Transformations + +- [ValueObservation.map](#valueobservationmap) +- [ValueObservation.compactMap](#valueobservationcompactmap) +- [ValueObservation.distinctUntilChanged](#valueobservationdistinctuntilchanged) +- [ValueObservation.combine(...)](#valueobservationcombine) -### ValueObservation.tracking(_:reducer:) +#### ValueObservation.map -The most general way to define a ValueObservation is to create one from an observed database region (see above), and a **reducer** that adopts the **ValueReducer** protocol ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)): +The `map` method lets you transform the values notified by a ValueObservation. + +For example: ```swift -protocol ValueReducer { - associatedtype Fetched - associatedtype Value - - /// Fetches a database value - func fetch(_ db: Database) throws -> Fetched - - /// Returns a notified value - mutating func value(_ fetched: Fetched) -> Value? +// Observe a player's profile image +let observation = ValueObservation + .trackingOne(Player.filter(key: 42)) + .map { player in player?.loadBigProfileImage() } + +let observer = observation.start(in: dbQueue) { image: UIImage? in + print("Player picture has changed") } ``` -The `fetch` method is called upon changes in the observed [database region](#databaseregion). It runs inside a dispatch queue which can access the database. +The transformation closure does not run on the main queue, and is suitable for heavy computations. -The `value` method transforms a fetched value into a notified value. It returns nil if the observer should not be notified. This method runs inside a private dispatch queue. -The sample code below counts the number of times the player table is modified: +#### ValueObservation.compactMap + +The `compactMap` method lets you transform and filter the values notified by a ValueObservation. Only non-nil transformed values are notified. + +For example: ```swift -var count = 0 -let reducer = AnyValueReducer( - fetch: { _ in }, - value: { _ -> Int? in - count += 1 - return count - }) -let observer = ValueObservation - .tracking(Player.all(), reducer: reducer) - .start(in: dbQueue) { count: Int in - print("Players have been modified \(count) times.") +// Observe a player +let observation = ValueObservation + .trackingOne(Player.filter(key: 42)) + .compactMap { $0 } + +let observer = observation.start(in: dbQueue) { player: Player in + print("Player name: \(player.name)") +} +``` + +The transformation closure does not run on the main queue, and is suitable for heavy computations. + + +#### ValueObservation.distinctUntilChanged + +The `distinctUntilChanged` method filters out the consecutive equal values notified by a ValueObservation. The observed values must adopt the standard Equatable protocol. + +For example: + +```swift +let observation = ValueObservation + .trackingOne(Player.filter(key: 42)) + .map { player in player != nil } // existence test + .distinctUntilChanged() + +let observer = observation.start(in: dbQueue) { exists: Bool in + if exists { + print("Player 42 exists.") + } else { + print("Player 42 does not exist.") } +} +``` + +> :point_up: **Note**: the observations returned by the [ValueObservation.trackingCount, trackingOne, and trackingAll](#valueobservationtrackingcount-trackingone-trackingall) methods already perform a similar filtering, based on raw database values. + + +#### ValueObservation.combine(...) + +Sometimes you need to observe several requests at the same time. For example, you need to observe changes in both a team and its players. + +When this happens, **combine** several observations together with the `ValueObservation.combine(...)` method: + +```swift +// The two observed requests (the team and its players) +let teamRequest = Team.filter(key: 1) +let playersRequest = Player.filter(Column("teamId") == 1) + +// Two observations +let teamObservation = ValueObservation.trackingOne(teamRequest) +let playersObservation = ValueObservation.trackingAll(playersRequest) + +// The combined observation +let observation = ValueObservation.combine(teamObservation, playersObservation) + +// Start tracking players and teams +let observer = observation.start(in: dbQueue) { team: Team?, players: [Player] in + print("Team or players have changed.") +} +``` + +Combining observations provides the guarantee that notified values are [**consistent**](https://en.wikipedia.org/wiki/Consistency_(database_systems)). + +> :point_up: **Note**: you can combine up to five observations together. Please submit a pull request if you need more. +> +> :point_up: **Note**: readers who are familiar with Reactive Programming will recognize the [CombineLatest](http://reactivex.io/documentation/operators/combinelatest.html) operator in the `ValueObservation.combine` method. The reactive operator does not care about data consistency, though: if you use a Reactive layer such as [RxGRDB], compose observations with `ValueObservation.combine`, not with the CombineLatest operator. + + +### ValueObservation Error Handling + +When you start an observation, you can provide an `onError` callback. This callback is called whenever an error happens when a fresh value is fetched after a database change. It is scheduled just like values (see [ValueObservation.scheduling](#valueobservationscheduling)): + +```swift +let observer = try observation.start( + in: dbQueue, + onError: { error in + print("fresh value could not be fetched") + }, + onChange: { value in + print("fresh value: \(value)") + }) ``` @@ -6458,8 +6342,6 @@ Some behaviors of value observations can be configured: - [ValueObservation.extent](#valueobservationextent): Precise control of the observation duration. - [ValueObservation.scheduling](#valueobservationscheduling): Control the dispatching of notified values. - [ValueObservation.requiresWriteAccess](#valueobservationrequireswriteaccess): Allow observations to write in the database. -- [ValueObservation.map](#valueobservationmap): Transform notified values. -- [ValueObservation Error Handling](#valueobservation-error-handling) #### ValueObservation.extent @@ -6573,35 +6455,135 @@ observation.requiresWriteAccess = true When you use a [database pool](#database-pools), don't use this flag unless you really need it. Observations with write access are less efficient because they block all writes for the whole duration of a fetch. -#### ValueObservation.map +### Advanced: ValueObservation.tracking(_:reducer:) -The `map` method lets you transform the values notified by a ValueObservation. - -The transformation runs in a dispatch queue which does not block the main queue or the database, and is suitable for heavy computations: +The most low-level way to define a ValueObservation is to create one from an observed database region (see above), and a **reducer** that adopts the **ValueReducer** protocol ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)): ```swift -let observation = ValueObservation - .trackingOne(Player.filter(key: 42)) - .map { player in player?.loadBigProfileImage() } - .start(in: dbQueue) { image: UIImage? in - print("Player picture has changed") - } +protocol ValueReducer { + associatedtype Fetched + associatedtype Value + + /// Fetches a database value + func fetch(_ db: Database) throws -> Fetched + + /// Returns a notified value + mutating func value(_ fetched: Fetched) -> Value? +} +``` + +The `fetch` method is called upon changes in the observed [database region](#databaseregion). It runs inside a protected dispatch queue and is guaranteed an immutable view of the last committed state of the database. + +The `value` method transforms a fetched value into a notified value. It returns nil if the observer should not be notified. It runs inside a dispatch queue called the "reduce queue", which is not the main queue, and not a database queue. + +The sample code below counts the number of times the player table is modified: + +```swift +var count = 0 +let reducer = AnyValueReducer( + fetch: { _ in /* don't fetch anything */ }, + value: { _ -> Int? in + defer { count += 1 } + return count }) +let observation = ValueObservation.tracking(Player.all(), reducer: { _ in reducer }) +let observer = observation.start(in: dbQueue) { count: Int in + print("Number of transactions that have modified players: \(count)") +} +// Prints "Number of transactions that have modified players: 0" + +try dbQueue.write { db in + try Player(...).insert(db) +} +// Prints "Number of transactions that have modified players: 1" ``` -#### ValueObservation Error Handling +## DatabaseRegionObservation -When you start an observation, you can provide an `onError` callback. This callback is called whenever an error happens when a fresh value is fetched after a database change. It is scheduled just like values (see [ValueObservation.scheduling](#valueobservationscheduling)): +**DatabaseRegionObservation tracks changes in database [requests](#requests), and notifies each impactful [transaction](#transactions-and-savepoints).** + +No insertion, update, or deletion in the tracked tables is missed. This includes indirect changes triggered by [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). + +DatabaseRegionObservation calls your application right after changes have been committed in the database, and before any other thread had any opportunity to perform further changes. *This is a pretty strong guarantee, that most applications do not really need.* Instead, most applications prefer to be notified with fresh values: make sure you check [ValueObservation] before using DatabaseRegionObservation. + + +### DatabaseRegionObservation Usage + +Define an observation by providing one or several requests to track: ```swift -let observer = try observation.start( - in: dbQueue, - onError: { error in - print("fresh value could not be fetched") - }, - onChange: { value in - print("fresh value: \(value)") - }) +// Track all players +let observation = DatabaseRegionObservation(tracking: Player.all()) +``` + +Then start the observation from a [database queue](#database-queues) or [pool](#database-pools): + +```swift +let observer = observation.start(in: dbQueue) { db: Database in + print("Players were changed") +} +``` + +And enjoy the changes notifications: + +```swift +try dbQueue.write { db in + try Player(name: "Arthur").insert(db) +} +// Prints "Players were changed" +``` + +By default, the observation lasts until the observer returned by the `start` method is deallocated. See [DatabaseRegionObservation.extent](#databaseregionobservationextent) for more details. + +You can also feed DatabaseRegionObservation with [DatabaseRegion], or any type which conforms to the [DatabaseRegionConvertible] protocol. For example: + +```swift +// Observe the full database +let observation = DatabaseRegionObservation(tracking: DatabaseRegion.fullDatabase) +let observer = observation.start(in: dbQueue) { db: Database in + print("Database was changed") +} +``` + + +### DatabaseRegionObservation Use Cases + +**There are very few use cases for DatabaseRegionObservation**. + +For example: + +- One needs to write in the database after an impactful transaction. + +- One needs to synchronize the content of the database file with some external resources, like other files, or system sensors like CLRegion monitoring. + +- On iOS, one needs to process a database transaction before the operating system had any opportunity to put the application in the suspended state. + +- One want to build a [database snapshot](#database-snapshots) with a guaranteed snapshot content. + +Outside of those use cases, it is much likely *wrong* to use a DatabaseRegionObservation. Please check other [Database Observation](#database-changes-observation) options. + + +### DatabaseRegionObservation.extent + +The `extent` property lets you specify the duration of the observation. See [Observation Extent](#observation-extent) for more details: + +```swift +// This observation lasts until the database connection is closed +var observation = DatabaseRegionObservation... +observation.extent = .databaseLifetime +_ = observation.start(in: dbQueue) { db in ... } +``` + +The default extent is `.observerLifetime`: the observation stops when the observer returned by `start` is deallocated. + +Regardless of the extent of an observation, you can always stop observation with the `remove(transactionObserver:)` method: + +```swift +// Start +let observer = observation.start(in: dbQueue) { db in ... } + +// Stop +dbQueue.remove(transactionObserver: observer) ``` @@ -6945,6 +6927,304 @@ try controller.performFetch() > ``` +## TransactionObserver Protocol + +The `TransactionObserver` protocol lets you **observe individual database changes and transactions**: + +```swift +protocol TransactionObserver : class { + /// Notifies a database change: + /// - event.kind (insert, update, or delete) + /// - event.tableName + /// - event.rowID + /// + /// For performance reasons, the event is only valid for the duration of + /// this method call. If you need to keep it longer, store a copy: + /// event.copy(). + func databaseDidChange(with event: DatabaseEvent) + + /// Filters the database changes that should be notified to the + /// `databaseDidChange(with:)` method. + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool + + /// An opportunity to rollback pending changes by throwing an error. + func databaseWillCommit() throws + + /// Database changes have been committed. + func databaseDidCommit(_ db: Database) + + /// Database changes have been rollbacked. + func databaseDidRollback(_ db: Database) +} +``` + +- [Activate a Transaction Observer](#activate-a-transaction-observer) +- [Database Changes And Transactions](#database-changes-and-transactions) +- [Filtering Database Events](#filtering-database-events) +- [Observation Extent](#observation-extent) +- [DatabaseRegion] +- [Support for SQLite Pre-Update Hooks](#support-for-sqlite-pre-update-hooks) + + +### Activate a Transaction Observer + +**To activate a transaction observer, add it to the database queue or pool:** + +```swift +let observer = MyObserver() +dbQueue.add(transactionObserver: observer) +``` + +By default, database holds weak references to its transaction observers: they are not retained, and stop getting notifications after they are deallocated. See [Observation Extent](#observation-extent) for more options. + + +### Database Changes And Transactions + +**A transaction observer is notified of all database changes**: inserts, updates and deletes. This includes indirect changes triggered by ON DELETE and ON UPDATE actions associated to [foreign keys](https://www.sqlite.org/foreignkeys.html#fk_actions), and [SQL triggers](https://www.sqlite.org/lang_createtrigger.html). + +> :point_up: **Note**: the changes that are not notified are changes to internal system tables (such as `sqlite_master`), changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables, and the deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite). + +Notified changes are not actually written to disk until the [transaction](#transactions-and-savepoints) commits, and the `databaseDidCommit` callback is called. On the other side, `databaseDidRollback` confirms their invalidation: + +```swift +try dbQueue.write { db in + try db.execute("INSERT ...") // 1. didChange + try db.execute("UPDATE ...") // 2. didChange +} // 3. willCommit, 4. didCommit + +try dbQueue.inTransaction { db in + try db.execute("INSERT ...") // 1. didChange + try db.execute("UPDATE ...") // 2. didChange + return .rollback // 3. didRollback +} + +try dbQueue.write { db in + try db.execute("INSERT ...") // 1. didChange + throw SomeError() +} // 2. didRollback +``` + +Database statements that are executed outside of any transaction do not drop off the radar: + +```swift +try dbQueue.inDatabase { db in + try db.execute("INSERT ...") // 1. didChange, 2. willCommit, 3. didCommit + try db.execute("UPDATE ...") // 4. didChange, 5. willCommit, 6. didCommit +} +``` + +Changes that are on hold because of a [savepoint](https://www.sqlite.org/lang_savepoint.html) are only notified after the savepoint has been released. This makes sure that notified events are only events that have an opportunity to be committed: + +```swift +try dbQueue.inTransaction { db in + try db.execute("INSERT ...") // 1. didChange + + try db.execute("SAVEPOINT foo") + try db.execute("UPDATE ...") // delayed + try db.execute("UPDATE ...") // delayed + try db.execute("RELEASE SAVEPOINT foo") // 2. didChange, 3. didChange + + try db.execute("SAVEPOINT foo") + try db.execute("UPDATE ...") // not notified + try db.execute("ROLLBACK TO SAVEPOINT foo") + + return .commit // 4. willCommit, 5. didCommit +} +``` + + +**Eventual errors** thrown from `databaseWillCommit` are exposed to the application code: + +```swift +do { + try dbQueue.inTransaction { db in + ... + return .commit // 1. willCommit (throws), 2. didRollback + } +} catch { + // 3. The error thrown by the transaction observer. +} +``` + +> :point_up: **Note**: all callbacks are called in a protected dispatch queue, and serialized with all database updates. +> +> :point_up: **Note**: the databaseDidChange(with:) and databaseWillCommit() callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument. + + +[DatabaseRegionObservation], [ValueObservation], [FetchedRecordsController], and [RxGRDB] are based on the TransactionObserver protocol. + +See also [TableChangeObserver.swift](https://gist.github.com/groue/2e21172719e634657dfd), which shows a transaction observer that notifies of modified database tables with NSNotificationCenter. + + +### Filtering Database Events + +**Transaction observers can avoid being notified of database changes they are not interested in.** + +The filtering happens in the `observes(eventsOfKind:)` method, which tells whether the observer wants notification of specific kinds of changes, or not. For example, here is how an observer can focus on the changes that happen on the "player" database table: + +```swift +class PlayerObserver: TransactionObserver { + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { + // Only observe changes to the "player" table. + return eventKind.tableName == "player" + } + + func databaseDidChange(with event: DatabaseEvent) { + // This method is only called for changes that happen to + // the "player" table. + } +} +``` + +Generally speaking, the `observes(eventsOfKind:)` method can distinguish insertions from deletions and updates, and is also able to inspect the columns that are about to be changed: + +```swift +class PlayerScoreObserver: TransactionObserver { + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { + // Only observe changes to the "score" column of the "player" table. + switch eventKind { + case .insert(let tableName): + return tableName == "player" + case .delete(let tableName): + return tableName == "player" + case .update(let tableName, let columnNames): + return tableName == "player" && columnNames.contains("score") + } + } +} +``` + +When the `observes(eventsOfKind:)` method returns false for all event kinds, the observer is still notified of commits and rollbacks: + +```swift +class PureTransactionObserver: TransactionObserver { + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { + // Ignore all individual changes + return false + } + + func databaseDidChange(with event: DatabaseEvent) { /* Never called */ } + func databaseWillCommit() throws { /* Called before commit */ } + func databaseDidRollback(_ db: Database) { /* Called on rollback */ } + func databaseDidCommit(_ db: Database) { /* Called on commit */ } +} +``` + +For more information about event filtering, see [DatabaseRegion]. + + +### Observation Extent + +**You can specify how long an observer is notified of database changes and transactions.** + +The `remove(transactionObserver:)` method explicitly stops notifications, at any time: + +```swift +// From a database queue or pool: +dbQueue.remove(transactionObserver: observer) + +// From a database connection: +dbQueue.inDatabase { db in + db.remove(transactionObserver: observer) +} +``` + +Alternatively, use the `extent` parameter of the `add(transactionObserver:extent:)` method: + +```swift +let observer = MyObserver() + +// On a database queue or pool: +dbQueue.add(transactionObserver: observer) // default extent +dbQueue.add(transactionObserver: observer, extent: .observerLifetime) +dbQueue.add(transactionObserver: observer, extent: .nextTransaction) +dbQueue.add(transactionObserver: observer, extent: .databaseLifetime) + +// On a database connection: +dbQueue.inDatabase { db in + db.add(transactionObserver: ...) +} +``` + +- The default extent is `.observerLifetime`: the database holds a weak reference to the observer, and the observation automatically ends when the observer is deallocated. Meanwhile, observer is notified of all changes and transactions. + +- `.nextTransaction` activates the observer until the current or next transaction completes. The database keeps a strong reference to the observer until its `databaseDidCommit` or `databaseDidRollback` method is eventually called. Hereafter the observer won't get any further notification. + +- `.databaseLifetime` has the database retain and notify the observer until the database connection is closed. + +Finally, an observer may ignore all database changes until the end of the current transaction: + +```swift +class PlayerObserver: TransactionObserver { + var playerTableWasModified = false + + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { + return eventKind.tableName == "player" + } + + func databaseDidChange(with event: DatabaseEvent) { + playerTableWasModified = true + + // It is pointless to keep on tracking further changes: + stopObservingDatabaseChangesUntilNextTransaction() + } +} +``` + +After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChange(with:)` method will not be notified of any change for the remaining duration of the current transaction. This helps GRDB optimize database observation. + + +### DatabaseRegion + +**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/3.5/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**. + +A request knows which database modifications can impact its results. It can communicate this information to [transaction observers](#transactionobserver-protocol) by the way of a DatabaseRegion. + +DatabaseRegion fuels, for example, [ValueObservation and DatabaseRegionObservation]. + +**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. + +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. + +Similarly, observing the region of `Country.filter(key: "FR")` will notify all changes that happen to the whole `country` table. That is because SQLite only notifies the numerical [rowid](https://www.sqlite.org/rowidtable.html) of changed rows, and we can't check if it is the row "FR" that has been changed, or another. This limitation does not apply to tables whose primary key is the rowid: `Player.filter(key: 42)` will only notify of changes performed on the row with id 42. + +For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/3.5/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). + + +#### The DatabaseRegionConvertible Protocol + +**DatabaseRegionConvertible** is a protocol for all types that can turn into a [DatabaseRegion]: + +```swift +protocol DatabaseRegionConvertible { + func databaseRegion(_ db: Database) throws -> DatabaseRegion +} +``` + +All [requests](#requests) adopt this protocol, and this allows them to be observed with [DatabaseRegionObservation] and [ValueObservation]. + +Use this protocol when you want to encapsulate your complex requests in a dedicated type, and still profit from observation APIs. See [DatabaseRegionConvertible Observation](#databaseregionconvertible-observation) for more information. + + +### Support for SQLite Pre-Update Hooks + +A [custom SQLite build](Documentation/CustomSQLiteBuilds.md) can activate [SQLite "preupdate hooks"](https://sqlite.org/c3ref/preupdate_count.html). In this case, TransactionObserverType gets an extra callback which lets you observe individual column values in the rows modified by a transaction: + +```swift +protocol TransactionObserverType : class { + #if SQLITE_ENABLE_PREUPDATE_HOOK + /// Notifies before a database change (insert, update, or delete) + /// with change information (initial / final values for the row's + /// columns). + /// + /// The event is only valid for the duration of this method call. If you + /// need to keep it longer, store a copy: event.copy(). + func databaseWillChange(with event: DatabasePreUpdateEvent) + #endif +} +``` + + Encryption ========== @@ -7759,6 +8039,7 @@ Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.gith These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example: - [Migrations](#migrations) +- [DatabaseRegionObservation] - [ValueObservation] - [FetchedRecordsController] - [RxGRDB] @@ -8321,5 +8602,9 @@ This chapter has been renamed [Beyond FetchableRecord]. [Record Customization Options]: #record-customization-options [TableRecord]: #tablerecord-protocol [ValueObservation]: #valueobservation +[DatabaseRegionObservation]: #databaseregionobservation [FetchedRecordsController]: #fetchedrecordscontroller -[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB \ No newline at end of file +[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB +[DatabaseRegionConvertible]: #the-databaseregionconvertible-protocol +[ValueObservation and DatabaseRegionObservation]: #valueobservation-and-databaseregionobservation +[DatabaseRegion]: #databaseregion \ No newline at end of file diff --git a/Tests/GRDBTests/DatabaseErrorTests.swift b/Tests/GRDBTests/DatabaseErrorTests.swift index 986cfa109..82d4139bf 100644 --- a/Tests/GRDBTests/DatabaseErrorTests.swift +++ b/Tests/GRDBTests/DatabaseErrorTests.swift @@ -9,6 +9,17 @@ import XCTest class DatabaseErrorTests: GRDBTestCase { + func testDatabaseErrorMessage() { + // Error messages are not always available + if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) { + // We don't test for actual messages, since they may depend on SQLite version + XCTAssertEqual(DatabaseError().resultCode, .SQLITE_ERROR) + XCTAssertNotNil(DatabaseError().message) + XCTAssertNotNil(DatabaseError(resultCode: .SQLITE_BUSY).message) + XCTAssertNotEqual(DatabaseError().message, DatabaseError(resultCode: .SQLITE_BUSY).message) + } + } + func testDatabaseErrorInTransaction() throws { let dbQueue = try makeDatabaseQueue() do { diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index a28376b07..44ef15faa 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -1,4 +1,5 @@ import XCTest +import Dispatch #if GRDBCIPHER import GRDBCipher #elseif GRDBCUSTOMSQLITE @@ -1097,4 +1098,72 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { blocks[index]() } } + + func testTargetQueue() throws { + // dispatchPrecondition(condition:) availability + if #available(OSX 10.12, iOS 10.0, *) { + func test(targetQueue: DispatchQueue) throws { + dbConfiguration.targetQueue = targetQueue + let dbPool = try makeDatabasePool() + try dbPool.write { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + try dbPool.read { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + } + + // background queue + try test(targetQueue: .global(qos: .background)) + + // main queue + let expectation = self.expectation(description: "main") + DispatchQueue.global(qos: .default).async { + try! test(targetQueue: .main) + expectation.fulfill() + } + waitForExpectations(timeout: 1, handler: nil) + } + } + + func testQoS() throws { + // dispatchPrecondition(condition:) availability + if #available(OSX 10.12, iOS 10.0, *) { + func test(qos: DispatchQoS) throws { + // https://forums.swift.org/t/what-is-the-default-target-queue-for-a-serial-queue/18094/5 + // + // > [...] the default target queue [for a serial queue] is the + // > [default] overcommit [global concurrent] queue. + // + // We want this default target queue in order to test database QoS + // with dispatchPrecondition(condition:). + // + // > [...] You can get a reference to the overcommit queue by + // > dropping down to the C function dispatch_get_global_queue + // > (available in Swift with a __ prefix) and passing the private + // > value of DISPATCH_QUEUE_OVERCOMMIT. + // > + // > [...] Of course you should not do this in production code, + // > because DISPATCH_QUEUE_OVERCOMMIT is not a public API. I don't + // > know of a way to get a reference to the overcommit queue using + // > only public APIs. + let DISPATCH_QUEUE_OVERCOMMIT: UInt = 2 + let targetQueue = __dispatch_get_global_queue( + Int(qos.qosClass.rawValue.rawValue), + DISPATCH_QUEUE_OVERCOMMIT) + + dbConfiguration.qos = qos + let dbPool = try makeDatabasePool() + try dbPool.write { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + try dbPool.read { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + } + + try test(qos: .background) + try test(qos: .userInitiated) + } + } } diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index 2c3b84dbf..e2014d9dd 100644 --- a/Tests/GRDBTests/DatabaseQueueTests.swift +++ b/Tests/GRDBTests/DatabaseQueueTests.swift @@ -131,4 +131,72 @@ class DatabaseQueueTests: GRDBTestCase { XCTAssertEqual(label, "Toreador") } } + + func testTargetQueue() throws { + // dispatchPrecondition(condition:) availability + if #available(OSX 10.12, iOS 10.0, *) { + func test(targetQueue: DispatchQueue) throws { + dbConfiguration.targetQueue = targetQueue + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + dbQueue.read { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + } + + // background queue + try test(targetQueue: .global(qos: .background)) + + // main queue + let expectation = self.expectation(description: "main") + DispatchQueue.global(qos: .default).async { + try! test(targetQueue: .main) + expectation.fulfill() + } + waitForExpectations(timeout: 1, handler: nil) + } + } + + func testQoS() throws { + // dispatchPrecondition(condition:) availability + if #available(OSX 10.12, iOS 10.0, *) { + func test(qos: DispatchQoS) throws { + // https://forums.swift.org/t/what-is-the-default-target-queue-for-a-serial-queue/18094/5 + // + // > [...] the default target queue [for a serial queue] is the + // > [default] overcommit [global concurrent] queue. + // + // We want this default target queue in order to test database QoS + // with dispatchPrecondition(condition:). + // + // > [...] You can get a reference to the overcommit queue by + // > dropping down to the C function dispatch_get_global_queue + // > (available in Swift with a __ prefix) and passing the private + // > value of DISPATCH_QUEUE_OVERCOMMIT. + // > + // > [...] Of course you should not do this in production code, + // > because DISPATCH_QUEUE_OVERCOMMIT is not a public API. I don't + // > know of a way to get a reference to the overcommit queue using + // > only public APIs. + let DISPATCH_QUEUE_OVERCOMMIT: UInt = 2 + let targetQueue = __dispatch_get_global_queue( + Int(qos.qosClass.rawValue.rawValue), + DISPATCH_QUEUE_OVERCOMMIT) + + dbConfiguration.qos = qos + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + dbQueue.read { _ in + dispatchPrecondition(condition: .onQueue(targetQueue)) + } + } + + try test(qos: .background) + try test(qos: .userInitiated) + } + } } diff --git a/Tests/GRDBTests/DatabaseRegionObservationTests.swift b/Tests/GRDBTests/DatabaseRegionObservationTests.swift new file mode 100644 index 000000000..dff415cc5 --- /dev/null +++ b/Tests/GRDBTests/DatabaseRegionObservationTests.swift @@ -0,0 +1,155 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + #if SWIFT_PACKAGE + import CSQLite + #else + import SQLite3 + #endif + import GRDB +#endif + +class DatabaseRegionObservationTests: GRDBTestCase { + func testDatabaseRegionObservationVariadic() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute("CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + try $0.execute("CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + } + + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + let request1 = SQLRequest("SELECT * FROM t1 ORDER BY id") + let request2 = SQLRequest("SELECT * FROM t2 ORDER BY id") + + var observation = DatabaseRegionObservation(tracking: request1, request2) + observation.extent = .databaseLifetime + + var count = 0 + _ = try observation.start(in: dbQueue) { db in + count += 1 + notificationExpectation.fulfill() + } + + try dbQueue.write { db in + try db.execute("INSERT INTO t1 (id, name) VALUES (1, 'foo')") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t2 (id, name) VALUES (1, 'foo')") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t1 (id, name) VALUES (2, 'foo')") + try db.execute("INSERT INTO t2 (id, name) VALUES (2, 'foo')") + } + waitForExpectations(timeout: 1, handler: nil) + + XCTAssertEqual(count, 3) + } + + func testDatabaseRegionObservationArray() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute("CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + try $0.execute("CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") + } + + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + let request1 = SQLRequest("SELECT * FROM t1 ORDER BY id") + let request2 = SQLRequest("SELECT * FROM t2 ORDER BY id") + + var observation = DatabaseRegionObservation(tracking: [request1, request2]) + observation.extent = .databaseLifetime + + var count = 0 + _ = try observation.start(in: dbQueue) { db in + count += 1 + notificationExpectation.fulfill() + } + + try dbQueue.write { db in + try db.execute("INSERT INTO t1 (id, name) VALUES (1, 'foo')") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t2 (id, name) VALUES (1, 'foo')") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t1 (id, name) VALUES (2, 'foo')") + try db.execute("INSERT INTO t2 (id, name) VALUES (2, 'foo')") + } + waitForExpectations(timeout: 1, handler: nil) + + XCTAssertEqual(count, 3) + } + + func testDatabaseRegionDefaultExtent() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + let observation = DatabaseRegionObservation(tracking: SQLRequest("SELECT * FROM t ORDER BY id")) + + var count = 0 + do { + let observer = try observation.start(in: dbQueue) { db in + count += 1 + notificationExpectation.fulfill() + } + + try withExtendedLifetime(observer) { + try dbQueue.write { db in + try db.execute("INSERT INTO t (id, name) VALUES (1, 'foo')") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t (id, name) VALUES (2, 'bar')") + } + } + } + // not notified + try dbQueue.write { db in + try db.execute("INSERT INTO t (id, name) VALUES (3, 'baz')") + } + waitForExpectations(timeout: 1, handler: nil) + + XCTAssertEqual(count, 2) + } + + func testDatabaseRegionExtentNextTransaction() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 1 + + var observation = DatabaseRegionObservation(tracking: SQLRequest("SELECT * FROM t ORDER BY id")) + observation.extent = .nextTransaction + + var count = 0 + _ = try observation.start(in: dbQueue) { db in + count += 1 + notificationExpectation.fulfill() + } + + try dbQueue.write { db in + try db.execute("INSERT INTO t (id, name) VALUES (1, 'foo')") + } + // not notified + try dbQueue.write { db in + try db.execute("INSERT INTO t (id, name) VALUES (2, 'bar')") + } + waitForExpectations(timeout: 1, handler: nil) + + XCTAssertEqual(count, 1) + } +} diff --git a/Tests/GRDBTests/DatabaseRegionTests.swift b/Tests/GRDBTests/DatabaseRegionTests.swift index 47744ced9..80bd6630e 100644 --- a/Tests/GRDBTests/DatabaseRegionTests.swift +++ b/Tests/GRDBTests/DatabaseRegionTests.swift @@ -606,7 +606,7 @@ class DatabaseRegionTests : GRDBTestCase { try dbQueue.inDatabase { db in do { let statement = try db.makeUpdateStatement("CREATE TABLE foo (id INTEGER)") - XCTAssertFalse(statement.invalidatesDatabaseSchemaCache) + XCTAssertTrue(statement.invalidatesDatabaseSchemaCache) try statement.execute() } do { diff --git a/Tests/GRDBTests/FetchableRecordDecodableTests.swift b/Tests/GRDBTests/FetchableRecordDecodableTests.swift index fcfdc109f..1722d5eb4 100644 --- a/Tests/GRDBTests/FetchableRecordDecodableTests.swift +++ b/Tests/GRDBTests/FetchableRecordDecodableTests.swift @@ -477,24 +477,44 @@ extension FetchableRecordDecodableTests { try db.create(table: "t1") { t in t.column("nested", .text) } - - let nested = NestedStruct(firstName: "Bob", lastName: "Dylan") - let value = StructWithNestedType(nested: [nested, nested]) + } + + try dbQueue.inTransaction { db in + let value = StructWithNestedType(nested: [ + NestedStruct(firstName: "Bob", lastName: "Dylan"), + NestedStruct(firstName: "Bob", lastName: "Dylan")]) try value.insert(db) - let parentModel = try StructWithNestedType.fetchAll(db) + let parentModel = try StructWithNestedType.fetchOne(db) - guard let arrayOfNestedModel = parentModel.first?.nested, let firstNestedModelInArray = arrayOfNestedModel.first else { + guard let nested = parentModel?.nested else { XCTFail() - return + return .rollback } // Check there are two models in array - XCTAssertTrue(arrayOfNestedModel.count == 2) + XCTAssertEqual(nested.count, 2) // Check the nested model contains the expected values of first and last name - XCTAssertEqual(firstNestedModelInArray.firstName, "Bob") - XCTAssertEqual(firstNestedModelInArray.lastName, "Dylan") + XCTAssertEqual(nested[0].firstName, "Bob") + XCTAssertEqual(nested[0].lastName, "Dylan") + + return .rollback + } + + try dbQueue.inTransaction { db in + let value = StructWithNestedType(nested: []) + try value.insert(db) + + let parentModel = try StructWithNestedType.fetchOne(db) + + guard let nested = parentModel?.nested else { + XCTFail() + return .rollback + } + + XCTAssertTrue(nested.isEmpty) + return .rollback } } diff --git a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift index f8b01ebce..a3f7db736 100644 --- a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift @@ -269,4 +269,238 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { } } } + + func testUpdateChangesWithRecord() throws { + class MyRecord: Record { + var id: Int64? + var firstName: String? + var lastName: String? + + init(id: Int64?, firstName: String?, lastName: String?) { + self.id = id + self.firstName = firstName + self.lastName = lastName + super.init() + } + + override class var databaseTableName: String { + return "myRecord" + } + + enum Columns: String, ColumnExpression { + case id, firstName, lastName + } + + required init(row: Row) { + id = row[Columns.id] + firstName = row[Columns.firstName] + lastName = row[Columns.lastName] + super.init(row: row) + } + + override func encode(to container: inout PersistenceContainer) { + container[Columns.id] = id + container[Columns.firstName] = firstName + container[Columns.lastName] = lastName + } + + override func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "myRecord") { t in + t.autoIncrementedPrimaryKey("id") + t.column("firstName", .text) + t.column("lastName", .text) + } + + // This `let` is part of the test + let record = MyRecord(id: nil, firstName: "Arthur", lastName: "Smith") + try record.insert(db) + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { _ in } + XCTAssertFalse(modified) + XCTAssert(sqlQueries.isEmpty) + } + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { + $0.firstName = "Arthur" + } + XCTAssertFalse(modified) + XCTAssert(sqlQueries.isEmpty) + } + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { + $0.firstName = nil + } + XCTAssertEqual(record.firstName, nil) + XCTAssertEqual(record.lastName, "Smith") + XCTAssertTrue(modified) + XCTAssertEqual(lastSQLQuery, "UPDATE \"myRecord\" SET \"firstName\"=NULL WHERE \"id\"=1") + } + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { + $0.firstName = "Bob" + $0.lastName = "Johnson" + } + XCTAssertEqual(record.firstName, "Bob") + XCTAssertEqual(record.lastName, "Johnson") + XCTAssertTrue(modified) + XCTAssertTrue([ + "UPDATE \"myRecord\" SET \"firstName\"=\'Bob\', \"lastName\"=\'Johnson\' WHERE \"id\"=1", + "UPDATE \"myRecord\" SET \"lastName\"=\'Johnson\', \"firstName\"=\'Bob\' WHERE \"id\"=1"] + .contains(lastSQLQuery)) + } + } + } + + func testUpdateChangesWithNonRecordClass() throws { + class MyRecord: Codable, PersistableRecord { + var id: Int64? + var firstName: String? + var lastName: String? + + init(id: Int64?, firstName: String?, lastName: String?) { + self.id = id + self.firstName = firstName + self.lastName = lastName + } + + func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "myRecord") { t in + t.autoIncrementedPrimaryKey("id") + t.column("firstName", .text) + t.column("lastName", .text) + } + + // This `let` is part of the test + let record = MyRecord(id: nil, firstName: "Arthur", lastName: "Smith") + try record.insert(db) + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { _ in } + XCTAssertFalse(modified) + XCTAssert(sqlQueries.isEmpty) + } + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { + $0.firstName = "Arthur" + } + XCTAssertFalse(modified) + XCTAssert(sqlQueries.isEmpty) + } + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { + $0.firstName = nil + } + XCTAssertEqual(record.firstName, nil) + XCTAssertEqual(record.lastName, "Smith") + XCTAssertTrue(modified) + XCTAssertEqual(lastSQLQuery, "UPDATE \"myRecord\" SET \"firstName\"=NULL WHERE \"id\"=1") + } + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { + $0.firstName = "Bob" + $0.lastName = "Johnson" + } + XCTAssertEqual(record.firstName, "Bob") + XCTAssertEqual(record.lastName, "Johnson") + XCTAssertTrue(modified) + XCTAssertTrue([ + "UPDATE \"myRecord\" SET \"firstName\"=\'Bob\', \"lastName\"=\'Johnson\' WHERE \"id\"=1", + "UPDATE \"myRecord\" SET \"lastName\"=\'Johnson\', \"firstName\"=\'Bob\' WHERE \"id\"=1"] + .contains(lastSQLQuery)) + } + } + } + + func testUpdateChangesWithStruct() throws { + struct MyRecord: Codable, MutablePersistableRecord { + var id: Int64? + var firstName: String? + var lastName: String? + + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "myRecord") { t in + t.autoIncrementedPrimaryKey("id") + t.column("firstName", .text) + t.column("lastName", .text) + } + + var record = MyRecord(id: nil, firstName: "Arthur", lastName: "Smith") + try record.insert(db) + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { _ in } + XCTAssertFalse(modified) + XCTAssert(sqlQueries.isEmpty) + } + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { + $0.firstName = "Arthur" + } + XCTAssertFalse(modified) + XCTAssert(sqlQueries.isEmpty) + } + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { + $0.firstName = nil + } + XCTAssertEqual(record.firstName, nil) + XCTAssertEqual(record.lastName, "Smith") + XCTAssertTrue(modified) + XCTAssertEqual(lastSQLQuery, "UPDATE \"myRecord\" SET \"firstName\"=NULL WHERE \"id\"=1") + } + + do { + sqlQueries = [] + let modified = try record.updateChanges(db) { + $0.firstName = "Bob" + $0.lastName = "Johnson" + } + XCTAssertEqual(record.firstName, "Bob") + XCTAssertEqual(record.lastName, "Johnson") + XCTAssertTrue(modified) + XCTAssertTrue([ + "UPDATE \"myRecord\" SET \"firstName\"=\'Bob\', \"lastName\"=\'Johnson\' WHERE \"id\"=1", + "UPDATE \"myRecord\" SET \"lastName\"=\'Johnson\', \"firstName\"=\'Bob\' WHERE \"id\"=1"] + .contains(lastSQLQuery)) + } + } + } } diff --git a/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift b/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift index 65ac337a6..6d166a88e 100644 --- a/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift @@ -416,6 +416,102 @@ extension MutablePersistableRecordEncodableTests { } } + func testArrayJSONEncoding() throws { + struct Record: PersistableRecord, Encodable { + let array: [String] + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "record") { t in + t.autoIncrementedPrimaryKey("id") + t.column("array", .text) + } + + try Record(array: []).insert(db) + try Record(array: ["foo"]).insert(db) + try Record(array: ["foo", "bar"]).insert(db) + + let rows = try Row.fetchAll(db, "SELECT * FROM record ORDER BY id") + XCTAssertEqual(rows.count, 3) + XCTAssertEqual(rows[0]["array"], "[]") + XCTAssertEqual(rows[1]["array"], "[\"foo\"]") + XCTAssertEqual(rows[2]["array"], "[\"foo\",\"bar\"]") + } + } + + func testOptionalArrayJSONEncoding() throws { + struct Record: PersistableRecord, Encodable { + let array: [String]? + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "record") { t in + t.autoIncrementedPrimaryKey("id") + t.column("array", .text) + } + + try Record(array: nil).insert(db) + try Record(array: []).insert(db) + try Record(array: ["foo"]).insert(db) + try Record(array: ["foo", "bar"]).insert(db) + + let rows = try Row.fetchAll(db, "SELECT * FROM record ORDER BY id") + XCTAssertEqual(rows.count, 4) + XCTAssertTrue(rows[0]["array"] == nil) + XCTAssertEqual(rows[1]["array"], "[]") + XCTAssertEqual(rows[2]["array"], "[\"foo\"]") + XCTAssertEqual(rows[3]["array"], "[\"foo\",\"bar\"]") + } + } + + func testDictionaryJSONEncoding() throws { + struct Record: PersistableRecord, Encodable { + let dictionary: [String: Int] + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "record") { t in + t.autoIncrementedPrimaryKey("id") + t.column("dictionary", .text) + } + + try Record(dictionary: [:]).insert(db) + try Record(dictionary: ["foo": 1]).insert(db) + + let rows = try Row.fetchAll(db, "SELECT * FROM record ORDER BY id") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0]["dictionary"], "{}") + XCTAssertEqual(rows[1]["dictionary"], "{\"foo\":1}") + } + } + + func testOptionalDictionaryJSONEncoding() throws { + struct Record: PersistableRecord, Encodable { + let dictionary: [String: Int]? + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "record") { t in + t.autoIncrementedPrimaryKey("id") + t.column("dictionary", .text) + } + + try Record(dictionary: nil).insert(db) + try Record(dictionary: [:]).insert(db) + try Record(dictionary: ["foo": 1]).insert(db) + + let rows = try Row.fetchAll(db, "SELECT * FROM record ORDER BY id") + XCTAssertEqual(rows.count, 3) + XCTAssertTrue(rows[0]["dictionary"] == nil) + XCTAssertEqual(rows[1]["dictionary"], "{}") + XCTAssertEqual(rows[2]["dictionary"], "{\"foo\":1}") + } + } + func testJSONDataEncodingStrategy() throws { struct Record: PersistableRecord, Encodable { let data: Data diff --git a/Tests/GRDBTests/TableDefinitionTests.swift b/Tests/GRDBTests/TableDefinitionTests.swift index b25ec0aa2..b85dda3f1 100644 --- a/Tests/GRDBTests/TableDefinitionTests.swift +++ b/Tests/GRDBTests/TableDefinitionTests.swift @@ -573,4 +573,15 @@ class TableDefinitionTests: GRDBTestCase { XCTAssertTrue(try db.indexes(on: "test").isEmpty) } } + + func testReindex() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.reindex(collation: .binary) + assertEqualSQL(lastSQLQuery, "REINDEX BINARY") + + try db.reindex(collation: .localizedCompare) + assertEqualSQL(lastSQLQuery, "REINDEX swiftLocalizedCompare") + } + } } diff --git a/Tests/GRDBTests/ValueObservationCombineTests.swift b/Tests/GRDBTests/ValueObservationCombineTests.swift new file mode 100644 index 000000000..32b89c860 --- /dev/null +++ b/Tests/GRDBTests/ValueObservationCombineTests.swift @@ -0,0 +1,383 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + #if SWIFT_PACKAGE + import CSQLite + #else + import SQLite3 + #endif + import GRDB +#endif + +class ValueObservationCombineTests: GRDBTestCase { + func testCombine2() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute(""" + CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT); + CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT); + """) + } + + var values: [(Int, Int)] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 4 + + struct T1: TableRecord { } + struct T2: TableRecord { } + let observation1 = ValueObservation.trackingCount(T1.all()) + let observation2 = ValueObservation.trackingCount(T2.all()) + var observation = ValueObservation.combine(observation1, observation2) + observation.extent = .databaseLifetime + _ = try observation.start(in: dbQueue) { value in + values.append(value) + notificationExpectation.fulfill() + } + + try dbQueue.write { db in + try db.execute("INSERT INTO t1 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("DELETE FROM t1") + try db.execute("INSERT INTO t1 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("DELETE FROM t2") + try db.execute("INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("DELETE FROM t1") + try db.execute("DELETE FROM t2") + try db.execute("INSERT INTO t1 DEFAULT VALUES") + try db.execute("INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t1 DEFAULT VALUES") + try db.execute("INSERT INTO t2 DEFAULT VALUES") + } + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(values.count, 4) + XCTAssert(values[0] == (0, 0)) + XCTAssert(values[1] == (1, 0)) + XCTAssert(values[2] == (1, 1)) + XCTAssert(values[3] == (2, 2)) + } + + func testCombine3() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute(""" + CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT); + CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT); + CREATE TABLE t3(id INTEGER PRIMARY KEY AUTOINCREMENT); + """) + } + + var values: [(Int, Int, Int)] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 5 + + struct T1: TableRecord { } + struct T2: TableRecord { } + struct T3: TableRecord { } + let observation1 = ValueObservation.trackingCount(T1.all()) + let observation2 = ValueObservation.trackingCount(T2.all()) + let observation3 = ValueObservation.trackingCount(T3.all()) + var observation = ValueObservation.combine(observation1, observation2, observation3) + observation.extent = .databaseLifetime + _ = try observation.start(in: dbQueue) { value in + values.append(value) + notificationExpectation.fulfill() + } + + try dbQueue.write { db in + try db.execute("INSERT INTO t1 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t3 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("DELETE FROM t1") + try db.execute("INSERT INTO t1 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("DELETE FROM t2") + try db.execute("INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("DELETE FROM t3") + try db.execute("INSERT INTO t3 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("DELETE FROM t1") + try db.execute("DELETE FROM t2") + try db.execute("DELETE FROM t3") + try db.execute("INSERT INTO t1 DEFAULT VALUES") + try db.execute("INSERT INTO t2 DEFAULT VALUES") + try db.execute("INSERT INTO t3 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t1 DEFAULT VALUES") + try db.execute("INSERT INTO t2 DEFAULT VALUES") + try db.execute("INSERT INTO t3 DEFAULT VALUES") + } + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(values.count, 5) + XCTAssert(values[0] == (0, 0, 0)) + XCTAssert(values[1] == (1, 0, 0)) + XCTAssert(values[2] == (1, 1, 0)) + XCTAssert(values[3] == (1, 1, 1)) + XCTAssert(values[4] == (2, 2, 2)) + } + + func testCombine4() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute(""" + CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT); + CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT); + CREATE TABLE t3(id INTEGER PRIMARY KEY AUTOINCREMENT); + CREATE TABLE t4(id INTEGER PRIMARY KEY AUTOINCREMENT); + """) + } + + var values: [(Int, Int, Int, Int)] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 6 + + struct T1: TableRecord { } + struct T2: TableRecord { } + struct T3: TableRecord { } + struct T4: TableRecord { } + let observation1 = ValueObservation.trackingCount(T1.all()) + let observation2 = ValueObservation.trackingCount(T2.all()) + let observation3 = ValueObservation.trackingCount(T3.all()) + let observation4 = ValueObservation.trackingCount(T4.all()) + var observation = ValueObservation.combine(observation1, observation2, observation3, observation4) + observation.extent = .databaseLifetime + _ = try observation.start(in: dbQueue) { value in + values.append(value) + notificationExpectation.fulfill() + } + + try dbQueue.write { db in + try db.execute("INSERT INTO t1 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t3 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t4 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("DELETE FROM t1") + try db.execute("INSERT INTO t1 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("DELETE FROM t2") + try db.execute("INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("DELETE FROM t3") + try db.execute("INSERT INTO t3 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("DELETE FROM t4") + try db.execute("INSERT INTO t4 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("DELETE FROM t1") + try db.execute("DELETE FROM t2") + try db.execute("DELETE FROM t3") + try db.execute("DELETE FROM t4") + try db.execute("INSERT INTO t1 DEFAULT VALUES") + try db.execute("INSERT INTO t2 DEFAULT VALUES") + try db.execute("INSERT INTO t3 DEFAULT VALUES") + try db.execute("INSERT INTO t4 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t1 DEFAULT VALUES") + try db.execute("INSERT INTO t2 DEFAULT VALUES") + try db.execute("INSERT INTO t3 DEFAULT VALUES") + try db.execute("INSERT INTO t4 DEFAULT VALUES") + } + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(values.count, 6) + XCTAssert(values[0] == (0, 0, 0, 0)) + XCTAssert(values[1] == (1, 0, 0, 0)) + XCTAssert(values[2] == (1, 1, 0, 0)) + XCTAssert(values[3] == (1, 1, 1, 0)) + XCTAssert(values[4] == (1, 1, 1, 1)) + XCTAssert(values[5] == (2, 2, 2, 2)) + } + + func testCombine5() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute(""" + CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT); + CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT); + CREATE TABLE t3(id INTEGER PRIMARY KEY AUTOINCREMENT); + CREATE TABLE t4(id INTEGER PRIMARY KEY AUTOINCREMENT); + CREATE TABLE t5(id INTEGER PRIMARY KEY AUTOINCREMENT); + """) + } + + var values: [(Int, Int, Int, Int, Int)] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 7 + + struct T1: TableRecord { } + struct T2: TableRecord { } + struct T3: TableRecord { } + struct T4: TableRecord { } + struct T5: TableRecord { } + let observation1 = ValueObservation.trackingCount(T1.all()) + let observation2 = ValueObservation.trackingCount(T2.all()) + let observation3 = ValueObservation.trackingCount(T3.all()) + let observation4 = ValueObservation.trackingCount(T4.all()) + let observation5 = ValueObservation.trackingCount(T5.all()) + var observation = ValueObservation.combine(observation1, observation2, observation3, observation4, observation5) + observation.extent = .databaseLifetime + _ = try observation.start(in: dbQueue) { value in + values.append(value) + notificationExpectation.fulfill() + } + + try dbQueue.write { db in + try db.execute("INSERT INTO t1 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t3 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t4 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t5 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("DELETE FROM t1") + try db.execute("INSERT INTO t1 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("DELETE FROM t2") + try db.execute("INSERT INTO t2 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("DELETE FROM t3") + try db.execute("INSERT INTO t3 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("DELETE FROM t4") + try db.execute("INSERT INTO t4 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("DELETE FROM t5") + try db.execute("INSERT INTO t5 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("DELETE FROM t1") + try db.execute("DELETE FROM t2") + try db.execute("DELETE FROM t3") + try db.execute("DELETE FROM t4") + try db.execute("DELETE FROM t5") + try db.execute("INSERT INTO t1 DEFAULT VALUES") + try db.execute("INSERT INTO t2 DEFAULT VALUES") + try db.execute("INSERT INTO t3 DEFAULT VALUES") + try db.execute("INSERT INTO t4 DEFAULT VALUES") + try db.execute("INSERT INTO t5 DEFAULT VALUES") + } + try dbQueue.write { db in + try db.execute("INSERT INTO t1 DEFAULT VALUES") + try db.execute("INSERT INTO t2 DEFAULT VALUES") + try db.execute("INSERT INTO t3 DEFAULT VALUES") + try db.execute("INSERT INTO t4 DEFAULT VALUES") + try db.execute("INSERT INTO t5 DEFAULT VALUES") + } + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(values.count, 7) + XCTAssert(values[0] == (0, 0, 0, 0, 0)) + XCTAssert(values[1] == (1, 0, 0, 0, 0)) + XCTAssert(values[2] == (1, 1, 0, 0, 0)) + XCTAssert(values[3] == (1, 1, 1, 0, 0)) + XCTAssert(values[4] == (1, 1, 1, 1, 0)) + XCTAssert(values[5] == (1, 1, 1, 1, 1)) + XCTAssert(values[6] == (2, 2, 2, 2, 2)) + } + + func testHeterogeneusCombine2() throws { + struct V1 { } + struct V2 { } + let observation1 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V1() }) + let observation2 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V2() }) + let observation = ValueObservation.combine(observation1, observation2) + var value: (V1, V2)? + _ = try observation.start(in: makeDatabaseQueue()) { value = $0 } + XCTAssertNotNil(value) + } + + func testHeterogeneusCombine3() throws { + struct V1 { } + struct V2 { } + struct V3 { } + let observation1 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V1() }) + let observation2 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V2() }) + let observation3 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V3() }) + let observation = ValueObservation.combine(observation1, observation2, observation3) + var value: (V1, V2, V3)? + _ = try observation.start(in: makeDatabaseQueue()) { value = $0 } + XCTAssertNotNil(value) + } + + func testHeterogeneusCombine4() throws { + struct V1 { } + struct V2 { } + struct V3 { } + struct V4 { } + let observation1 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V1() }) + let observation2 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V2() }) + let observation3 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V3() }) + let observation4 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V4() }) + let observation = ValueObservation.combine(observation1, observation2, observation3, observation4) + var value: (V1, V2, V3, V4)? + _ = try observation.start(in: makeDatabaseQueue()) { value = $0 } + XCTAssertNotNil(value) + } + + func testHeterogeneusCombine5() throws { + struct V1 { } + struct V2 { } + struct V3 { } + struct V4 { } + struct V5 { } + let observation1 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V1() }) + let observation2 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V2() }) + let observation3 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V3() }) + let observation4 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V4() }) + let observation5 = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in V5() }) + let observation = ValueObservation.combine(observation1, observation2, observation3, observation4, observation5) + var value: (V1, V2, V3, V4, V5)? + _ = try observation.start(in: makeDatabaseQueue()) { value = $0 } + XCTAssertNotNil(value) + } +} diff --git a/Tests/GRDBTests/ValueObservationCompactMapTests.swift b/Tests/GRDBTests/ValueObservationCompactMapTests.swift new file mode 100644 index 000000000..5d3d91f94 --- /dev/null +++ b/Tests/GRDBTests/ValueObservationCompactMapTests.swift @@ -0,0 +1,79 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + #if SWIFT_PACKAGE + import CSQLite + #else + import SQLite3 + #endif + import GRDB +#endif + +class ValueObservationCompactMapTests: GRDBTestCase { + func testCompactMap() throws { + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [String] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + // The base reducer + var count = 0 + let reducer = AnyValueReducer( + fetch: { _ in /* don't fetch anything */ }, + value: { _ -> Int? in + count += 1 + return count + }) + + // Create an observation + var observation = ValueObservation + .tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) + .compactMap { count -> String? in + if count % 2 == 0 { return nil } + return "\(count)" + } + observation.extent = .databaseLifetime + + // Start observation + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.writeWithoutTransaction { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, ["1", "3"]) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func testCompactMapPreservesConfiguration() { + var observation = ValueObservation.tracking(DatabaseRegion(), fetch: { _ in }) + observation.extent = .nextTransaction + observation.requiresWriteAccess = true + observation.scheduling = .unsafe(startImmediately: true) + + let mappedObservation = observation.compactMap { _ in } + XCTAssertEqual(mappedObservation.extent, observation.extent) + XCTAssertEqual(mappedObservation.requiresWriteAccess, observation.requiresWriteAccess) + switch mappedObservation.scheduling { + case .unsafe: + break + default: + XCTFail() + } + } +} diff --git a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift index 1f5e11562..bc996d858 100644 --- a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift @@ -1,15 +1,15 @@ import XCTest #if GRDBCIPHER - import GRDBCipher + @testable import GRDBCipher #elseif GRDBCUSTOMSQLITE - import GRDBCustomSQLite + @testable import GRDBCustomSQLite #else #if SWIFT_PACKAGE import CSQLite #else import SQLite3 #endif - import GRDB + @testable import GRDB #endif private struct Name: DatabaseValueConvertible { @@ -143,4 +143,58 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { ["foo", nil], [nil]]) } + + func testViewOptimization() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute(""" + CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT); + CREATE VIEW v AS SELECT * FROM t + """) + } + + var results: [[Name]] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 4 + + // Test that view v is included in the request region + let request = SQLRequest("SELECT name FROM v ORDER BY id") + try dbQueue.inDatabase { db in + let region = try request.databaseRegion(db) + XCTAssertEqual(region.description, "t(id,name),v(id,name)") + } + + // Test that view v is not included in the observed region. + // This optimization helps observation of views that feed from a + // single table. + var observation = ValueObservation.trackingAll(request) + observation.extent = .databaseLifetime + let transactionObserver = try observation.start(in: dbQueue) { names in + results.append(names) + notificationExpectation.fulfill() + } + let valueObserver = transactionObserver as! ValueObserver>> + XCTAssertEqual(valueObserver.region.description, "t(id,name)") // view is not tracked + + // Test view observation + try dbQueue.inDatabase { db in + try db.execute("INSERT INTO t (id, name) VALUES (1, 'foo')") // +1 + try db.execute("UPDATE t SET name = 'foo' WHERE id = 1") // = + try db.inTransaction { // +1 + try db.execute("INSERT INTO t (id, name) VALUES (2, 'bar')") + try db.execute("INSERT INTO t (id, name) VALUES (3, 'baz')") + try db.execute("DELETE FROM t WHERE id = 3") + return .commit + } + try db.execute("DELETE FROM t WHERE id = 1") // -1 + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(results.map { $0.map { $0.rawValue }}, [ + [], + ["foo"], + ["foo", "bar"], + ["bar"]]) + } } diff --git a/Tests/GRDBTests/ValueObservationExtentTests.swift b/Tests/GRDBTests/ValueObservationExtentTests.swift index 253507f6f..47fef4251 100644 --- a/Tests/GRDBTests/ValueObservationExtentTests.swift +++ b/Tests/GRDBTests/ValueObservationExtentTests.swift @@ -23,7 +23,7 @@ class ValueObservationExtentTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - // Track reducer proceess + // Track reducer process let notificationExpectation = expectation(description: "notification") notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 3 @@ -34,7 +34,7 @@ class ValueObservationExtentTests: GRDBTestCase { value: { $0 }) // Create an observation - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) observation.extent = .databaseLifetime // Start observation @@ -60,7 +60,7 @@ class ValueObservationExtentTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - // Track reducer proceess + // Track reducer process var changesCount = 0 let notificationExpectation = expectation(description: "notification") notificationExpectation.assertForOverFulfill = true @@ -72,7 +72,7 @@ class ValueObservationExtentTests: GRDBTestCase { value: { $0 }) // Create an observation - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) observation.extent = .observerLifetime // Start observation and deallocate observer after second change @@ -107,7 +107,7 @@ class ValueObservationExtentTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - // Track reducer proceess + // Track reducer process let notificationExpectation = expectation(description: "notification") notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 2 @@ -118,7 +118,7 @@ class ValueObservationExtentTests: GRDBTestCase { value: { $0 }) // Create an observation - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) observation.extent = .nextTransaction // Start observation diff --git a/Tests/GRDBTests/ValueObservationFetchTests.swift b/Tests/GRDBTests/ValueObservationFetchTests.swift index de6aa1dbe..e4755699a 100644 --- a/Tests/GRDBTests/ValueObservationFetchTests.swift +++ b/Tests/GRDBTests/ValueObservationFetchTests.swift @@ -13,67 +13,111 @@ import XCTest #endif class ValueObservationFetchTests: GRDBTestCase { - func testFetch() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 4 - - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! - }) - observation.extent = .databaseLifetime - _ = try observation.start(in: dbQueue) { count in - counts.append(count) - notificationExpectation.fulfill() - } - - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") - } - try dbQueue.write { - try $0.execute("UPDATE t SET id = id") - } - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1, 1, 2]) + func testRegionsAPI() { + // single region + _ = ValueObservation.tracking(DatabaseRegion(), fetch: { _ in }) + _ = ValueObservation.tracking(DatabaseRegion(), fetchDistinct: { _ in 0 }) + // variadic + _ = ValueObservation.tracking(DatabaseRegion(), DatabaseRegion(), fetch: { _ in }) + _ = ValueObservation.tracking(DatabaseRegion(), DatabaseRegion(), fetchDistinct: { _ in 0 }) + // array + _ = ValueObservation.tracking([DatabaseRegion()], fetch: { _ in }) } - func testFetchWithUniquing() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 3 - - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetchDistinct: { - try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! - }) - observation.extent = .databaseLifetime - _ = try observation.start(in: dbQueue) { count in - counts.append(count) - notificationExpectation.fulfill() + func testFetch() throws { + func test(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 4 + + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! + }) + observation.extent = .databaseLifetime + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.writeWithoutTransaction { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("UPDATE t SET id = id") + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1, 1, 2]) } - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") - } - try dbQueue.write { - try $0.execute("UPDATE t SET id = id") - } - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + // Test for a deprecated API + func testFetchDistinct() throws { + func test(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetchDistinct: { + try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! + }) + observation.extent = .databaseLifetime + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.writeWithoutTransaction { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("UPDATE t SET id = id") + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1, 2]) } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1, 2]) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func testDistinctUntilChanged() throws { + func test(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! + }).distinctUntilChanged() + observation.extent = .databaseLifetime + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.writeWithoutTransaction { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("UPDATE t SET id = id") + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1, 2]) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } } diff --git a/Tests/GRDBTests/ValueObservationMapTests.swift b/Tests/GRDBTests/ValueObservationMapTests.swift new file mode 100644 index 000000000..16a8c08b5 --- /dev/null +++ b/Tests/GRDBTests/ValueObservationMapTests.swift @@ -0,0 +1,76 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + #if SWIFT_PACKAGE + import CSQLite + #else + import SQLite3 + #endif + import GRDB +#endif + +class ValueObservationMapTests: GRDBTestCase { + func testMap() throws { + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [String] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + // The base reducer + var count = 0 + let reducer = AnyValueReducer( + fetch: { _ in /* don't fetch anything */ }, + value: { _ -> Int? in + count += 1 + return count + }) + + // Create an observation + var observation = ValueObservation + .tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) + .map { count -> String in return "\(count)" } + observation.extent = .databaseLifetime + + // Start observation + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.writeWithoutTransaction { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, ["1", "2", "3"]) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func testMapPreservesConfiguration() { + var observation = ValueObservation.tracking(DatabaseRegion(), fetch: { _ in }) + observation.extent = .nextTransaction + observation.requiresWriteAccess = true + observation.scheduling = .unsafe(startImmediately: true) + + let mappedObservation = observation.map { _ in } + XCTAssertEqual(mappedObservation.extent, observation.extent) + XCTAssertEqual(mappedObservation.requiresWriteAccess, observation.requiresWriteAccess) + switch mappedObservation.scheduling { + case .unsafe: + break + default: + XCTFail() + } + } +} diff --git a/Tests/GRDBTests/ValueObservationReducerTests.swift b/Tests/GRDBTests/ValueObservationReducerTests.swift index 393da3e7c..c34f83a4a 100644 --- a/Tests/GRDBTests/ValueObservationReducerTests.swift +++ b/Tests/GRDBTests/ValueObservationReducerTests.swift @@ -1,4 +1,5 @@ import XCTest +import Dispatch #if GRDBCIPHER import GRDBCipher #elseif GRDBCUSTOMSQLITE @@ -13,290 +14,459 @@ import XCTest #endif class ValueObservationReducerTests: GRDBTestCase { + func testRegionsAPI() { + let reducer = AnyValueReducer(fetch: { _ in }, value: { }) + + // single region + _ = ValueObservation.tracking(DatabaseRegion(), reducer: { _ in reducer }) + // variadic + _ = ValueObservation.tracking(DatabaseRegion(), DatabaseRegion(), reducer: { _ in reducer }) + // array + _ = ValueObservation.tracking([DatabaseRegion()], reducer: { _ in reducer }) + } + func testReducer() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - // Track reducer proceess - var fetchCount = 0 - var reduceCount = 0 - var errors: [Error] = [] - var changes: [String] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 3 - - // A reducer which tracks its progress - var dropNext = false // if true, reducer drops next value - let reducer = AnyValueReducer( - fetch: { db -> Int in - fetchCount += 1 - // test for database access - return try Int.fetchOne(db, "SELECT COUNT(*) FROM t")! + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + // Track reducer process + var fetchCount = 0 + var reduceCount = 0 + var errors: [Error] = [] + var changes: [String] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + // A reducer which tracks its progress + let reducer = AnyValueReducer( + fetch: { db -> Int in + fetchCount += 1 + // test for database access + return try Int.fetchOne(db, "SELECT COUNT(*) FROM t")! }, - value: { count -> String? in - reduceCount += 1 - if dropNext { - // test that reducer can drop values - dropNext = false - return nil + value: { count -> String? in + reduceCount += 1 + if count == 3 { + // test that reducer can drop values + return nil + } + // test that the fetched type and the notified type can be different + return count.description + }) + + // Create an observation + let request = SQLRequest("SELECT * FROM t") + var observation = ValueObservation.tracking(request, reducer: { _ in reducer }) + observation.extent = .databaseLifetime + + // Start observation + _ = try observation.start( + in: dbWriter, + onError: { + errors.append($0) + notificationExpectation.fulfill() + }, + onChange: { + changes.append($0) + notificationExpectation.fulfill() + }) + + + // Test that default config synchronously notifies initial value + XCTAssertEqual(fetchCount, 1) + XCTAssertEqual(reduceCount, 1) + XCTAssertEqual(errors.count, 0) + XCTAssertEqual(changes, ["0"]) + + try dbWriter.writeWithoutTransaction { db in + // Test a 1st notified transaction + try db.inTransaction { + try db.execute("INSERT INTO t DEFAULT VALUES") + return .commit + } + + // Test an untracked transaction + try db.inTransaction { + try db.execute("CREATE TABLE ignored(a)") + return .commit + } + + // Test a dropped transaction + try db.inTransaction { + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("INSERT INTO t DEFAULT VALUES") + return .commit + } + + // Test a rollbacked transaction + try db.inTransaction { + try db.execute("INSERT INTO t DEFAULT VALUES") + return .rollback + } + + // Test a 2nd notified transaction + try db.inTransaction { + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("INSERT INTO t DEFAULT VALUES") + return .commit } - // test that the fetched type and the notified type can be different - return count.description - }) - - // Create an observation - let request = SQLRequest("SELECT * FROM t") - var observation = ValueObservation.tracking(request, reducer: reducer) - observation.extent = .databaseLifetime - - // Start observation - _ = try observation.start( - in: dbQueue, - onError: { - errors.append($0) - notificationExpectation.fulfill() - }, - onChange: { - changes.append($0) - notificationExpectation.fulfill() - }) - - - // Test that default config synchronously notifies initial value - XCTAssertEqual(fetchCount, 1) - XCTAssertEqual(reduceCount, 1) - XCTAssertEqual(errors.count, 0) - XCTAssertEqual(changes, ["0"]) - - try dbQueue.inDatabase { db in - // Test a 1st notified transaction - try db.inTransaction { - try db.execute("INSERT INTO t DEFAULT VALUES") - return .commit } - // Test an untracked transaction - try db.inTransaction { - try db.execute("CREATE TABLE ignored(a)") - return .commit - } - - // Test a dropped transaction - dropNext = true - try db.inTransaction { - try db.execute("INSERT INTO t DEFAULT VALUES") - try db.execute("INSERT INTO t DEFAULT VALUES") - return .commit - } - - // Test a rollbacked transaction - try db.inTransaction { - try db.execute("INSERT INTO t DEFAULT VALUES") - return .rollback - } - - // Test a 2nd notified transaction - try db.inTransaction { - try db.execute("INSERT INTO t DEFAULT VALUES") - try db.execute("INSERT INTO t DEFAULT VALUES") - return .commit - } + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(fetchCount, 4) + XCTAssertEqual(reduceCount, 4) + XCTAssertEqual(errors.count, 0) + XCTAssertEqual(changes, ["0", "1", "5"]) } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(fetchCount, 4) - XCTAssertEqual(reduceCount, 4) - XCTAssertEqual(errors.count, 0) - XCTAssertEqual(changes, ["0", "1", "5"]) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } func testInitialError() throws { - struct TestError: Error { } - let reducer = AnyValueReducer( - fetch: { _ in throw TestError() }, - value: { _ in fatalError() }) - - // Create an observation - let observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) - - // Start observation - do { - let dbQueue = try makeDatabaseQueue() - _ = try observation.start( - in: dbQueue, - onError: { _ in fatalError() }, - onChange: { _ in fatalError() }) - XCTFail("Expected error") - } catch is TestError { + func test(_ dbWriter: DatabaseWriter) throws { + struct TestError: Error { } + let reducer = AnyValueReducer( + fetch: { _ in throw TestError() }, + value: { _ in fatalError() }) + + // Create an observation + let observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) + + // Start observation + do { + _ = try observation.start( + in: dbWriter, + onError: { _ in fatalError() }, + onChange: { _ in fatalError() }) + XCTFail("Expected error") + } catch is TestError { + } } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } func testSuccessThenErrorThenSuccess() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - // Track reducer proceess - var errors: [Error] = [] - var changes: [Void] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 3 - - // A reducer which throws an error is requested to do so - var nextError: Error? = nil // If not null, reducer throws an error - let reducer = AnyValueReducer( - fetch: { _ -> Void in - if let error = nextError { - nextError = nil - throw error - } + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + // Track reducer process + var errors: [Error] = [] + var changes: [Void] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + // A reducer which throws an error is requested to do so + var nextError: Error? = nil // If not null, reducer throws an error + let reducer = AnyValueReducer( + fetch: { _ -> Void in + if let error = nextError { + nextError = nil + throw error + } }, - value: { $0 }) - - // Create an observation - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) - observation.extent = .databaseLifetime - - // Start observation - _ = try observation.start( - in: dbQueue, - onError: { - errors.append($0) - notificationExpectation.fulfill() + value: { $0 }) + + // Create an observation + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) + observation.extent = .databaseLifetime + + // Start observation + _ = try observation.start( + in: dbWriter, + onError: { + errors.append($0) + notificationExpectation.fulfill() }, - onChange: { - changes.append($0) - notificationExpectation.fulfill() + onChange: { + changes.append($0) + notificationExpectation.fulfill() }) - - struct TestError: Error { } - nextError = TestError() - try dbQueue.write { db in - try db.execute("INSERT INTO t DEFAULT VALUES") + + struct TestError: Error { } + nextError = TestError() + try dbWriter.writeWithoutTransaction { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(errors.count, 1) + XCTAssertEqual(changes.count, 2) } - try dbQueue.write { db in - try db.execute("INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(errors.count, 1) - XCTAssertEqual(changes.count, 2) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } + func testDeprecatedReadMeReducer() throws { + func test(_ dbWriter: DatabaseWriter) throws { + // Test for the reducer documented in the main README + + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + // Track reducer process + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + // Create an observation + var count = 0 + let reducer = AnyValueReducer( + fetch: { _ in /* don't fetch anything */ }, + value: { _ -> Int? in + defer { count += 1 } + return count }) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + observation.extent = .databaseLifetime + + // Start observation + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.write { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1]) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + func testReadMeReducer() throws { - // Test for the reducer documented in the main README - - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - // Track reducer proceess - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - // The reducer - var count = 0 - let reducer = AnyValueReducer( - fetch: { _ in /* don't fetch anything */ }, - value: { _ -> Int? in - count += 1 - return count - }) - - // Create an observation - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) - observation.extent = .databaseLifetime - - // Start observation - _ = try observation.start(in: dbQueue) { count in - counts.append(count) - notificationExpectation.fulfill() + func test(_ dbWriter: DatabaseWriter) throws { + // Test for the reducer documented in the main README + + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + // Track reducer process + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + // Create an observation + var count = 0 + let reducer = AnyValueReducer( + fetch: { _ in /* don't fetch anything */ }, + value: { _ -> Int? in + defer { count += 1 } + return count }) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer}) + observation.extent = .databaseLifetime + + // Start observation + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.write { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1]) } - try dbQueue.write { db in - try db.execute("INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [1, 2]) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } func testMapValueReducer() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - // Track reducer proceess - var counts: [String] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - // The base reducer - var count = 0 - let reducer = AnyValueReducer( - fetch: { _ in /* don't fetch anything */ }, - value: { _ -> Int? in - count += 1 - return count - }) - - // The mapped reducer - let mapReducer = reducer.map { count -> String? in - if count % 2 == 0 { return nil } - return "\(count)" + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + // Track reducer process + var counts: [String] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + // The base reducer + var count = 0 + let baseReducer = AnyValueReducer( + fetch: { _ in /* don't fetch anything */ }, + value: { _ -> Int? in + count += 1 + return count + }) + + // The mapped reducer + let reducer = baseReducer.map { count -> String in + return "\(count)" + } + + // Create an observation + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) + observation.extent = .databaseLifetime + + // Start observation + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.writeWithoutTransaction { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, ["1", "2", "3"]) } - // Create an observation - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: mapReducer) - observation.extent = .databaseLifetime - - // Start observation - _ = try observation.start(in: dbQueue) { count in - counts.append(count) - notificationExpectation.fulfill() - } - - try dbQueue.inDatabase { db in - try db.execute("INSERT INTO t DEFAULT VALUES") - try db.execute("INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, ["1", "3"]) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } + func testCompactMapValueReducer() throws { + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + // Track reducer process + var counts: [String] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + // The base reducer + var count = 0 + let baseReducer = AnyValueReducer( + fetch: { _ in /* don't fetch anything */ }, + value: { _ -> Int? in + count += 1 + return count + }) + + // The mapped reducer + let reducer = baseReducer.compactMap { count -> String? in + if count % 2 == 0 { return nil } + return "\(count)" + } + + // Create an observation + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) + observation.extent = .databaseLifetime + + // Start observation + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.writeWithoutTransaction { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, ["1", "3"]) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + func testValueObservationMap() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [String] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 3 - - struct T: TableRecord { } - var observation = ValueObservation - .trackingCount(T.all()) - .map { "\($0)" } - observation.extent = .databaseLifetime - _ = try observation.start(in: dbQueue) { count in - counts.append(count) - notificationExpectation.fulfill() + func test(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [String] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + struct T: TableRecord { } + var observation = ValueObservation + .trackingCount(T.all()) + .map { "\($0)" } + observation.extent = .databaseLifetime + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.writeWithoutTransaction { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, ["0", "1", "2"]) } - try dbQueue.inDatabase { - try $0.execute("INSERT INTO t DEFAULT VALUES") - try $0.execute("INSERT INTO t DEFAULT VALUES") + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func testReducerQueueLabel() throws { + func test(_ dbWriter: DatabaseWriter, expectedLabels: [String]) throws { + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + let reduceExpectation = expectation(description: "notification") + reduceExpectation.assertForOverFulfill = true + reduceExpectation.expectedFulfillmentCount = expectedLabels.count + + var labels: [String] = [] + let reducer = AnyValueReducer(fetch: { _ in }, value: { _ in + // This test CAN break in future releases: the dispatch queue labels + // are documented to be a debug-only tool. + if let label = String(utf8String: __dispatch_queue_get_label(nil)) { + labels.append(label) + } + reduceExpectation.fulfill() + }) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) + observation.extent = .databaseLifetime + _ = try observation.start(in: dbWriter, onChange: { _ in }) + + try dbWriter.write { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(labels, expectedLabels) + } + do { + // dbQueue with default label + dbConfiguration.label = nil + let dbQueue = try makeDatabaseQueue() + try test(dbQueue, expectedLabels: ["GRDB.DatabaseQueue", "GRDB.ValueObservation.reducer"]) + } + do { + // dbQueue with custom label + dbConfiguration.label = "Custom" + let dbQueue = try makeDatabaseQueue() + try test(dbQueue, expectedLabels: ["Custom", "Custom.ValueObservation.reducer"]) + } + do { + // dbPool with default label + dbConfiguration.label = nil + let dbPool = try makeDatabasePool() + try test(dbPool, expectedLabels: ["GRDB.DatabasePool.writer", "GRDB.ValueObservation.reducer"]) + } + do { + // dbPool with custom label + dbConfiguration.label = "Custom" + let dbPool = try makeDatabasePool() + try test(dbPool, expectedLabels: ["Custom.writer", "Custom.ValueObservation.reducer"]) } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, ["0", "1", "2"]) } } diff --git a/Tests/GRDBTests/ValueObservationSchedulingTests.swift b/Tests/GRDBTests/ValueObservationSchedulingTests.swift index 18593a024..fe1251eba 100644 --- a/Tests/GRDBTests/ValueObservationSchedulingTests.swift +++ b/Tests/GRDBTests/ValueObservationSchedulingTests.swift @@ -14,364 +14,404 @@ import XCTest class ValueObservationSchedulingTests: GRDBTestCase { func testMainQueueObservationStartedFromMainQueue() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let key = DispatchSpecificKey<()>() - DispatchQueue.main.setSpecific(key: key, value: ()) - - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! - }) - observation.extent = .databaseLifetime - - _ = try observation.start(in: dbQueue) { count in - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - counts.append(count) - notificationExpectation.fulfill() - } - // .mainQueue scheduling: initial value MUST be synchronously - // dispatched when observation is started from the main queue - XCTAssertEqual(counts, [0]) - - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! + }) + observation.extent = .databaseLifetime + + _ = try observation.start(in: dbWriter) { count in + XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) + counts.append(count) + notificationExpectation.fulfill() + } + // .mainQueue scheduling: initial value MUST be synchronously + // dispatched when observation is started from the main queue + XCTAssertEqual(counts, [0]) + + try dbWriter.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1]) } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1]) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } @available(OSX 10.10, *) // DispatchQueue qos func testMainQueueObservationStartedFromAnotherQueue() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! + }) + observation.extent = .databaseLifetime + + DispatchQueue.global(qos: .default).async { + _ = try! observation.start(in: dbWriter) { count in + XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) + counts.append(count) + notificationExpectation.fulfill() + } + + try! dbWriter.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1]) + } - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func testMainQueueError() throws { + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var errorCount = 0 + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + + var nextError: Error? = nil // If not null, reducer throws an error + let reducer = AnyValueReducer( + fetch: { _ -> Void in + if let error = nextError { + nextError = nil + throw error + } + }, + value: { $0 }) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) + observation.extent = .databaseLifetime + + _ = try observation.start( + in: dbWriter, + onError: { error in + XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) + errorCount += 1 + notificationExpectation.fulfill() + }, + onChange: { _ in + XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) + notificationExpectation.fulfill() + }) + + struct TestError: Error { } + nextError = TestError() + try dbWriter.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(errorCount, 1) + } - let key = DispatchSpecificKey<()>() - DispatchQueue.main.setSpecific(key: key, value: ()) - - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! - }) - observation.extent = .databaseLifetime - - DispatchQueue.global(qos: .default).async { - _ = try! observation.start(in: dbQueue) { count in + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func testCustomQueueStartImmediately() throws { + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + let queue = DispatchQueue(label: "") + let key = DispatchSpecificKey<()>() + queue.setSpecific(key: key, value: ()) + + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! + }) + observation.extent = .databaseLifetime + observation.scheduling = .onQueue(queue, startImmediately: true) + + _ = try observation.start(in: dbWriter) { count in XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) counts.append(count) notificationExpectation.fulfill() } - try! dbQueue.write { + try dbWriter.write { try $0.execute("INSERT INTO t DEFAULT VALUES") } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1]) } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1]) - } - - func testMainQueueError() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var errorCount = 0 - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let key = DispatchSpecificKey<()>() - DispatchQueue.main.setSpecific(key: key, value: ()) - - var nextError: Error? = nil // If not null, reducer throws an error - let reducer = AnyValueReducer( - fetch: { _ -> Void in - if let error = nextError { - nextError = nil - throw error - } - }, - value: { $0 }) - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) - observation.extent = .databaseLifetime - - _ = try observation.start( - in: dbQueue, - onError: { error in - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - errorCount += 1 - notificationExpectation.fulfill() - }, - onChange: { _ in - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - notificationExpectation.fulfill() - }) - - struct TestError: Error { } - nextError = TestError() - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(errorCount, 1) - } - - func testCustomQueueStartImmediately() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let queue = DispatchQueue(label: "") - let key = DispatchSpecificKey<()>() - queue.setSpecific(key: key, value: ()) - - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! - }) - observation.extent = .databaseLifetime - observation.scheduling = .onQueue(queue, startImmediately: true) - - _ = try observation.start(in: dbQueue) { count in - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - counts.append(count) - notificationExpectation.fulfill() - } - - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1]) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } func testCustomQueueDontStartImmediately() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 1 - - let queue = DispatchQueue(label: "") - let key = DispatchSpecificKey<()>() - queue.setSpecific(key: key, value: ()) - - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! - }) - observation.extent = .databaseLifetime - observation.scheduling = .onQueue(queue, startImmediately: false) - - _ = try observation.start(in: dbQueue) { count in - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - counts.append(count) - notificationExpectation.fulfill() + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 1 + + let queue = DispatchQueue(label: "") + let key = DispatchSpecificKey<()>() + queue.setSpecific(key: key, value: ()) + + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! + }) + observation.extent = .databaseLifetime + observation.scheduling = .onQueue(queue, startImmediately: false) + + _ = try observation.start(in: dbWriter) { count in + XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [1]) } - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [1]) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } func testCustomQueueError() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var errorCount = 0 - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 1 - - let queue = DispatchQueue(label: "") - let key = DispatchSpecificKey<()>() - queue.setSpecific(key: key, value: ()) - - struct TestError: Error { } - let reducer = AnyValueReducer( - fetch: { _ in throw TestError() }, - value: { $0 }) - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) - observation.extent = .databaseLifetime - observation.scheduling = .onQueue(queue, startImmediately: false) - - _ = try observation.start( - in: dbQueue, - onError: { error in - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - errorCount += 1 - notificationExpectation.fulfill() + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var errorCount = 0 + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 1 + + let queue = DispatchQueue(label: "") + let key = DispatchSpecificKey<()>() + queue.setSpecific(key: key, value: ()) + + struct TestError: Error { } + let reducer = AnyValueReducer( + fetch: { _ in throw TestError() }, + value: { $0 }) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) + observation.extent = .databaseLifetime + observation.scheduling = .onQueue(queue, startImmediately: false) + + _ = try observation.start( + in: dbWriter, + onError: { error in + XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) + errorCount += 1 + notificationExpectation.fulfill() }, - onChange: { _ in fatalError() }) - - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") + onChange: { _ in fatalError() }) + + try dbWriter.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(errorCount, 1) } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(errorCount, 1) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } func testUnsafeStartImmediatelyFromMainQueue() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let key = DispatchSpecificKey<()>() - DispatchQueue.main.setSpecific(key: key, value: ()) - - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! - }) - observation.extent = .databaseLifetime - observation.scheduling = .unsafe(startImmediately: true) - - _ = try observation.start(in: dbQueue) { count in - if counts.isEmpty { - // require main queue on first element - XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) - } - counts.append(count) - notificationExpectation.fulfill() - } - - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1]) - } - - func testUnsafeStartImmediatelyFromCustomQueue() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 2 - - let queue = DispatchQueue(label: "") - let key = DispatchSpecificKey<()>() - queue.setSpecific(key: key, value: ()) - - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! - }) - observation.extent = .databaseLifetime - observation.scheduling = .unsafe(startImmediately: true) - - queue.async { - _ = try! observation.start(in: dbQueue) { count in + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! + }) + observation.extent = .databaseLifetime + observation.scheduling = .unsafe(startImmediately: true) + + _ = try observation.start(in: dbWriter) { count in if counts.isEmpty { - // require custom queue on first notification + // require main queue on first element XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) } counts.append(count) notificationExpectation.fulfill() } - try! dbQueue.write { + try dbWriter.write { try $0.execute("INSERT INTO t DEFAULT VALUES") } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1]) } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1]) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) + } + + func testUnsafeStartImmediatelyFromCustomQueue() throws { + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + let queue = DispatchQueue(label: "") + let key = DispatchSpecificKey<()>() + queue.setSpecific(key: key, value: ()) + + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! + }) + observation.extent = .databaseLifetime + observation.scheduling = .unsafe(startImmediately: true) + + queue.async { + _ = try! observation.start(in: dbWriter) { count in + if counts.isEmpty { + // require custom queue on first notification + XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) + } + counts.append(count) + notificationExpectation.fulfill() + } + + try! dbWriter.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1]) + } + + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } func testUnsafeDontStartImmediately() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 1 - - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { - try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! - }) - observation.extent = .databaseLifetime - observation.scheduling = .unsafe(startImmediately: false) - - _ = try observation.start(in: dbQueue) { count in - counts.append(count) - notificationExpectation.fulfill() + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var counts: [Int] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 1 + + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { + try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! + }) + observation.extent = .databaseLifetime + observation.scheduling = .unsafe(startImmediately: false) + + _ = try observation.start(in: dbWriter) { count in + counts.append(count) + notificationExpectation.fulfill() + } + + try dbWriter.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [1]) } - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") - } - - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [1]) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } func testUnsafeError() throws { - // We need something to change - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var errorCount = 0 - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 1 - - struct TestError: Error { } - let reducer = AnyValueReducer( - fetch: { _ in throw TestError() }, - value: { $0 }) - var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) - observation.extent = .databaseLifetime - observation.scheduling = .unsafe(startImmediately: false) - - _ = try observation.start( - in: dbQueue, - onError: { error in - errorCount += 1 - notificationExpectation.fulfill() + func test(_ dbWriter: DatabaseWriter) throws { + // We need something to change + try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + var errorCount = 0 + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 1 + + struct TestError: Error { } + let reducer = AnyValueReducer( + fetch: { _ in throw TestError() }, + value: { $0 }) + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer }) + observation.extent = .databaseLifetime + observation.scheduling = .unsafe(startImmediately: false) + + _ = try observation.start( + in: dbWriter, + onError: { error in + errorCount += 1 + notificationExpectation.fulfill() }, - onChange: { _ in fatalError() }) - - try dbQueue.write { - try $0.execute("INSERT INTO t DEFAULT VALUES") + onChange: { _ in fatalError() }) + + try dbWriter.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(errorCount, 1) } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(errorCount, 1) + try test(makeDatabaseQueue()) + try test(makeDatabasePool()) } } diff --git a/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift b/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift index 44eecc8a3..d28fcb6f4 100644 --- a/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift +++ b/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift @@ -1,11 +1,3 @@ -// -// AppDelegate.swift -// GRDBProfiling -// -// Created by Gwendal Roué on 15/09/2015. -// Copyright © 2015 Gwendal Roué. All rights reserved. -// - import Cocoa import GRDB diff --git a/Tests/Performance/GRDBProfiling/GRDBProfiling/ViewController.swift b/Tests/Performance/GRDBProfiling/GRDBProfiling/ViewController.swift index 7bf4397e5..fed4f07a5 100644 --- a/Tests/Performance/GRDBProfiling/GRDBProfiling/ViewController.swift +++ b/Tests/Performance/GRDBProfiling/GRDBProfiling/ViewController.swift @@ -1,11 +1,3 @@ -// -// ViewController.swift -// GRDBProfiling -// -// Created by Gwendal Roué on 15/09/2015. -// Copyright © 2015 Gwendal Roué. All rights reserved. -// - import Cocoa class ViewController: NSViewController {