diff --git a/CHANGELOG.md b/CHANGELOG.md index ce202e6de..afec8ff14 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,127 @@ Release Notes ============= +## Next Version + +This release comes with **[ValueObservation](README.md#valueobservation)**, a new type which tracks the results of database requests, and notifies fresh values whenever the database changes: + +```swift +let observer = ValueObversation + .trackingOne(Player.filter(key: 42)) + .start(in: dbQueue) { player: Player? in + print("Player has changed") + } +``` + +ValueObservation also aims at providing support for third-party code that needs to react to database changes. For example, [RxSwiftCommunity/RxGRDB#46](https://github.com/RxSwiftCommunity/RxGRDB/pull/46) is the pull request which implements RxGRDB, the companion library based on [RxSwift](https://github.com/ReactiveX/RxSwift), on top of ValueObservation. + + +### New + +- [#435](https://github.com/groue/GRDB.swift/pull/435): Improved support for values observation +- It is now possible to observe database change from a [DatabaseReader](https://groue.github.io/GRDB.swift/docs/3.5/Protocols/DatabaseReader.html). + + +### Breaking Change + +It used to be possible to define custom types that adopt the [DatabaseReader and DatabaseWriter protocols](README.md#databasewriter-and-databasereader-protocols), with a major drawback: it was impossible to add concurrency-related APIs to GRDB without breaking user code. Now all types that adopt those protocols are defined by GRDB: DatabaseQueue, DatabasePool, DatabaseSnapshot, AnyDatabaseReader, and AnyDatabaseWriter. **Expanding this set is no longer supported.** + + +### Documentation Diff + +- [ValueObservation](README.md#valueobservation): this new chapter describes the new way to observe database values. + + +### API diff + +```diff + protocol DatabaseReader: class { ++ func add( ++ observation: ValueObservation, ++ onError: ((Error) -> Void)?, ++ onChange: @escaping (Reducer.Value) -> Void) ++ throws -> TransactionObserver ++ func remove(transactionObserver: TransactionObserver) + } + + protocol DatabaseWriter: DatabaseReader { +- func remove(transactionObserver: TransactionObserver) + } + ++protocol DatabaseRegionConvertible { ++ func databaseRegion(_ db: Database) throws -> DatabaseRegion ++} ++ ++extension DatabaseRegion: DatabaseRegionConvertible { } ++ ++struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible { ++ init(_ region: @escaping (Database) throws -> DatabaseRegion) ++ init(_ region: DatabaseRegionConvertible) ++} + +-protocol FetchRequest { ... } ++protocol FetchRequest: DatabaseRegionConvertible { ... } + ++enum ValueScheduling { ++ case mainQueue ++ case onQueue(DispatchQueue, startImmediately: Bool) ++ case unsafe(startImmediately: Bool) ++} + ++protocol ValueReducer { ++ associatedtype Fetched ++ associatedtype Value ++ func fetch(_ db: Database) throws -> Fetched ++ mutating func value(_ fetched: Fetched) -> Value? ++} ++ ++extension ValueReducer { ++ func map(_ transform: @escaping (Value) -> T?) -> MapValueReducer ++} ++ ++struct AnyValueReducer: ValueReducer { ++ init(fetch: @escaping (Database) throws -> Fetched, value: @escaping (Fetched) -> Value?) ++ init(_ reducer: Reducer) where Reducer.Fetched == Fetched, Reducer.Value == Value ++} + ++struct ValueObservation { ++ var extent: Database.TransactionObservationExtent ++ var requiresWriteAccess: Bool ++ var scheduling: ValueScheduling ++ static func tracking(_ regions: DatabaseRegionConvertible..., reducer: Reducer) -> ValueObservation ++} ++ ++extension ValueObservation where Reducer: ValueReducer { ++ func map(_ transform: @escaping (Reducer.Value) -> T) ++ -> ValueObservation> ++ func start( ++ in reader: DatabaseReader, ++ onError: ((Error) -> Void)? = nil, ++ onChange: @escaping (Reducer.Value) -> Void) throws -> TransactionObserver ++} ++ ++extension ValueObservation where Reducer == Void { ++ static func tracking( ++ _ regions: DatabaseRegionConvertible..., ++ fetch: @escaping (Database) throws -> Value) ++ -> ValueObservation> ++ ++ static func tracking( ++ _ regions: DatabaseRegionConvertible..., ++ fetchDistinct: @escaping (Database) throws -> Value) ++ -> ValueObservation> ++ where Value: Equatable ++ ++ static func trackingCount(_ request: Request) ++ -> ValueObservation> ++ static func trackingAll(_ request: Request) ++ -> ValueObservation> ++ static func trackingOne(_ request: Request) ++ -> ValueObservation> ++} +``` + + ## 3.4.0 Released October 8, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v3.3.1...v3.4.0) @@ -74,7 +195,7 @@ This release comes with **Association Aggregates**. They let you compute values +} +extension SQLSpecificExpressible { -+ public func aliased(_ key: CodingKey) -> SQLSelectable ++ func aliased(_ key: CodingKey) -> SQLSelectable +} ``` diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0b878a9ad..b7f3ab8b6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -75,7 +75,6 @@ The ideas, in alphabetical order: - [CloudKit] - [Concurrency] - [Custom FTS5 Auxiliary Functions] -- [Database Observation] - [Date and Time Functions] - [Decode NSDecimalNumber from Text Columns] - [Documentation] @@ -86,6 +85,7 @@ The ideas, in alphabetical order: - [JSON] - [Linux] - [More SQL Generation] +- [Reactive Database Observation] - [Records: Splitting Database Encoding from Ability to Write in the Database] - [SQL Console in the Debugger] - [SQLCipher in a Shared App Container] @@ -160,24 +160,6 @@ Applications can define their own [custom FTS5 auxiliary functions](https://www. See issue [#421](https://github.com/groue/GRDB.swift/issues/421) for more information. -### Database Observation - -:muscle: Hard - -[Database Observation](README#database-changes-observation) is currently available in three flavors: - -- The [TransactionObserver](README.md#transactionobserver-protocol) protocol: versatile, but low-level and challenging in terms of concurrency, especially when used in conjunction with database pools. - -- [FetchedRecordsController]: high-level and easier to use. - -- [RxGRDB]: high-level and easier to use, depends on [RxSwift](https://github.com/ReactiveX/RxSwift). - -Suggested contributions are: - -- Enhancements to FetchedRecordsController (see below). -- More choices of reactive engines. - - ### Date and Time Functions :baby: Starter Task @@ -257,7 +239,7 @@ let stringRequest = Player.select(Column("name"), as: String.self) let rowRequest = SQLRequest("SELECT ...") ``` -This limitation does not apply to [RxGRDB], the reactive sibling of FetchedRecordsController. It would be nice if FetchedRecordsController would become just as versatile. +This limitation does not apply to [ValueObservation] and [RxGRDB]. It would be nice if FetchedRecordsController would become just as versatile. ### FetchedRecordsController Support for Sections @@ -312,6 +294,15 @@ There are several SQLite features that GRDB could natively support: - [More ideas](https://www.sqlite.org/lang.html) +### Reactive Database Observation + +:baby: Starter Task + +We already have the [RxGRDB] companion library, which offers [RxSwift](https://github.com/ReactiveX/RxSwift) bindings. + +We need more choices of reactive engines. + + ### Records: Splitting Database Encoding from Ability to Write in the Database :baby: Starter Task :pencil: Documentation @@ -416,3 +407,4 @@ Features that blur this focus are non-goals: [PersistableRecord]: README.md#persistablerecord-protocol [Record Comparison]: README.md#record-comparison [Requesting Associated Records]: Documentation/AssociationsBasics.md#requesting-associated-records +[ValueObservation]: README.md#valueobservation diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift index 517ff1842..bd0258d82 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift @@ -1,22 +1,23 @@ import UIKit import GRDB +/// PlayersViewController displays the list of players. class PlayersViewController: UITableViewController { - enum PlayerOrdering { + private enum PlayerOrdering { case byName case byScore } - var playersController: FetchedRecordsController! - - var playerOrdering: PlayerOrdering = .byScore { + @IBOutlet private weak var newPlayerButtonItem: UIBarButtonItem! + private var playersController: FetchedRecordsController! + private var playerCountObserver: TransactionObserver? + private var playerOrdering: PlayerOrdering = .byScore { didSet { try! playersController.setRequest(playersRequest) - configureNavigationItem() + configureOrderingBarButtonItem() } } - - var playersRequest: QueryInterfaceRequest { + private var playersRequest: QueryInterfaceRequest { switch playerOrdering { case .byName: return Player.orderedByName() @@ -25,57 +26,59 @@ class PlayersViewController: UITableViewController { } } - @IBOutlet weak var newPlayerButtonItem: UIBarButtonItem! - override func viewDidLoad() { super.viewDidLoad() - configureTableView() configureToolbar() - configureNavigationItem() + configureOrderingBarButtonItem() + configureTitle() + configureTableView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.isToolbarHidden = false } -} - - -// MARK: - Navigation - -extension PlayersViewController { - override func prepare(for segue: UIStoryboardSegue, sender: Any?) { - if segue.identifier == "Edit" { - let player = playersController.record(at: tableView.indexPathForSelectedRow!) - let controller = segue.destination as! PlayerEditionViewController - controller.title = player.name - controller.player = player - controller.presentation = .push - } - else if segue.identifier == "New" { - setEditing(false, animated: true) - let navigationController = segue.destination as! UINavigationController - let controller = navigationController.viewControllers.first as! PlayerEditionViewController - controller.title = "New Player" - controller.player = Player(id: nil, name: "", score: 0) - controller.presentation = .modal + private func configureToolbar() { + toolbarItems = [ + UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deletePlayers)), + UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), + UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refresh)), + UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), + UIBarButtonItem(title: "💣", style: .plain, target: self, action: #selector(stressTest)), + ] + } + + private func configureOrderingBarButtonItem() { + navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem] + + switch playerOrdering { + case .byScore: + navigationItem.rightBarButtonItem = UIBarButtonItem( + title: "Score ⬇︎", + style: .plain, + target: self, action: #selector(sortByName)) + case .byName: + navigationItem.rightBarButtonItem = UIBarButtonItem( + title: "Name ⬆︎", + style: .plain, + target: self, action: #selector(sortByScore)) } } - @IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) { - // Player creation cancelled + private func configureTitle() { + // Track changes in the number of players + playerCountObserver = try! ValueObservation + .trackingCount(playersRequest) + .start(in: dbQueue) { [unowned self] count in + switch count { + case 0: self.navigationItem.title = "No Player" + case 1: self.navigationItem.title = "1 Player" + default: self.navigationItem.title = "\(count) Players" + } + } } - @IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) { - // Player creation committed - } -} - - -// MARK: - UITableViewDataSource - -extension PlayersViewController { private func configureTableView() { // Track changes in the database players playersController = try! FetchedRecordsController(dbQueue, request: playersRequest) @@ -118,7 +121,44 @@ extension PlayersViewController { // Initial fetch try! playersController.performFetch() } +} + + +// MARK: - Navigation + +extension PlayersViewController { + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if segue.identifier == "Edit" { + let player = playersController.record(at: tableView.indexPathForSelectedRow!) + let controller = segue.destination as! PlayerEditionViewController + controller.title = player.name + controller.player = player + controller.presentation = .push + } + else if segue.identifier == "New" { + setEditing(false, animated: true) + let navigationController = segue.destination as! UINavigationController + let controller = navigationController.viewControllers.first as! PlayerEditionViewController + controller.title = "New Player" + controller.player = Player(id: nil, name: "", score: 0) + controller.presentation = .modal + } + } + + @IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) { + // Player creation cancelled + } + + @IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) { + // Player creation committed + } +} + + +// MARK: - UITableViewDataSource + +extension PlayersViewController { override func numberOfSections(in tableView: UITableView) -> Int { return playersController.sections.count } @@ -156,33 +196,6 @@ extension PlayersViewController { // MARK: - Actions extension PlayersViewController { - private func configureNavigationItem() { - navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem] - - switch playerOrdering { - case .byScore: - navigationItem.rightBarButtonItem = UIBarButtonItem( - title: "Score ⬇︎", - style: .plain, - target: self, action: #selector(sortByName)) - case .byName: - navigationItem.rightBarButtonItem = UIBarButtonItem( - title: "Name ⬆︎", - style: .plain, - target: self, action: #selector(sortByScore)) - } - } - - private func configureToolbar() { - toolbarItems = [ - UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deletePlayers)), - UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), - UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refresh)), - UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), - UIBarButtonItem(title: "💣", style: .plain, target: self, action: #selector(stressTest)), - ] - } - @IBAction func sortByName() { setEditing(false, animated: true) playerOrdering = .byName diff --git a/DemoApps/GRDBDemoiOS/README.md b/DemoApps/GRDBDemoiOS/README.md index f8e18ffb4..9c0eb9562 100644 --- a/DemoApps/GRDBDemoiOS/README.md +++ b/DemoApps/GRDBDemoiOS/README.md @@ -25,7 +25,7 @@ Demo Application - [PlayersViewController.swift](GRDBDemoiOS/PlayersViewController.swift) - `PlayersViewController` displays a list of players, and animates its table view according to database changes with [FetchedRecordsController](../../README.md#fetchedrecordscontroller). + `PlayersViewController` displays a list of players. It keeps its title up-to-date with [ValueObservation](../../README.md#valueobservation), and animates its table view according to database changes with [FetchedRecordsController](../../README.md#fetchedrecordscontroller). - [PlayerEditionViewController.swift](GRDBDemoiOS/PlayerEditionViewController.swift) diff --git a/Documentation/Images/GRDBDemoScreenshot.png b/Documentation/Images/GRDBDemoScreenshot.png index 8ca1c391f..f8f3a7bac 100644 Binary files a/Documentation/Images/GRDBDemoScreenshot.png and b/Documentation/Images/GRDBDemoScreenshot.png differ diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 62c452314..b42142903 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -116,6 +116,27 @@ 5634B10A1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */; }; 5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; 5636E9BF1D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; + 563B06AB217EF0CC00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */; }; + 563B06AC217EF0CC00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */; }; + 563B06AD217EF0CC00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */; }; + 563B06BD2185CCD300B38F35 /* ValueObservationReducerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06BC2185CCD300B38F35 /* ValueObservationReducerTests.swift */; }; + 563B06BE2185CCD300B38F35 /* ValueObservationReducerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06BC2185CCD300B38F35 /* ValueObservationReducerTests.swift */; }; + 563B06C32185D29F00B38F35 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C02185D29F00B38F35 /* ValueObservationExtentTests.swift */; }; + 563B06C42185D29F00B38F35 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C02185D29F00B38F35 /* ValueObservationExtentTests.swift */; }; + 563B06C52185D29F00B38F35 /* ValueObservationSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C12185D29F00B38F35 /* ValueObservationSchedulingTests.swift */; }; + 563B06C62185D29F00B38F35 /* ValueObservationSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C12185D29F00B38F35 /* ValueObservationSchedulingTests.swift */; }; + 563B06C72185D29F00B38F35 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */; }; + 563B06C82185D29F00B38F35 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */; }; + 563B06CA2185D2E500B38F35 /* ValueObservationFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C92185D2E500B38F35 /* ValueObservationFetchTests.swift */; }; + 563B06CB2185D2E500B38F35 /* ValueObservationFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C92185D2E500B38F35 /* ValueObservationFetchTests.swift */; }; + 563B06F721861D8400B38F35 /* ValueObservationCountTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */; }; + 563B06F821861D8400B38F35 /* ValueObservationCountTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */; }; + 563B0705218627F800B38F35 /* ValueObservationRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B0704218627F700B38F35 /* ValueObservationRowTests.swift */; }; + 563B0706218627F800B38F35 /* ValueObservationRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B0704218627F700B38F35 /* ValueObservationRowTests.swift */; }; + 563B071521862C4700B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */; }; + 563B071621862C4700B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */; }; + 563B071821862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; + 563B071921862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; 563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF414215F87EB007DAACD /* OrderedDictionary.swift */; }; 563EF416215F87EB007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF414215F87EB007DAACD /* OrderedDictionary.swift */; }; 563EF417215F87EB007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF414215F87EB007DAACD /* OrderedDictionary.swift */; }; @@ -889,6 +910,16 @@ 563363F81C960711000BE133 /* PerformanceRealmTests.realm */ = {isa = PBXFileReference; lastKnownFileType = file; path = PerformanceRealmTests.realm; 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 = ""; }; + 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservation.swift; sourceTree = ""; }; + 563B06BC2185CCD300B38F35 /* ValueObservationReducerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationReducerTests.swift; sourceTree = ""; }; + 563B06C02185D29F00B38F35 /* ValueObservationExtentTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationExtentTests.swift; sourceTree = ""; }; + 563B06C12185D29F00B38F35 /* ValueObservationSchedulingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationSchedulingTests.swift; sourceTree = ""; }; + 563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationReadonlyTests.swift; sourceTree = ""; }; + 563B06C92185D2E500B38F35 /* ValueObservationFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationFetchTests.swift; sourceTree = ""; }; + 563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCountTests.swift; sourceTree = ""; }; + 563B0704218627F700B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = ""; }; + 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = ""; }; + 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = ""; }; 563EF414215F87EB007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = ""; }; 563EF42C2161180D007DAACD /* AssociationAggregate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationAggregate.swift; sourceTree = ""; }; 563EF43E216131D1007DAACD /* AssociationAggregateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationAggregateTests.swift; sourceTree = ""; }; @@ -1450,6 +1481,22 @@ name = DatabaseQueue; sourceTree = ""; }; + 563B06BF2185CD1700B38F35 /* ValueObservation */ = { + isa = PBXGroup; + children = ( + 563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */, + 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */, + 563B06C02185D29F00B38F35 /* ValueObservationExtentTests.swift */, + 563B06C92185D2E500B38F35 /* ValueObservationFetchTests.swift */, + 563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */, + 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */, + 563B06BC2185CCD300B38F35 /* ValueObservationReducerTests.swift */, + 563B0704218627F700B38F35 /* ValueObservationRowTests.swift */, + 563B06C12185D29F00B38F35 /* ValueObservationSchedulingTests.swift */, + ); + name = ValueObservation; + sourceTree = ""; + }; 5653EABF20944B1300F46237 /* Association */ = { isa = PBXGroup; children = ( @@ -1621,6 +1668,7 @@ 56A238201B9C74A90082EB20 /* Statement */, 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */, 5607EFD11BB8253300605DE3 /* TransactionObserver */, + 563B06BF2185CD1700B38F35 /* ValueObservation */, ); name = Core; sourceTree = ""; @@ -1714,6 +1762,7 @@ 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, 5605F1471C672E4000235C62 /* Support */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, + 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */, ); path = Core; sourceTree = ""; @@ -2372,6 +2421,7 @@ 56CEB5671EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 5653EB272094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 565490B91D5AE236005622CB /* DatabasePool.swift in Sources */, + 563B06AD217EF0CC00B38F35 /* ValueObservation.swift in Sources */, 5674A6EF1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 565490D81D5AE252005622CB /* DatabaseMigrator.swift in Sources */, 56CEB5601EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, @@ -2562,6 +2612,7 @@ 5605F1661C672E4000235C62 /* NSNull.swift in Sources */, 569EF0E3200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */, 56A238841B9C75030082EB20 /* DatabaseQueue.swift in Sources */, + 563B06AC217EF0CC00B38F35 /* ValueObservation.swift in Sources */, 5698AC7B1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */, 56D1215D1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, @@ -2596,6 +2647,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 563B06C82185D29F00B38F35 /* ValueObservationReadonlyTests.swift in Sources */, 6340BF841E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 56300B861C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift in Sources */, 56F26C1C1CEE3F32007969C4 /* RowAdapterTests.swift in Sources */, @@ -2623,12 +2675,14 @@ 56A2385A1B9C74A90082EB20 /* RecordPrimaryKeySingleTests.swift in Sources */, 562756471E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 569531381C919DF700CF1A2B /* DatabasePoolFunctionTests.swift in Sources */, + 563B06F821861D8400B38F35 /* ValueObservationCountTests.swift in Sources */, 56A238481B9C74A90082EB20 /* RowCopiedFromStatementTests.swift in Sources */, 56EA63C6209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */, 5674A71A1F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 5698AC071D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, 56C3F7561CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, 56B021CD1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, + 563B0706218627F800B38F35 /* ValueObservationRowTests.swift in Sources */, 569531271C9087B700CF1A2B /* DatabaseQueueSchemaCacheTests.swift in Sources */, 56B14E831D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 562393341DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, @@ -2656,11 +2710,13 @@ 567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, 5657AB621D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, 5657AB6A1D108BA9006283EF /* FoundationURLTests.swift in Sources */, + 563B06C42185D29F00B38F35 /* ValueObservationExtentTests.swift in Sources */, 564FCE5F20F7E11B00202B90 /* DatabaseValueConversionErrorTests.swift in Sources */, 5653EADF20944B4F00F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 56F3E74D1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 56EB0AB31BCD787300A3DC55 /* DataMemoryTests.swift in Sources */, 56B6EF57208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */, + 563B071621862C4700B38F35 /* ValueObservationRecordTests.swift in Sources */, 56176C7F1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */, 56741EAC1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 5672DE5C1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, @@ -2671,6 +2727,7 @@ 564E73E0203D50B9000C443C /* JoinSupportTests.swift in Sources */, 5674A7121F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, 5657AB521D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */, + 563B071921862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */, 5665F85E203EE6030084C6C0 /* ColumnInfoTests.swift in Sources */, 56A238441B9C74A90082EB20 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, 560A37AC1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift in Sources */, @@ -2680,6 +2737,7 @@ 565D5D721BBC694D00DC9BD4 /* Row+FoundationTests.swift in Sources */, 5623936D1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, 567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, + 563B06CB2185D2E500B38F35 /* ValueObservationFetchTests.swift in Sources */, 5623935B1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 5674A72D1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 566A84412041914000E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, @@ -2735,6 +2793,7 @@ 5623931C1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */, 562393641DEE06D300A6B01F /* CursorTests.swift in Sources */, + 563B06C62185D29F00B38F35 /* ValueObservationSchedulingTests.swift in Sources */, 5657AB5A1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 56300B6C1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 5674A7231F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, @@ -2748,6 +2807,7 @@ 56A2383A1B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift in Sources */, 56A5E40A1BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift in Sources */, 5653EAF520944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */, + 563B06BE2185CCD300B38F35 /* ValueObservationReducerTests.swift in Sources */, 56FF455A1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, 56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */, 5605F1881C69111300235C62 /* DatabaseRegionTests.swift in Sources */, @@ -2763,6 +2823,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 563B06C72185D29F00B38F35 /* ValueObservationReadonlyTests.swift in Sources */, 6340BF801E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 56D496771D81309E008276D7 /* RecordInitializersTests.swift in Sources */, 56D496651D813076008276D7 /* DatabaseMigratorTests.swift in Sources */, @@ -2790,12 +2851,14 @@ 56D4968C1D81316E008276D7 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, 56D496981D81317B008276D7 /* DatabaseValueTests.swift in Sources */, 56D4966B1D81309E008276D7 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 563B06F721861D8400B38F35 /* ValueObservationCountTests.swift in Sources */, 56D4965B1D81304E008276D7 /* FoundationNSDecimalNumberTests.swift in Sources */, 562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 56EA63C5209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */, 56D496BF1D8135D4008276D7 /* TableDefinitionTests.swift in Sources */, 5674A7171F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 56D496801D813131008276D7 /* StatementColumnConvertibleFetchTests.swift in Sources */, + 563B0705218627F800B38F35 /* ValueObservationRowTests.swift in Sources */, 56D4966E1D81309E008276D7 /* RecordPrimaryKeyMultipleTests.swift in Sources */, 56D496891D81316E008276D7 /* DatabaseValueConvertibleFetchTests.swift in Sources */, 56D4967C1D8130DB008276D7 /* CGFloatTests.swift in Sources */, @@ -2823,11 +2886,13 @@ 56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 56D496601D81304E008276D7 /* FoundationNSUUIDTests.swift in Sources */, 567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, + 563B06C32185D29F00B38F35 /* ValueObservationExtentTests.swift in Sources */, 56D4968D1D81316E008276D7 /* DatabaseFunctionTests.swift in Sources */, 564FCE5E20F7E11B00202B90 /* DatabaseValueConversionErrorTests.swift in Sources */, 5653EADE20944B4F00F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 56D496661D813086008276D7 /* QueryInterfaceRequestTests.swift in Sources */, 56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, + 563B071521862C4700B38F35 /* ValueObservationRecordTests.swift in Sources */, 56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */, 5698ACD71DA925420056AF8C /* RowTestCase.swift in Sources */, 56176C7D1EACCD2D000F3F2B /* EncryptionTests.swift in Sources */, @@ -2838,6 +2903,7 @@ 56D496581D81304E008276D7 /* FoundationDateTests.swift in Sources */, 562205F31E420E47005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 564E73DF203D50B9000C443C /* JoinSupportTests.swift in Sources */, + 563B071821862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */, 5674A70F1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, 56D496711D81309E008276D7 /* RecordPrimaryKeySingleTests.swift in Sources */, 5665F85D203EE6030084C6C0 /* ColumnInfoTests.swift in Sources */, @@ -2847,6 +2913,7 @@ 5653EAF220944B4F00F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 56D496851D813147008276D7 /* StatementArgumentsTests.swift in Sources */, 56D496B81D813465008276D7 /* DataMemoryTests.swift in Sources */, + 563B06CA2185D2E500B38F35 /* ValueObservationFetchTests.swift in Sources */, 56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */, 56D496961D81317B008276D7 /* PersistableRecordTests.swift in Sources */, 5698AC9E1DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, @@ -2902,6 +2969,7 @@ 56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */, 56D496951D81317B008276D7 /* MutablePersistableRecordTests.swift in Sources */, 5653EAD620944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */, + 563B06C52185D29F00B38F35 /* ValueObservationSchedulingTests.swift in Sources */, 5698AC801DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, 56D496821D813131008276D7 /* TransactionObserverTests.swift in Sources */, 56D496941D81317B008276D7 /* SchedulingWatchdogTests.swift in Sources */, @@ -2915,6 +2983,7 @@ 5653EAD820944B4F00F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 562205F11E420E47005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */, 5653EAF420944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */, + 563B06BD2185CCD300B38F35 /* ValueObservationReducerTests.swift in Sources */, 56D496971D81317B008276D7 /* DatabaseReaderTests.swift in Sources */, 56D496911D81316E008276D7 /* RowFromStatementTests.swift in Sources */, 56071A411DB54ED000CA6E47 /* FetchedRecordsControllerTests.swift in Sources */, @@ -2939,6 +3008,7 @@ 563EF44A2161F179007DAACD /* Inflections.swift in Sources */, 566B91091FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91231FA4CF810012D5B0 /* Database+Schema.swift in Sources */, + 563B06AB217EF0CC00B38F35 /* ValueObservation.swift in Sources */, 56CEB5111EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index eb940bae1..2da9e72cc 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -575,13 +575,7 @@ extension DatabasePool : DatabaseReader { return Future { // Block the future until results are fetched _ = futureSemaphore.wait(timeout: .distantFuture) - - switch futureResult! { - case .failure(let error): - throw error - case .success(let result): - return result - } + return try futureResult!.unwrap() } } diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 06148a0ba..0814bb11c 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -225,7 +225,8 @@ extension DatabaseQueue { public func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future { // DatabaseQueue can't perform parallel reads. - let result = Result { + // Perform a blocking read instead. + return Future(Result { // Check that we're on the writer queue... try writer.execute { db in // ... and that no transaction is opened. @@ -234,10 +235,7 @@ extension DatabaseQueue { try block(db) } } - } - return Future { - try result.unwrap() - } + }) } // MARK: - Writing in Database @@ -387,4 +385,3 @@ extension DatabaseQueue { writer.sync { $0.remove(collation: collation) } } } - diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 9e17ef96b..ee4ddd702 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -149,6 +149,27 @@ public protocol DatabaseReader : class { /// Remove a collation. func remove(collation: DatabaseCollation) + + // MARK: - Value Observation + + /// Starts a value observation. + /// + /// You should use the `ValueObservation.start(in:onError:onChange:)` + /// method instead. + /// + /// - parameter observation: the stared observation + /// - parameter onError: a closure that is provided by eventual errors that happen + /// during observation + /// - parameter onChange: a closure that is provided fresh values + /// - returns: a TransactionObserver + func add( + observation: ValueObservation, + onError: ((Error) -> Void)?, + onChange: @escaping (Reducer.Value) -> Void) + throws -> TransactionObserver + + /// Remove a transaction observer. + func remove(transactionObserver: TransactionObserver) } extension DatabaseReader { @@ -228,4 +249,21 @@ public final class AnyDatabaseReader : DatabaseReader { public func remove(collation: DatabaseCollation) { base.remove(collation: collation) } + + // MARK: - Value Observation + + /// :nodoc: + public func add( + observation: ValueObservation, + onError: ((Error) -> Void)?, + onChange: @escaping (Reducer.Value) -> Void) + throws -> TransactionObserver + { + return try base.add(observation: observation, onError: onError, onChange: onChange) + } + + /// :nodoc: + public func remove(transactionObserver: TransactionObserver) { + base.remove(transactionObserver: transactionObserver) + } } diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 490450ebb..613796e9d 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -296,3 +296,37 @@ private struct TableRegion: Equatable { return TableRegion(columns: columnsUnion, rowIds: rowIdsUnion) } } + +// MARK: - DatabaseRegionConvertible + +public protocol DatabaseRegionConvertible { + /// Returns a database region. + /// + /// - parameter db: A database connection. + func databaseRegion(_ db: Database) throws -> DatabaseRegion +} + +extension DatabaseRegion: DatabaseRegionConvertible { + /// :nodoc: + public func databaseRegion(_ db: Database) throws -> DatabaseRegion { + return self + } +} + +/// A type-erased DatabaseRegionConvertible +public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible { + let _region: (Database) throws -> DatabaseRegion + + public init(_ region: @escaping (Database) throws -> DatabaseRegion) { + _region = region + } + + public init(_ region: DatabaseRegionConvertible) { + _region = { try region.databaseRegion($0) } + } + + /// :nodoc: + public func databaseRegion(_ db: Database) throws -> DatabaseRegion { + return try _region(db) + } +} diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 423822fcf..30f60bef2 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -1,3 +1,5 @@ +import Dispatch + /// A DatabaseSnapshot sees an unchanging database content, as it existed at the /// moment it was created. /// @@ -81,45 +83,77 @@ extension DatabaseSnapshot { // MARK: - Functions - /// Add or redefine an SQL function. - /// - /// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in - /// guard let int = Int.fromDatabaseValue(dbValues[0]) else { - /// return nil - /// } - /// return int + 1 - /// } - /// snapshot.add(function: fn) - /// try snapshot.read { db in - /// try Int.fetchOne(db, "SELECT succ(1)") // 2 - /// } public func add(function: DatabaseFunction) { serializedDatabase.sync { $0.add(function: function) } } - /// Remove an SQL function. public func remove(function: DatabaseFunction) { serializedDatabase.sync { $0.remove(function: function) } } // MARK: - Collations - /// Add or redefine a collation. - /// - /// let collation = DatabaseCollation("localized_standard") { (string1, string2) in - /// return (string1 as NSString).localizedStandardCompare(string2) - /// } - /// snapshot.add(collation: collation) - /// let files = try snapshot.read { db in - /// try File.fetchAll(db, "SELECT * FROM file ORDER BY name COLLATE localized_standard") - /// } public func add(collation: DatabaseCollation) { serializedDatabase.sync { $0.add(collation: collation) } } - /// Remove a collation. public func remove(collation: DatabaseCollation) { serializedDatabase.sync { $0.remove(collation: collation) } } + + // MARK: - Value Observation + + public func add( + observation: ValueObservation, + onError: ((Error) -> Void)?, + onChange: @escaping (Reducer.Value) -> Void) + throws -> TransactionObserver + { + // Deal with initial value + switch observation.scheduling { + case .mainQueue: + var reducer = observation.reducer + if let value = try reducer.value(unsafeReentrantRead(reducer.fetch)) { + if DispatchQueue.isMain { + onChange(value) + } else { + DispatchQueue.main.async { + onChange(value) + } + } + } + case let .onQueue(queue, startImmediately: startImmediately): + if startImmediately { + var reducer = observation.reducer + if let value = try reducer.value(unsafeReentrantRead(reducer.fetch)) { + queue.async { + onChange(value) + } + } + } + case let .unsafe(startImmediately: startImmediately): + if startImmediately { + var reducer = observation.reducer + if let value = try reducer.value(unsafeReentrantRead(reducer.fetch)) { + onChange(value) + } + } + } + + // Return a dummy observer, because snapshots never change + return SnapshotValueObserver() + } + + public func remove(transactionObserver: TransactionObserver) { + // Can't remove an observer which could not be added :-) + } } +/// An observer that does nothing, support for +/// `DatabaseSnapshot.add(observation:onError:onChange:)`. +private class SnapshotValueObserver: TransactionObserver { + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { return false } + func databaseDidChange(with event: DatabaseEvent) { } + func databaseDidCommit(_ db: Database) { } + func databaseDidRollback(_ db: Database) { } +} diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index c1b77e010..b8a4318ba 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -137,7 +137,6 @@ extension DatabaseWriter { writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) } } - /// Remove a transaction observer. public func remove(transactionObserver: TransactionObserver) { writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) } } @@ -187,37 +186,6 @@ extension DatabaseWriter { #endif } - // MARK: - Reading from Database - - /// Default implementation, based on the deprecated readFromCurrentState. - /// - /// :nodoc: - public func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future { - let semaphore = DispatchSemaphore(value: 0) - var result: Result? = nil - - do { - try readFromCurrentState { db in - result = Result { try block(db) } - semaphore.signal() - } - } catch { - result = .failure(error) - semaphore.signal() - } - - return Future { - _ = semaphore.wait(timeout: .distantFuture) - - switch result! { - case .failure(let error): - throw error - case .success(let result): - return result - } - } - } - // MARK: - Claiming Disk Space /// Rebuilds the database file, repacking it into a minimal amount of @@ -227,6 +195,200 @@ extension DatabaseWriter { public func vacuum() throws { try writeWithoutTransaction { try $0.execute("VACUUM") } } + + // MARK: - Value Observation + + public func add( + observation: ValueObservation, + onError: ((Error) -> Void)?, + onChange: @escaping (Reducer.Value) -> Void) + throws -> TransactionObserver + { + let calledOnMainQueue = DispatchQueue.isMain + var startValue: Reducer.Value? = nil + defer { + if let startValue = startValue { + onChange(startValue) + } + } + + // Use unsafeReentrantWrite so that observation can start from any + // dispatch queue. + return try unsafeReentrantWrite { db in + // 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.fetch(db)) { + if calledOnMainQueue { + startValue = value + } else { + DispatchQueue.main.async { onChange(value) } + } + } + case let .onQueue(queue, startImmediately: startImmediately): + if startImmediately { + if let value = try reducer.value(observation.fetch(db)) { + queue.async { onChange(value) } + } + } + case let .unsafe(startImmediately: startImmediately): + if startImmediately { + startValue = try reducer.value(observation.fetch(db)) + } + } + + // Start observing the database + let valueObserver = try ValueObserver( + region: observation.observedRegion(db), + reducer: reducer, + fetch: observation.fetchAfterChange(in: self), + notificationQueue: observation.notificationQueue, + onError: onError, + onChange: onChange) + db.add(transactionObserver: valueObserver, extent: observation.extent) + + return valueObserver + } + } +} + +extension ValueObservation where Reducer: ValueReducer { + /// Helper method for DatabaseWriter.add(observation:onError:onChange:) + fileprivate func fetch(_ db: Database) throws -> Reducer.Fetched { + if requiresWriteAccess { + var fetchedValue: Reducer.Fetched! + try db.inSavepoint { + fetchedValue = try reducer.fetch(db) + return .commit + } + return fetchedValue + } else { + return try db.readOnly { try reducer.fetch(db) } + } + } + + /// 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 + // depends on the requiresWriteAccess flag: + if requiresWriteAccess { + // Synchronous fetch + return { (db, reducer) in + Future(Result { + var fetchedValue: Reducer.Fetched! + try db.inTransaction { + fetchedValue = try reducer.fetch(db) + return .commit + } + return fetchedValue + }) + } + } else { + // Concurrent fetch + return { [unowned writer] (_, reducer) in + writer.concurrentRead(reducer.fetch) + } + } + } +} + + +/// 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. @@ -238,6 +400,10 @@ public class Future { _wait = wait } + init(_ result: Result) { + _wait = { try result.unwrap() } + } + /// Blocks the current thread until the value is available, and returns it. /// /// It is a programmer error to call this method several times. diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index cf8995872..ede50ec8e 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -8,7 +8,7 @@ /// try request.fetchCursor(db) // Cursor of Player /// try request.fetchAll(db) // [Player] /// try request.fetchOne(db) // Player? -public protocol FetchRequest { +public protocol FetchRequest: DatabaseRegionConvertible { /// The type that tells how fetched database rows should be interpreted. associatedtype RowDecoder @@ -30,11 +30,6 @@ public protocol FetchRequest { /// /// - parameter db: A database connection. func fetchCount(_ db: Database) throws -> Int - - /// Returns the database region that the request looks into. - /// - /// - parameter db: A database connection. - func databaseRegion(_ db: Database) throws -> DatabaseRegion } extension FetchRequest { diff --git a/GRDB/Core/ValueObservation.swift b/GRDB/Core/ValueObservation.swift new file mode 100644 index 000000000..914b55351 --- /dev/null +++ b/GRDB/Core/ValueObservation.swift @@ -0,0 +1,922 @@ +// +// 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 + +/// 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 + + public 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?? + + public 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]? + + /// TODO + public 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?? + + /// TODO + public 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]? + + /// TODO + public 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 + + /// TODO + public 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]? + + /// TODO + public 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/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index c7f768fe5..f6541248d 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -180,6 +180,44 @@ 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 */; }; + 563B06E42185E07300B38F35 /* ValueObservationExtentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06DC2185E07100B38F35 /* ValueObservationExtentTests.swift */; }; + 563B06E52185E07300B38F35 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06DD2185E07200B38F35 /* ValueObservationReadonlyTests.swift */; }; + 563B06E62185E07300B38F35 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06DD2185E07200B38F35 /* ValueObservationReadonlyTests.swift */; }; + 563B06E72185E07300B38F35 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06DD2185E07200B38F35 /* ValueObservationReadonlyTests.swift */; }; + 563B06E82185E07300B38F35 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06DD2185E07200B38F35 /* ValueObservationReadonlyTests.swift */; }; + 563B06E92185E07300B38F35 /* ValueObservationFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06DE2185E07200B38F35 /* ValueObservationFetchTests.swift */; }; + 563B06EA2185E07300B38F35 /* ValueObservationFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06DE2185E07200B38F35 /* ValueObservationFetchTests.swift */; }; + 563B06EB2185E07300B38F35 /* ValueObservationFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06DE2185E07200B38F35 /* ValueObservationFetchTests.swift */; }; + 563B06EC2185E07300B38F35 /* ValueObservationFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06DE2185E07200B38F35 /* ValueObservationFetchTests.swift */; }; + 563B06ED2185E07300B38F35 /* ValueObservationReducerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06DF2185E07200B38F35 /* ValueObservationReducerTests.swift */; }; + 563B06EE2185E07300B38F35 /* ValueObservationReducerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06DF2185E07200B38F35 /* ValueObservationReducerTests.swift */; }; + 563B06EF2185E07300B38F35 /* ValueObservationReducerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06DF2185E07200B38F35 /* ValueObservationReducerTests.swift */; }; + 563B06F02185E07300B38F35 /* ValueObservationReducerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06DF2185E07200B38F35 /* ValueObservationReducerTests.swift */; }; + 563B06F12185E07300B38F35 /* ValueObservationSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06E02185E07200B38F35 /* ValueObservationSchedulingTests.swift */; }; + 563B06F22185E07300B38F35 /* ValueObservationSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06E02185E07200B38F35 /* ValueObservationSchedulingTests.swift */; }; + 563B06F32185E07300B38F35 /* ValueObservationSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06E02185E07200B38F35 /* ValueObservationSchedulingTests.swift */; }; + 563B06F42185E07300B38F35 /* ValueObservationSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06E02185E07200B38F35 /* ValueObservationSchedulingTests.swift */; }; + 563B06FA21861D8B00B38F35 /* ValueObservationCountTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06F921861D8B00B38F35 /* ValueObservationCountTests.swift */; }; + 563B06FB21861D8B00B38F35 /* ValueObservationCountTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06F921861D8B00B38F35 /* ValueObservationCountTests.swift */; }; + 563B06FC21861D8B00B38F35 /* ValueObservationCountTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06F921861D8B00B38F35 /* ValueObservationCountTests.swift */; }; + 563B06FD21861D8B00B38F35 /* ValueObservationCountTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06F921861D8B00B38F35 /* ValueObservationCountTests.swift */; }; + 563B07082186280600B38F35 /* ValueObservationRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B07072186280500B38F35 /* ValueObservationRowTests.swift */; }; + 563B07092186280600B38F35 /* ValueObservationRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B07072186280500B38F35 /* ValueObservationRowTests.swift */; }; + 563B070A2186280600B38F35 /* ValueObservationRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B07072186280500B38F35 /* ValueObservationRowTests.swift */; }; + 563B070B2186280600B38F35 /* ValueObservationRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B07072186280500B38F35 /* ValueObservationRowTests.swift */; }; + 563B070D21862C3600B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B070C21862C3500B38F35 /* ValueObservationRecordTests.swift */; }; + 563B070E21862C3600B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B070C21862C3500B38F35 /* ValueObservationRecordTests.swift */; }; + 563B070F21862C3600B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B070C21862C3500B38F35 /* ValueObservationRecordTests.swift */; }; + 563B071021862C3600B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B070C21862C3500B38F35 /* ValueObservationRecordTests.swift */; }; + 563B071E21862F5D00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071D21862F5D00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; + 563B071F21862F5D00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071D21862F5D00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; + 563B072021862F5D00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071D21862F5D00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; + 563B072121862F5D00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071D21862F5D00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; 563EF424215F8A88007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF422215F8A88007DAACD /* OrderedDictionary.swift */; }; 563EF425215F8A88007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF422215F8A88007DAACD /* OrderedDictionary.swift */; }; 563EF43C2161183E007DAACD /* AssociationAggregate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF43A2161183E007DAACD /* AssociationAggregate.swift */; }; @@ -988,6 +1026,16 @@ 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 = ""; }; + 563B06DF2185E07200B38F35 /* ValueObservationReducerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationReducerTests.swift; sourceTree = ""; }; + 563B06E02185E07200B38F35 /* ValueObservationSchedulingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationSchedulingTests.swift; sourceTree = ""; }; + 563B06F921861D8B00B38F35 /* ValueObservationCountTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCountTests.swift; sourceTree = ""; }; + 563B07072186280500B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = ""; }; + 563B070C21862C3500B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = ""; }; + 563B071D21862F5D00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = ""; }; 563EF422215F8A88007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = ""; }; 563EF43A2161183E007DAACD /* AssociationAggregate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationAggregate.swift; sourceTree = ""; }; 563EF44421613212007DAACD /* AssociationAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationAggregateTests.swift; sourceTree = ""; }; @@ -1519,6 +1567,22 @@ name = DatabaseQueue; sourceTree = ""; }; + 563B06F52185E07C00B38F35 /* ValueObservation */ = { + isa = PBXGroup; + children = ( + 563B06F921861D8B00B38F35 /* ValueObservationCountTests.swift */, + 563B071D21862F5D00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */, + 563B06DC2185E07100B38F35 /* ValueObservationExtentTests.swift */, + 563B06DE2185E07200B38F35 /* ValueObservationFetchTests.swift */, + 563B06DD2185E07200B38F35 /* ValueObservationReadonlyTests.swift */, + 563B070C21862C3500B38F35 /* ValueObservationRecordTests.swift */, + 563B06DF2185E07200B38F35 /* ValueObservationReducerTests.swift */, + 563B07072186280500B38F35 /* ValueObservationRowTests.swift */, + 563B06E02185E07200B38F35 /* ValueObservationSchedulingTests.swift */, + ); + name = ValueObservation; + sourceTree = ""; + }; 5653EB8420961FBF00F46237 /* Association */ = { isa = PBXGroup; children = ( @@ -1675,6 +1739,7 @@ 56A238201B9C74A90082EB20 /* Statement */, 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */, 5607EFD11BB8253300605DE3 /* TransactionObserver */, + 563B06F52185E07C00B38F35 /* ValueObservation */, ); name = Core; sourceTree = ""; @@ -1768,6 +1833,7 @@ 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, 5605F1471C672E4000235C62 /* Support */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, + 563B06B4217F3C5900B38F35 /* ValueObservation.swift */, ); path = Core; sourceTree = ""; @@ -2244,6 +2310,7 @@ 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 */, @@ -2316,12 +2383,14 @@ 560FC56B1CB00B880014AA8E /* DatabaseCollationTests.swift in Sources */, 560FC56C1CB00B880014AA8E /* UpdateStatementTests.swift in Sources */, 5653EBE020961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, + 563B06FA21861D8B00B38F35 /* ValueObservationCountTests.swift in Sources */, 560FC56D1CB00B880014AA8E /* DatabaseMigratorTests.swift in Sources */, 56EA63CC209C7F31009715B8 /* DerivableRequestTests.swift in Sources */, 560FC5701CB00B880014AA8E /* DatabasePoolCollationTests.swift in Sources */, 560FC5711CB00B880014AA8E /* RecordPrimaryKeySingleTests.swift in Sources */, 5674A7191F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 56B021CA1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, + 563B07082186280600B38F35 /* ValueObservationRowTests.swift in Sources */, 562205F61E420E48005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 560FC5741CB00B880014AA8E /* DatabasePoolFunctionTests.swift in Sources */, 5653EBDC20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */, @@ -2347,12 +2416,15 @@ 56D5075F1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C631EACCCC7000F3F2B /* FTS5TokenizerTests.swift in Sources */, 5623934F1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, + 563B06ED2185E07300B38F35 /* ValueObservationReducerTests.swift in Sources */, 560FC57C1CB00B880014AA8E /* StatementArgumentsTests.swift in Sources */, + 563B06E52185E07300B38F35 /* ValueObservationReadonlyTests.swift in Sources */, 567F45A91F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, 5634B1081CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, 560FC57D1CB00B880014AA8E /* RecordInitializersTests.swift in Sources */, 56176C5F1EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 565F03C31CE5D3AA00DE108F /* RowAdapterTests.swift in Sources */, + 563B070D21862C3600B38F35 /* ValueObservationRecordTests.swift in Sources */, 56B6EF64208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */, 5657AB3F1D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 560FC57E1CB00B880014AA8E /* MutablePersistableRecordTests.swift in Sources */, @@ -2363,6 +2435,7 @@ 5653EBE820961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 56176C601EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */, 564E73EF203DA2A2000C443C /* JoinSupportTests.swift in Sources */, + 563B071E21862F5D00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */, 5674A7111F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, 5657AB471D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, 5665F86C203EF47D0084C6C0 /* ColumnInfoTests.swift in Sources */, @@ -2391,8 +2464,10 @@ 560FC58E1CB00B880014AA8E /* RecordPrimaryKeyRowIDTests.swift in Sources */, 560FC58F1CB00B880014AA8E /* DatabaseReaderTests.swift in Sources */, 5653EBD020961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, + 563B06E12185E07200B38F35 /* ValueObservationExtentTests.swift in Sources */, 560FC5901CB00B880014AA8E /* RecordEditedTests.swift in Sources */, 5665FA412129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, + 563B06F12185E07300B38F35 /* ValueObservationSchedulingTests.swift in Sources */, 5644DE8220F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, 560FC5911CB00B880014AA8E /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 56CC924C201E059100CB597E /* DropFirstCursorTests.swift in Sources */, @@ -2417,6 +2492,7 @@ 560FC59B1CB00B880014AA8E /* DatabaseTimestampTests.swift in Sources */, 5698AC411DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 5623936A1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, + 563B06E92185E07300B38F35 /* ValueObservationFetchTests.swift in Sources */, 560FC59C1CB00B880014AA8E /* StatementArguments+FoundationTests.swift in Sources */, 5657AB671D108BA9006283EF /* FoundationURLTests.swift in Sources */, 560FC59D1CB00B880014AA8E /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, @@ -2483,12 +2559,14 @@ 5671562E1CB16729007DC145 /* DatabasePoolCollationTests.swift in Sources */, 5671562F1CB16729007DC145 /* RecordPrimaryKeySingleTests.swift in Sources */, 5653EBE120961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, + 563B06FB21861D8B00B38F35 /* ValueObservationCountTests.swift in Sources */, 56EA63CD209C7F31009715B8 /* DerivableRequestTests.swift in Sources */, 56C3F7551CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, 5672DE5B1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, 56B021CB1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 5674A71B1F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 56B14E811D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, + 563B07092186280600B38F35 /* ValueObservationRowTests.swift in Sources */, 562205F91E420E49005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 566AD8C81D531BEB002EC1A8 /* TableDefinitionTests.swift in Sources */, 5653EBDD20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */, @@ -2514,12 +2592,15 @@ 56D507601F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C691EACCCC8000F3F2B /* FTS5TokenizerTests.swift in Sources */, 562393501DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, + 563B06EE2185E07300B38F35 /* ValueObservationReducerTests.swift in Sources */, 5671563A1CB16729007DC145 /* StatementArgumentsTests.swift in Sources */, + 563B06E62185E07300B38F35 /* ValueObservationReadonlyTests.swift in Sources */, 567F45AA1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, 5657AB601D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, 5671563B1CB16729007DC145 /* RecordInitializersTests.swift in Sources */, 56176C651EACCCC8000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 5657AB681D108BA9006283EF /* FoundationURLTests.swift in Sources */, + 563B070E21862C3600B38F35 /* ValueObservationRecordTests.swift in Sources */, 56B6EF65208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */, 5671563C1CB16729007DC145 /* MutablePersistableRecordTests.swift in Sources */, 5671563D1CB16729007DC145 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, @@ -2530,6 +2611,7 @@ 5653EBE920961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 56176C661EACCCC8000F3F2B /* FTS5PatternTests.swift in Sources */, 564E73F0203DA2A3000C443C /* JoinSupportTests.swift in Sources */, + 563B071F21862F5D00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */, 5674A7131F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, 567156411CB16729007DC145 /* PersistableRecordTests.swift in Sources */, 5665F86D203EF47D0084C6C0 /* ColumnInfoTests.swift in Sources */, @@ -2558,8 +2640,10 @@ 5671564F1CB16729007DC145 /* RecordEditedTests.swift in Sources */, 567156501CB16729007DC145 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 5653EBD120961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, + 563B06E22185E07200B38F35 /* ValueObservationExtentTests.swift in Sources */, 567156511CB16729007DC145 /* FetchableRecordTests.swift in Sources */, 5665FA422129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, + 563B06F22185E07300B38F35 /* ValueObservationSchedulingTests.swift in Sources */, 5644DE8320F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, 56A8C2441D1918EE0096E9D4 /* FoundationUUIDTests.swift in Sources */, 56CC924D201E059100CB597E /* DropFirstCursorTests.swift in Sources */, @@ -2584,6 +2668,7 @@ 567156571CB16729007DC145 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, 5698AC421DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 5623936B1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, + 563B06EA2185E07300B38F35 /* ValueObservationFetchTests.swift in Sources */, 567156591CB16729007DC145 /* DatabaseTimestampTests.swift in Sources */, 5671565A1CB16729007DC145 /* StatementArguments+FoundationTests.swift in Sources */, 5657AB581D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, @@ -2693,6 +2778,7 @@ 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 */, @@ -2765,12 +2851,14 @@ 5657AB4B1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, 56AFCA3E1CB1AA9900F48B96 /* DatabasePoolCollationTests.swift in Sources */, 5653EBE220961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, + 563B06FC21861D8B00B38F35 /* ValueObservationCountTests.swift in Sources */, 56FF455B1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, 56EA63CE209C7F31009715B8 /* DerivableRequestTests.swift in Sources */, 56AFCA3F1CB1AA9900F48B96 /* RecordPrimaryKeySingleTests.swift in Sources */, 56AFCA421CB1AA9900F48B96 /* DatabasePoolFunctionTests.swift in Sources */, 5674A7181F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 56AFCA441CB1AA9900F48B96 /* RowCopiedFromStatementTests.swift in Sources */, + 563B070A2186280600B38F35 /* ValueObservationRowTests.swift in Sources */, 56C3F7571CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, 562393351DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, 5653EBDE20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */, @@ -2796,12 +2884,15 @@ 56CC9238201E009900CB597E /* DropWhileCursorTests.swift in Sources */, 56D507631F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C751EACCCCA000F3F2B /* FTS5TokenizerTests.swift in Sources */, + 563B06EF2185E07300B38F35 /* ValueObservationReducerTests.swift in Sources */, 56AFCA4D1CB1AA9900F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */, + 563B06E72185E07300B38F35 /* ValueObservationReadonlyTests.swift in Sources */, 5657AB631D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, 567F45AD1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, 5657AB6B1D108BA9006283EF /* FoundationURLTests.swift in Sources */, 56AFCA4F1CB1AA9900F48B96 /* DataMemoryTests.swift in Sources */, 56176C711EACCCCA000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, + 563B070F21862C3600B38F35 /* ValueObservationRecordTests.swift in Sources */, 56B6EF66208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */, 5672DE5D1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, 56AFCA501CB1AA9900F48B96 /* RecordCopyTests.swift in Sources */, @@ -2812,6 +2903,7 @@ 5653EBEA20961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 5698AC9B1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 56176C721EACCCCA000F3F2B /* FTS5PatternTests.swift in Sources */, + 563B072021862F5D00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */, 564E73F1203DA2A3000C443C /* JoinSupportTests.swift in Sources */, 5674A7101F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, 56AFCA551CB1AA9900F48B96 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, @@ -2840,8 +2932,10 @@ 56AFCA5D1CB1AA9900F48B96 /* DatabaseReaderTests.swift in Sources */, 56A8C2491D1918F10096E9D4 /* FoundationNSUUIDTests.swift in Sources */, 5653EBD220961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, + 563B06E32185E07300B38F35 /* ValueObservationExtentTests.swift in Sources */, 56AFCA5E1CB1AA9900F48B96 /* FetchableRecordTests.swift in Sources */, 5665FA432129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, + 563B06F32185E07300B38F35 /* ValueObservationSchedulingTests.swift in Sources */, 5644DE8420F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, 56AFCA5F1CB1AA9900F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */, 56AFCA601CB1AA9900F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */, @@ -2866,6 +2960,7 @@ 5657AB3B1D108BA9006283EF /* FoundationDataTests.swift in Sources */, 5698AC081D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, 56AFCA661CB1AA9900F48B96 /* DatabaseQueueReleaseMemoryTests.swift in Sources */, + 563B06EB2185E07300B38F35 /* ValueObservationFetchTests.swift in Sources */, 561667061D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */, 565EFAF31D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, 56AFCA671CB1AA9900F48B96 /* DatabasePoolReleaseMemoryTests.swift in Sources */, @@ -2932,12 +3027,14 @@ 56AFCA921CB1ABC800F48B96 /* SelectStatementTests.swift in Sources */, 56AFCA931CB1ABC800F48B96 /* UpdateStatementTests.swift in Sources */, 5653EBE320961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, + 563B06FD21861D8B00B38F35 /* ValueObservationCountTests.swift in Sources */, 56AFCA941CB1ABC800F48B96 /* DatabaseMigratorTests.swift in Sources */, 56EA63CF209C7F31009715B8 /* DerivableRequestTests.swift in Sources */, 5657AB641D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, 56FF455C1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, 56AFCA971CB1ABC800F48B96 /* DatabasePoolCollationTests.swift in Sources */, 5674A7151F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, + 563B070B2186280600B38F35 /* ValueObservationRowTests.swift in Sources */, 5657AB5C1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 56AFCA981CB1ABC800F48B96 /* RecordPrimaryKeySingleTests.swift in Sources */, 562393361DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, @@ -2963,12 +3060,15 @@ 56CC9239201E009A00CB597E /* DropWhileCursorTests.swift in Sources */, 56D507641F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C7B1EACCCCB000F3F2B /* FTS5TokenizerTests.swift in Sources */, + 563B06F02185E07300B38F35 /* ValueObservationReducerTests.swift in Sources */, 566AD8CC1D531BEE002EC1A8 /* TableDefinitionTests.swift in Sources */, + 563B06E82185E07300B38F35 /* ValueObservationReadonlyTests.swift in Sources */, 56AFCAA41CB1ABC800F48B96 /* MutablePersistableRecordTests.swift in Sources */, 567F45AE1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, 56AFCAA51CB1ABC800F48B96 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 56AFCAA61CB1ABC800F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */, 56176C771EACCCCB000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, + 563B071021862C3600B38F35 /* ValueObservationRecordTests.swift in Sources */, 56B6EF67208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */, 5657AB6C1D108BA9006283EF /* FoundationURLTests.swift in Sources */, 56AFCAA81CB1ABC800F48B96 /* DataMemoryTests.swift in Sources */, @@ -2979,6 +3079,7 @@ 5653EBEB20961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 5698AC9C1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 56176C781EACCCCB000F3F2B /* FTS5PatternTests.swift in Sources */, + 563B072121862F5D00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */, 564E73F2203DA2A4000C443C /* JoinSupportTests.swift in Sources */, 5674A70D1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, 56AFCAAC1CB1ABC800F48B96 /* DatabaseValueConversionTests.swift in Sources */, @@ -3007,8 +3108,10 @@ 56AFCAB41CB1ABC800F48B96 /* DatabaseValueTests.swift in Sources */, 5657AB3C1D108BA9006283EF /* FoundationDataTests.swift in Sources */, 5653EBD320961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, + 563B06E42185E07300B38F35 /* ValueObservationExtentTests.swift in Sources */, 5634B10C1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, 5665FA442129EEEF004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, + 563B06F42185E07300B38F35 /* ValueObservationSchedulingTests.swift in Sources */, 5644DE8520F8D1E4001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, 56AFCAB51CB1ABC800F48B96 /* DatabaseQueueReadOnlyTests.swift in Sources */, 56AFCAB61CB1ABC800F48B96 /* DatabaseReaderTests.swift in Sources */, @@ -3033,6 +3136,7 @@ 561667071D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */, 5698AC091D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, 56AFCABD1CB1ABC800F48B96 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, + 563B06EC2185E07300B38F35 /* ValueObservationFetchTests.swift in Sources */, 56AFCABE1CB1ABC800F48B96 /* DatabaseErrorTests.swift in Sources */, 56AFCABF1CB1ABC800F48B96 /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 56AFCAC01CB1ABC800F48B96 /* DatabasePoolReleaseMemoryTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 40f51815e..7b4462c5f 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -43,6 +43,26 @@ 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 */; }; + 563B06D42185E04600B38F35 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CD2185E04600B38F35 /* ValueObservationReadonlyTests.swift */; }; + 563B06D52185E04600B38F35 /* ValueObservationFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CE2185E04600B38F35 /* ValueObservationFetchTests.swift */; }; + 563B06D62185E04600B38F35 /* ValueObservationFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CE2185E04600B38F35 /* ValueObservationFetchTests.swift */; }; + 563B06D72185E04600B38F35 /* ValueObservationReducerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CF2185E04600B38F35 /* ValueObservationReducerTests.swift */; }; + 563B06D82185E04600B38F35 /* ValueObservationReducerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06CF2185E04600B38F35 /* ValueObservationReducerTests.swift */; }; + 563B06D92185E04600B38F35 /* ValueObservationSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06D02185E04600B38F35 /* ValueObservationSchedulingTests.swift */; }; + 563B06DA2185E04600B38F35 /* ValueObservationSchedulingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06D02185E04600B38F35 /* ValueObservationSchedulingTests.swift */; }; + 563B06FF21861D9D00B38F35 /* ValueObservationCountTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06FE21861D9D00B38F35 /* ValueObservationCountTests.swift */; }; + 563B070021861D9D00B38F35 /* ValueObservationCountTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06FE21861D9D00B38F35 /* ValueObservationCountTests.swift */; }; + 563B0702218627DF00B38F35 /* ValueObservationRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B0701218627DE00B38F35 /* ValueObservationRowTests.swift */; }; + 563B0703218627DF00B38F35 /* ValueObservationRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B0701218627DE00B38F35 /* ValueObservationRowTests.swift */; }; + 563B071221862C3E00B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */; }; + 563B071321862C3E00B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */; }; + 563B071B21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; + 563B071C21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; }; 563EF420215F8A76007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF41E215F8A76007DAACD /* OrderedDictionary.swift */; }; 563EF421215F8A76007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF41E215F8A76007DAACD /* OrderedDictionary.swift */; }; 563EF4382161182C007DAACD /* AssociationAggregate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF4362161182C007DAACD /* AssociationAggregate.swift */; }; @@ -649,6 +669,16 @@ 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 = ""; }; + 563B06CF2185E04600B38F35 /* ValueObservationReducerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationReducerTests.swift; sourceTree = ""; }; + 563B06D02185E04600B38F35 /* ValueObservationSchedulingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationSchedulingTests.swift; sourceTree = ""; }; + 563B06FE21861D9D00B38F35 /* ValueObservationCountTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCountTests.swift; sourceTree = ""; }; + 563B0701218627DE00B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = ""; }; + 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = ""; }; + 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = ""; }; 563EF41E215F8A76007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = ""; }; 563EF4362161182C007DAACD /* AssociationAggregate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationAggregate.swift; sourceTree = ""; }; 563EF441216131F5007DAACD /* AssociationAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationAggregateTests.swift; sourceTree = ""; }; @@ -1153,6 +1183,22 @@ name = DatabaseQueue; sourceTree = ""; }; + 563B06DB2185E04E00B38F35 /* ValueObservation */ = { + isa = PBXGroup; + children = ( + 563B06FE21861D9D00B38F35 /* ValueObservationCountTests.swift */, + 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */, + 563B06CC2185E04500B38F35 /* ValueObservationExtentTests.swift */, + 563B06CE2185E04600B38F35 /* ValueObservationFetchTests.swift */, + 563B06CD2185E04600B38F35 /* ValueObservationReadonlyTests.swift */, + 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */, + 563B06CF2185E04600B38F35 /* ValueObservationReducerTests.swift */, + 563B0701218627DE00B38F35 /* ValueObservationRowTests.swift */, + 563B06D02185E04600B38F35 /* ValueObservationSchedulingTests.swift */, + ); + name = ValueObservation; + sourceTree = ""; + }; 5653EB3620961F6000F46237 /* Association */ = { isa = PBXGroup; children = ( @@ -1309,6 +1355,7 @@ 56A238201B9C74A90082EB20 /* Statement */, 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */, 5607EFD11BB8253300605DE3 /* TransactionObserver */, + 563B06DB2185E04E00B38F35 /* ValueObservation */, ); name = Core; sourceTree = ""; @@ -1400,8 +1447,9 @@ 56A238781B9C75030082EB20 /* Statement.swift */, 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */, 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, - 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, 5605F1471C672E4000235C62 /* Support */, + 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, + 563B06B8217F3C6E00B38F35 /* ValueObservation.swift */, ); path = Core; sourceTree = ""; @@ -1907,6 +1955,7 @@ 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 */, @@ -1979,12 +2028,14 @@ F3BA81221CFB3063003DC1BA /* RecordPrimaryKeyRowIDTests.swift in Sources */, F3BA80F81CFB3021003DC1BA /* StatementArgumentsTests.swift in Sources */, 5653EB7D20961FB200F46237 /* AssociationBelongsToSQLTests.swift in Sources */, + 563B070021861D9D00B38F35 /* ValueObservationCountTests.swift in Sources */, 5698AC0A1D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, 56EA63CA209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */, F3BA80E91CFB3016003DC1BA /* RowAdapterTests.swift in Sources */, 562393371DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, 5674A7161F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 56B021D01D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, + 563B0703218627DF00B38F35 /* ValueObservationRowTests.swift in Sources */, 5623935E1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 56B14E861D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 566AD8CD1D531BEE002EC1A8 /* TableDefinitionTests.swift in Sources */, @@ -2010,12 +2061,15 @@ 56CC9235201E009100CB597E /* DropWhileCursorTests.swift in Sources */, 56D507651F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 5657AB651D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, + 563B06D82185E04600B38F35 /* ValueObservationReducerTests.swift in Sources */, 5657AB6D1D108BA9006283EF /* FoundationURLTests.swift in Sources */, + 563B06D42185E04600B38F35 /* ValueObservationReadonlyTests.swift in Sources */, 567F45AF1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, F3BA804C1CFB2B24003DC1BA /* GRDBTestCase.swift in Sources */, 5698ACBD1DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 5623931F1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 562393701DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, + 563B071321862C3E00B38F35 /* ValueObservationRecordTests.swift in Sources */, 56B6EF61208CB746002F0ACB /* ColumnExpressionTests.swift in Sources */, F3BA81121CFB3059003DC1BA /* DatabaseMigratorTests.swift in Sources */, 56176C801EACCD31000F3F2B /* EncryptionTests.swift in Sources */, @@ -2026,6 +2080,7 @@ 5653EB8120961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 56B964CA1DA521450002DA19 /* FTS5PatternTests.swift in Sources */, 564E73F4203DA2AD000C443C /* JoinSupportTests.swift in Sources */, + 563B071C21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */, 5674A70E1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, 5657AB551D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */, 5665F869203EF4650084C6C0 /* ColumnInfoTests.swift in Sources */, @@ -2054,8 +2109,10 @@ 5698AC471DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, F3BA80D61CFB2FFD003DC1BA /* DatabaseReaderTests.swift in Sources */, 5653EB7520961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */, + 563B06D22185E04600B38F35 /* ValueObservationExtentTests.swift in Sources */, 5698AC9D1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 5665FA3E2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, + 563B06DA2185E04600B38F35 /* ValueObservationSchedulingTests.swift in Sources */, 5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, 56A4CDB71D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 56CC924A201E058900CB597E /* DropFirstCursorTests.swift in Sources */, @@ -2080,6 +2137,7 @@ 562393551DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, F3BA804F1CFB2B59003DC1BA /* DatabasePoolReleaseMemoryTests.swift in Sources */, 561667081D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */, + 563B06D62185E04600B38F35 /* ValueObservationFetchTests.swift in Sources */, 565EFAF51D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, F3BA81231CFB3063003DC1BA /* RecordPrimaryKeySingleTests.swift in Sources */, F3BA80541CFB2B59003DC1BA /* DatabaseRegionTests.swift in Sources */, @@ -2189,6 +2247,7 @@ 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 */, @@ -2261,12 +2320,14 @@ F3BA80F61CFB301E003DC1BA /* StatementColumnConvertibleFetchTests.swift in Sources */, F3BA80E61CFB3012003DC1BA /* DatabaseFunctionTests.swift in Sources */, 5653EB7C20961FB200F46237 /* AssociationBelongsToSQLTests.swift in Sources */, + 563B06FF21861D9D00B38F35 /* ValueObservationCountTests.swift in Sources */, 5698ACDA1DA925430056AF8C /* RowTestCase.swift in Sources */, 56EA63C9209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */, F3BA811D1CFB305F003DC1BA /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, F3BA80AD1CFB2FA6003DC1BA /* DataMemoryTests.swift in Sources */, 5698ACB91DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 5674A7141F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, + 563B0702218627DF00B38F35 /* ValueObservationRowTests.swift in Sources */, 567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, F3BA81301CFB3064003DC1BA /* RecordPrimaryKeyRowIDTests.swift in Sources */, 56DAA2D51DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, @@ -2292,12 +2353,15 @@ 56CC9234201E009000CB597E /* DropWhileCursorTests.swift in Sources */, 56D507611F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, F3BA80B01CFB2FB2003DC1BA /* DatabaseCollationTests.swift in Sources */, + 563B06D72185E04600B38F35 /* ValueObservationReducerTests.swift in Sources */, 56C7A6AE1D2DFF6100EFB0C2 /* FoundationNSDateTests.swift in Sources */, + 563B06D32185E04600B38F35 /* ValueObservationReadonlyTests.swift in Sources */, 567F45AB1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, F3BA80A61CFB2F91003DC1BA /* GRDBTestCase.swift in Sources */, 5657AB411D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 56B964C61DA521450002DA19 /* FTS5PatternTests.swift in Sources */, 562205FA1E420E49005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */, + 563B071221862C3E00B38F35 /* ValueObservationRecordTests.swift in Sources */, 56B6EF60208CB746002F0ACB /* ColumnExpressionTests.swift in Sources */, 562205FD1E420EA2005860AC /* DatabasePoolBackupTests.swift in Sources */, 562206091E420EB2005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */, @@ -2308,6 +2372,7 @@ 5653EB8020961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 5657AB611D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, 564E73F3203DA2AC000C443C /* JoinSupportTests.swift in Sources */, + 563B071B21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */, 5674A70C1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, 5698AC8C1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 5665F868203EF4640084C6C0 /* ColumnInfoTests.swift in Sources */, @@ -2336,8 +2401,10 @@ F3BA80D51CFB2FFB003DC1BA /* DatabaseReaderTests.swift in Sources */, F3BA81321CFB3064003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 5653EB7420961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */, + 563B06D12185E04600B38F35 /* ValueObservationExtentTests.swift in Sources */, 5623935A1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 5665FA3D2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, + 563B06D92185E04600B38F35 /* ValueObservationSchedulingTests.swift in Sources */, 5644DE7F20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */, F3BA80FC1CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */, 56CC9249201E058900CB597E /* DropFirstCursorTests.swift in Sources */, @@ -2362,6 +2429,7 @@ 562205FF1E420EA2005860AC /* DatabasePoolReadOnlyTests.swift in Sources */, 562205FC1E420E49005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 562393631DEE06D300A6B01F /* CursorTests.swift in Sources */, + 563B06D52185E04600B38F35 /* ValueObservationFetchTests.swift in Sources */, 562205FE1E420EA2005860AC /* DatabasePoolConcurrencyTests.swift in Sources */, 565EFAF11D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, F3BA812E1CFB3064003DC1BA /* RecordPrimaryKeyMultipleTests.swift in Sources */, diff --git a/Makefile b/Makefile index 62b7ac67d..892b1c034 100644 --- a/Makefile +++ b/Makefile @@ -37,6 +37,12 @@ XCODEVERSION := $(XCODEVERSION_MAJOR).$(XCODEVERSION_MINOR) # Used to determine if xcpretty is available XCPRETTY_PATH := $(shell command -v xcpretty 2> /dev/null) +# Avoid the "No output has been received in the last 10m0s" error on Travis: +COCOAPODS_EXTRA_TIME = +ifeq ($(TRAVIS),true) + COCOAPODS_EXTRA_TIME = --verbose +endif + # Tests # ===== @@ -334,7 +340,7 @@ endif test_CocoaPodsLint_GRDB: ifdef POD - $(POD) lib lint GRDB.swift.podspec --allow-warnings + $(POD) lib lint GRDB.swift.podspec --allow-warnings $(COCOAPODS_EXTRA_TIME) else @echo CocoaPods must be installed for test_CocoaPodsLint_GRDB @exit 1 @@ -342,7 +348,7 @@ endif test_CocoaPodsLint_GRDBPlus: ifdef POD - $(POD) lib lint GRDBPlus.podspec --allow-warnings + $(POD) lib lint GRDBPlus.podspec --allow-warnings $(COCOAPODS_EXTRA_TIME) else @echo CocoaPods must be installed for test_CocoaPodsLint_GRDBPlus @exit 1 @@ -350,7 +356,7 @@ endif test_CocoaPodsLint_GRDBCipher: ifdef POD - $(POD) lib lint GRDBCipher.podspec --allow-warnings + $(POD) lib lint GRDBCipher.podspec --allow-warnings $(COCOAPODS_EXTRA_TIME) else @echo CocoaPods must be installed for test_CocoaPodsLint_GRDBCipher @exit 1 diff --git a/README.md b/README.md index bce0a6206..c689dec52 100644 --- a/README.md +++ b/README.md @@ -55,18 +55,18 @@ See [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md) if you are looking for your GRDB ships with: - [Access to raw SQL and SQLite](#sqlite-api) -- [Records](#records): fetching and persistence methods for your custom structs and class hierarchies -- [Query Interface](#the-query-interface): a swift way to avoid the SQL language -- [WAL Mode Support](#database-pools): extra performance for multi-threaded applications -- [Migrations](#migrations): transform your database as your application evolves -- [Database Observation](#database-changes-observation): track database transactions, get notified of database changes +- [Records](#records): Fetching and persistence methods for your custom structs and class hierarchies. +- [Query Interface](#the-query-interface): A swift way to avoid the SQL language. +- [WAL Mode Support](#database-pools): Extra performance for multi-threaded applications. +- [Migrations](#migrations): Transform your database as your application evolves. +- [Database Observation](#database-changes-observation): Observe database changes and transactions. - [Full-Text Search](#full-text-search) - [Encryption](#encryption) - [Support for Custom SQLite Builds](Documentation/CustomSQLiteBuilds.md) Companion libraries that enhance and extend GRDB: -- [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB): track database changes in a reactive way, with [RxSwift](https://github.com/ReactiveX/RxSwift). +- [RxGRDB]: track database changes in a reactive way, with [RxSwift](https://github.com/ReactiveX/RxSwift). - [GRDBObjc](https://github.com/groue/GRDBObjc): FMDB-compatible bindings to GRDB. @@ -221,24 +221,14 @@ See the [Query Interface](#the-query-interface) ```swift let request = Place.order(Column("title")) - -// Track request changes with FetchedRecordsController -let controller = FetchedRecordsController(dbQueue, request: request) -controller.trackChanges { controller in - print("Places have changed.") - let places = controller.fetchedRecords // [Place] -} -try controller.performFetch() - -// Track request changes with RxSwift and RxGRDB -request.rx - .fetchAll(in: dbQueue) - .subscribe(onNext: { places: [Place] in +try ValueObservation + .trackingAll(request) + .start(in: dbQueue) { places: [Place] in print("Places have changed.") - }) + } ``` -See [Database Changes Observation](#database-changes-observation), and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) +See [Database Changes Observation](#database-changes-observation) @@ -272,8 +262,7 @@ Documentation - [Migrations](#migrations): Transform your database as your application evolves. - [Full-Text Search](#full-text-search): Perform efficient and customizable full-text searches. - [Joined Queries Support](#joined-queries-support): Consume complex joined queries. -- [Database Changes Observation](#database-changes-observation): Perform post-commit and post-rollback actions. -- [FetchedRecordsController](#fetchedrecordscontroller): Automated tracking of changes in a query results, plus UITableView animations. +- [Database Changes Observation](#database-changes-observation): Observe database changes and transactions. - [Encryption](#encryption): Encrypt your database with SQLCipher. - [Backup](#backup): Dump the content of a database to another. @@ -358,17 +347,17 @@ If you decide to use Carthage despite this warning, and get any Carthage-related 4. Add the `GRDB.framework` from the targetted platform to the **Embedded Binaries** section of the **General** tab of your application target (extension target for WatchOS). -See the [Demo Application](DemoApps/GRDBDemoiOS) for an example of such integration. +> :bulb: **Tip**: see the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for an example of such integration. Demo Application ================ -The repository comes with a [demo application](DemoApps/GRDBDemoiOS) that shows you: +The repository comes with a [demo application](DemoApps/GRDBDemoiOS/README.md) that shows you: - how to setup a database in an iOS app - how to define a simple [Codable Record](#codable-records) -- how to track database changes and animate a table view with [FetchedRecordsController](#fetchedrecordscontroller). +- how to track database changes with [ValueObservation] and [FetchedRecordsController].

@@ -451,7 +440,7 @@ let newPlaceCount = try dbQueue.write { db -> Int in **A database queue needs your application to follow rules in order to deliver its safety guarantees.** Please refer to the [Concurrency](#concurrency) chapter. -See the [Demo Application](DemoApps/GRDBDemoiOS) for a sample code that sets up a database queue on iOS. +> :bulb: **Tip**: see the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for a sample code that sets up a database queue on iOS. ### DatabaseQueue Configuration @@ -531,7 +520,7 @@ let newPlaceCount = try dbPool.write { db -> Int in **A database pool needs your application to follow rules in order to deliver its safety guarantees.** See the [Concurrency](#concurrency) chapter for more details about database pools, how they differ from database queues, and advanced use cases. -See the [Demo Application](DemoApps/GRDBDemoiOS) for a sample code that sets up a database queue on iOS, and just replace DatabaseQueue with DatabasePool. +> :bulb: **Tip**: see the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for a sample code that sets up a database queue on iOS, and just replace DatabaseQueue with DatabasePool. ### DatabasePool Configuration @@ -2072,7 +2061,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.4/Structs/Configuration.html) - `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/3.4/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), [FetchedRecordsController](#fetchedrecordscontroller) +- `sqlite3_commit_hook`, `sqlite3_rollback_hook`, `sqlite3_update_hook`: see [TransactionObserver Protocol](#transactionobserver-protocol), [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) @@ -2100,13 +2089,17 @@ try dbQueue.write { db in } ``` -Of course, you need to open a [database connection](#database-connections), and [create a database table](#database-schema) first. +Of course, you need to open a [database connection](#database-connections), and [create database tables](#database-schema) first. -Your custom structs and classes can adopt each protocol individually, and opt in to focused sets of features. Or you can subclass the `Record` class, and get the full toolkit in one go: fetching methods, persistence methods, and record comparison. See the [list of record methods](#list-of-record-methods) for an overview. +To define your custom records, you subclass the ready-made `Record` class, or you extend your structs and classes with protocols that come with focused sets of features: fetching methods, persistence methods, record comparison... + +Extending structs with record protocols is more "swifty". Subclassing the Record class is more "classic". You can choose either way. See some [examples of record definitions](#examples-of-record-definitions), and the [list of record methods](#list-of-record-methods) for an overview. > :point_up: **Note**: if you are familiar with Core Data's NSManagedObject or Realm's Object, you may experience a cultural shock: GRDB records are not uniqued, do not auto-update, and do not lazy-load. This is both a purpose, and a consequence of protocol-oriented programming. You should read [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) for a general introduction. > > :bulb: **Tip**: after you have read this chapter, check the [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) Guide. +> +> :bulb: **Tip**: see the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for an sample app that uses records. **Overview** @@ -2696,6 +2689,8 @@ For more information about Codable records, see: - [The userInfo Dictionary] - [Tip: Use Coding Keys as Columns](#tip-use-coding-keys-as-columns) +> :bulb: **Tip**: see the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for an sample app that uses Codable records. + ### JSON Columns @@ -2743,7 +2738,7 @@ protocol MutablePersistableRecord { } ``` -> :bulb: **Tip**: Make sure you set the JSONEncoder `sortedKeys` option, available from iOS 11.0+, macOS 10.13+, and watchOS 4.0+. This option makes sure that the JSON output is stable. This stability is required for [Record Comparison] to work as expected, and database observation tools such as [FetchedRecordsController](#fetchedrecordscontroller) or [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) to accurately recognize changed records. +> :bulb: **Tip**: Make sure you set the JSONEncoder `sortedKeys` option, available from iOS 11.0+, macOS 10.13+, and watchOS 4.0+. This option makes sure that the JSON output is stable. This stability is required for [Record Comparison] to work as expected, and database observation tools such as [ValueObservation] to accurately recognize changed records. ### Date and UUID Coding Strategies @@ -2868,15 +2863,15 @@ try dbQueue.read { db in } ``` -... and feed database observation tools such as [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB): +... and feed database observation tools such as [ValueObservation]: ```swift // Observe changes -Player.maximumScore.rx - .fetchOne(in: dbQueue) - .subscribe(onNext: { maxScore: Int? in +try ValueObservation + .trackingOne(Player.maximumScore) + .start(in: dbQueue) { maxScore: Int? in print("The maximum score has changed") - }) + } ``` @@ -3659,7 +3654,7 @@ Use an individual column as **primary**, **unique**, or **foreign key**. When de > } > ``` > -> The reason for this recommendation is that auto-incremented primary keys prevent the reuse of ids. This prevents your app or [database observation tools](#database-changes-observation) to think that a row was updated, when it was actually deleted, then replaced. Depending on your application needs, this may be OK. Or not. +> The reason for this recommendation is that auto-incremented primary keys prevent the reuse of ids. This prevents your app or [database observation tools](#database-changes-observation) to think that a row was updated, when it was actually deleted, then replaced. Depending on your application needs, this may be acceptable. But usually it is not. **Create an index** on the column: @@ -4243,7 +4238,7 @@ let minScore = row[0] as Int? let maxScore = row[1] as Int? ``` -When you also want to use database observation tools such as [FetchedRecordsController](#fetchedrecordscontroller) or [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB), you have to go one step further, and change the type of the request: +When you also want to use database observation tools such as [ValueObservation], you have to go one step further, and change the type of the request: - When you change the selection, prefer the `select(..., as:)` method: @@ -4256,12 +4251,12 @@ When you also want to use database observation tools such as [FetchedRecordsCont try request.fetchOne(db) // Int? } - // Observe with RxGRDB - request.rx - .fetchOne(in: dbQueue) - .subscribe(onNext: { maxScore: Int? in + // Observe with ValueObservation + try ValueObservation + .trackingOne(request) + .start(in: dbQueue) { maxScore: Int? in print("The maximum score has changed") - }) + } ``` - Otherwise, use `asRequest(of:)`. Here is an example that uses [Associations]: @@ -4282,13 +4277,12 @@ When you also want to use database observation tools such as [FetchedRecordsCont try request.fetchAll(db) // [BookInfo] } - // Observe with FetchedRecordsController - let controller = FetchedRecordsController( - dbQueue, - request: request, - isSameRecord: { (bookInfo1, bookInfo2) in - bookInfo1.book.id == bookInfo2.book.id - }) + // Observe with ValueObservation + try ValueObservation + .trackingAll(request) + .start(in: dbQueue) { bookInfos: [BookInfo] in + print("Books have changed") + } ``` @@ -4355,14 +4349,14 @@ let request = Player.filter(key: ["email": "arthur@example.com"]) let player = try request.fetchOne(db) // Player? ``` -Those requests help observing the database with [FetchedRecordsController](#fetchedrecordscontroller) or [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB): +Those requests can feed [ValueObservation]: ```swift -Player.filter(key: 1).rx - .fetchOne(in: dbQueue) - .subscribe(onNext: { player: Player? in +try ValueObservation. + .trackingOne(Player.filter(key: 1)) + .start(in: dbQueue) { player: Player? in print("Player 1 has changed") - }) + } ``` @@ -4475,14 +4469,14 @@ But you may prefer to bring some elegance back in, and build custom requests: try Player.customRequest().fetchAll(db) // [Player] ``` -Custom requests also grant [FetchedRecordsController](#fetchedrecordscontroller) and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) the ability to observe the database: +Custom requests can also feed [ValueObservation]: ```swift -Player.customRequest(...).rx - .fetchAll(in: dbQueue) - .subscribe(onNext: { players: [Player] in +try ValueObservation. + .trackingAll(Player.customRequest(...)) + .start(in: dbQueue) { players: [Player] in print("Players have changed") - }) + } ``` - [FetchRequest Protocol](#fetchrequest-protocol) @@ -4495,7 +4489,7 @@ Player.customRequest(...).rx **FetchRequest** is the protocol for all requests that run from a single select statement, and know how fetched rows should be interpreted: ```swift -protocol FetchRequest { +protocol FetchRequest: DatabaseRegionConvertible { /// The type that tells how fetched rows should be decoded associatedtype RowDecoder @@ -4504,9 +4498,6 @@ protocol FetchRequest { /// The number of rows fetched by the request. func fetchCount(_ db: Database) throws -> Int - - /// The database region that the request looks into. - func databaseRegion(_ db: Database) throws -> DatabaseRegion } ``` @@ -4516,7 +4507,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 `databaseRegion` method is involved in [database observation](#database-changes-observation). It is given a default implementation, based on the statement returned by `prepare`. For more information, see [DatabaseRegion](#databaseregion), and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB). +The base `DatabaseRegionConvertible` protocol is involved in [database observation](#database-changes-observation). For more information, see [DatabaseRegion](#databaseregion), and [ValueObservation]. The FetchRequest protocol is adopted, for example, by [query interface requests](#requests): @@ -5639,7 +5630,7 @@ let playerInfos = try dbQueue.read { db in ### Splitting Rows, the Request Way -The `PlayerInfo.fetchAll` method [above](#splitting-rows-the-record-way) directly fetches records. It's all good, but in order to profit from [database observation](#database-changes-observation) with [FetchedRecordsController](#fetchedrecordscontroller) or [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB), you'll need a [custom request](#custom-requests) that defines a database query. +The `PlayerInfo.fetchAll` method [above](#splitting-rows-the-record-way) directly fetches records. It's all good, but in order to profit from [database observation](#database-changes-observation), you'll need a [custom request](#custom-requests) that defines a database query. It is recommended that you read the previous paragraphs before you dive in this sample code. We start with the same PlayerInfo record as above: @@ -5792,15 +5783,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. -- [TransactionObserver Protocol](#transactionobserver-protocol): The low-level protocol for database observation - - [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) -- [FetchedRecordsController](#fetchedrecordscontroller): Automated tracking of changes in a query results, plus UITableView animations -- [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB): Automated tracking of changes in a query results, based on [RxSwift](https://github.com/ReactiveX/RxSwift) +- [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. @@ -5988,7 +5974,7 @@ do { > :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. -[FetchedRecordsController](#fetchedrecordscontroller) and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) are based on the TransactionObserver protocol. +[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. @@ -6133,13 +6119,15 @@ You can group regions: } ``` -Those regions provide support for the `observes(eventsOfKind:)` and `databaseDidChange(with:)` methods of transaction observers. For example: +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 region observer +// A transaction observer which notifies all changes to a database region. class DatabaseRegionObserver: TransactionObserver { let region: DatabaseRegion - var regionModified = false + var regionIsModified = false init(region: DatabaseRegion) { self.region = region @@ -6151,22 +6139,21 @@ class DatabaseRegionObserver: TransactionObserver { func databaseDidChange(with event: DatabaseEvent) { if region.isModified(by: event) { - regionModified = true + regionIsModified = true stopObservingDatabaseChangesUntilNextTransaction() } } func databaseDidRollback(_ db: Database) { - regionModified = false + regionIsModified = false } func databaseDidCommit(_ db: Database) { - if regionModified { - regionModified = false - - // You'll customize your handling of changes here: - print("Region changes have been committed.") - } + if regionIsModified == false { return } + regionIsModified = false + + // You'll customize your handling of changes here: + print("Region has been modified.") } } @@ -6177,7 +6164,7 @@ try dbQueue.write { db in } ``` -Beware that 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. +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. @@ -6203,19 +6190,432 @@ protocol TransactionObserverType : class { ``` +## ValueObservation + +**ValueObservation tracks changes in the results of database [requests](#requests), and notifies fresh values whenever the database changes.** + +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). + +Here is a typical UIViewController which observes the database in order to keep its view up-to-date: + +```swift +class PlayerViewController: UIViewController { + @IBOutlet weak var nameLabel: UILabel! + private var observer: TransactionObserver? + + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + + // Define a ValueObservation which tracks a player + let request = Player.filter(key: 42) + let observation = ValueObservation.trackingOne(request) + + // Start observing the database + observer = try! observation.start( + in: dbQueue, + onChange: { [unowned self] player: Player? in + // Player has changed: update view + self.nameLabel.text = player?.name + }) + } + + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + + // Stop observing the database + observer = nil + } +} +``` + +By default, all values are notified on the main queue. Views can be updated right from the `onChange` callback. + +An initial fetch is performed as soon as the observation starts: the view is set up and ready when the `viewWillAppear` method returns. + +The observer returned by the `start` method is stored in a property of the view controller. This allows the view controller to control the duration of the observation. When the observer is deallocated, the observation stops. Meanwhile, all transactions that modify the observed player are notified, and the `nameLabel` is kept up-to-date. + +> :bulb: **Tip**: see the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for an 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 + +Given a [request](#requests), you can track its number of results, the first one, or all of them: + +```swift +ValueObservation.trackingCount(request) +ValueObservation.trackingOne(request) +ValueObservation.trackingAll(request) +``` + +Those observations match the `fetchCount`, `fetchOne`, and `fetchAll` request methods: + +- `trackingCount` notifies counts: + + ```swift + // Observe number of players + let observer = ValueObservation + .trackingCount(Player.all()) + .start(in: dbQueue) { count: Int in + print("Number of players have changed: \(count)") + } + ``` + +- `trackingOne` notifies optional values, built from a single database row (if any): + + ```swift + // Observe a single player + let observer = ValueObservation + .trackingOne(Player.filter(key: 1)) + .start(in: dbQueue) { player: Player? in + print("Player has changed: \(player)") + } + + // Observe the maximum score + let request = Player.select(max(Column("score")), as: Int.self) + let observer = ValueObservation + .trackingOne(request) + .start(in: dbQueue) { maximumScore: Int? in + print("Maximum score has changed: \(maximumScore)") + } + ``` + +- `trackingAll` notifies arrays: + + ```swift + // Observe all players + let observer = ValueObservation + .trackingAll(Player.all()) + .start(in: dbQueue) { players: [Player] in + print("Players have changed: \(players)") + } + + // Observe all player names + let request = SQLRequest("SELECT name FROM player") + let observer = ValueObservation + .trackingAll(request) + .start(in: dbQueue) { names: [String] in + print("Player names have changed: \(names)") + } + ``` + + +### 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. + +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: + +```swift +// The two observed requests (the team and its players) +let teamRequest = Team.filter(key: 1) +let playersRequest = Player.filter(Column("teamId") == 1) + +// The fetched value +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 { + var teamId: Int64 + + private var teamRequest: QueryInterfaceRequest { + return Team.filter(key: teamId) + } + + 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) + } + + func fetch(_ db: Database) throws -> TeamInfo? { + guard let team = try teamRequest.fetchOne(db) else { + return nil + } + let players = try playersRequest.fetchAll(db) + return TeamInfo(team: team, players: players) + } +} + +let request = TeamInfoRequest(teamId: 1) +let observer = ValueObservation + .tracking(request, fetch: request.fetch) + .start(in: dbQueue) { teamInfo: TeamInfo? in + print("Team and players have hanged.") + } +``` + +See [DatabaseRegion](#databaseregion) for more information. + + +### ValueObservation.tracking(_:reducer:) + +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: + +```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? +} +``` + +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 `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: + +```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.") + } +``` + + +### ValueObservation Options + +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 + +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 = ValueObservation... +observation.extent = .databaseLifetime +_ = observation.start(in: dbQueue) { newValue 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) { ... } + +// Stop +dbQueue.remove(transactionObserver: observer) +``` + + +#### ValueObservation.scheduling + +The `scheduling` property lets you control how fresh values are notified: + +- `.mainQueue` (the default): 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: + + ```swift + // On main queue + let observer = ValueObservation + .trackingAll(Player.all()) + .start(in: dbQueue) { players: [Player] in + // On main queue + 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: + + ```swift + // Not on the main queue + let observer = ValueObservation + .trackingAll(Player.all()) + .start(in: dbQueue) { players: [Player] in + // On main queue + print("fresh players: \(players)") + } + ``` + + When the database changes, fresh values are asynchronously notified: + + ```swift + // 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. + + ```swift + let customQueue = DispatchQueue(label: "customQueue") + var observation = ValueObservation.trackingAll(Player.all()) + observation.scheduling = .onQueue(customQueue, startImmediately: true) + let observer = try observation.start(in: dbQueue) { players: [Player] in + // On customQueue + print("fresh players: \(players)")s + } + ``` + +- `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. + + ```swift + // 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. + + > :point_up: **Note**: this unsafe mode is intended for third-party libraries that provide their own scheduling engine. + + +#### ValueObservation.requiresWriteAccess + +The `requiresWriteAccess` property is false by default. When true, a ValueObservation has a write access to the database, and its fetches are automatically wrapped in a [savepoint](#transactions-and-savepoints): + +```swift +var observation = ValueObservation.tracking(..., fetch: { db in + // write access allowed +}) +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 + +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: + +```swift +let observation = ValueObservation + .trackingOne(Player.filter(key: 42)) + .map { player in player?.computeValue() } + .start(in: dbQueue) { value in + print(value) + } +``` + + +#### 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)") + }) +``` + + ## FetchedRecordsController -**You use FetchedRecordsController to track changes in the results of an SQLite request.** - -**FetchedRecordsController can also feed table views, collection views, and animate cells when the results of the request change.** +**FetchedRecordsController track changes in the results of a request, feedd table views, collection views, and animate cells when the results of the request change.** It looks and behaves very much like [Core Data's NSFetchedResultsController](https://developer.apple.com/library/ios/documentation/CoreData/Reference/NSFetchedResultsController_Class/). Given a fetch request, and a type that adopts the [FetchableRecord] protocol, such as a subclass of the [Record](#record-class) class, a FetchedRecordsController is able to track changes in the results of the fetch request, notify of those changes, and return the results of the request in a form that is suitable for a table view or a collection view, with one cell per fetched record. -See the [Demo Application](DemoApps/GRDBDemoiOS) for an sample app that uses FetchedRecordsController. - -See also [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB), an [RxSwift](https://github.com/ReactiveX/RxSwift) extension, for a reactive way to track request changes. +> :point_up: **Note**: when you don't need to animate a table or a collection view, use [ValueObservation] or [RxGRDB] instead. +> +> :bulb: **Tip**: see the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for an sample app that uses FetchedRecordsController. - [Creating the Fetched Records Controller](#creating-the-fetched-records-controller) - [Responding to Changes](#responding-to-changes) @@ -6509,10 +6909,10 @@ controller.trackChanges( ``` > :warning: **Warning**: notification of individual record changes (the `onChange` callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus **not suited for large result sets**. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see [Issue 263](https://github.com/groue/GRDB.swift/issues/263) for more information. - -See the [Demo Application](DemoApps/GRDBDemoiOS) for an sample app that uses FetchedRecordsController to animate a table view. - +> > :point_up: **Note**: our sample code above uses `unowned` references to the table view controller. This is a safe pattern as long as the table view controller owns the fetched records controller, and is deallocated from the main thread (this is usually the case). In other situations, prefer weak references. +> +> :bulb: **Tip**: see the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for an sample app that uses FetchedRecordsController to animate a table view. ### FetchedRecordsController Concurrency @@ -7109,7 +7509,7 @@ Those guarantees hold as long as you follow three rules: This means that opening a new connection each time you access the database is a bad idea. Do share a single connection instead. - See the [Demo Application](DemoApps/GRDBDemoiOS) for an sample app that sets up a single database queue that is available throughout the application. + See the [Demo Application](DemoApps/GRDBDemoiOS/README.md) for an sample app that sets up a single database queue that is available throughout the application. If there are several instances of database queues or pools that write in the same database, a multi-threaded application will eventually face "database is locked" errors. See [Dealing with External Connections](#dealing-with-external-connections). @@ -7359,10 +7759,37 @@ 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) -- [FetchedRecordsController](#fetchedrecordscontroller) -- [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) +- [ValueObservation] +- [FetchedRecordsController] +- [RxGRDB] -Caution: DatabaseReader and DatabaseWriter only provide the *smallest* common guarantees. They don't erase the differences between queues, pools, and snapshots. See for example [Differences between Database Queues and Pools](#differences-between-database-queues-and-pools). +Only five types adopt those protocols: DatabaseQueue, DatabasePool, DatabaseSnapshot, AnyDatabaseReader, and AnyDatabaseWriter. Expanding this set is not supported: any future GRDB release may break your custom writers and readers, without notice. + +DatabaseReader and DatabaseWriter provide the *smallest* common guarantees: they don't erase the differences between queues, pools, and snapshots. See for example [Differences between Database Queues and Pools](#differences-between-database-queues-and-pools). + +However, you can prevent some parts of your application from writing in the database by giving them a DatabaseReader: + +```swift +// This class can read in the database, but can't write into it. +class MyReadOnlyComponent { + let reader: DatabaseReader + + init(reader: DatabaseReader) { + self.reader = reader + } +} + +let dbQueue: DatabaseQueue = ... +let component = MyReadOnlyComponent(reader: dbQueue) +``` + +> :point_up: **Note**: DatabaseReader is not a **secure** way to prevent an application component from writing in the database, because write access is just a cast away: +> +> ```swift +> if let dbQueue = reader as? DatabaseQueue { +> try dbQueue.write { ... } +> } +> ``` ### Unsafe Concurrency APIs @@ -7839,7 +8266,7 @@ Sample Code =========== - The [Documentation](#documentation) is full of GRDB snippets. -- [Demo Application](DemoApps/GRDBDemoiOS): A sample iOS application. +- [Demo Application](DemoApps/GRDBDemoiOS/README.md): A sample iOS application. - [WWDC Companion](https://github.com/groue/WWDCCompanion): A sample iOS application. - Check `GRDB.xcworkspace`: it contains GRDB-enabled playgrounds to play with. - How to synchronize a database table with a JSON payload: [JSONSynchronization.playground](Playgrounds/JSONSynchronization.playground/Contents.swift) @@ -7893,3 +8320,6 @@ This chapter has been renamed [Beyond FetchableRecord]. [Record Comparison]: #record-comparison [Record Customization Options]: #record-customization-options [TableRecord]: #tablerecord-protocol +[ValueObservation]: #valueobservation +[FetchedRecordsController]: #fetchedrecordscontroller +[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB \ No newline at end of file diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index 109d65759..f92531a46 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -42,18 +42,6 @@ private class UserDatabaseAggregate2 : DatabaseAggregate { func finalize() throws -> DatabaseValueConvertible? { preconditionFailure() } } -// MARK: - DatabaseReader - -private class UserDatabaseReader : DatabaseReader { - func read(_ block: (Database) throws -> T) throws -> T { preconditionFailure() } - func unsafeRead(_ block: (Database) throws -> T) throws -> T { preconditionFailure() } - func unsafeReentrantRead(_ block: (Database) throws -> T) throws -> T { preconditionFailure() } - func add(function: DatabaseFunction) { } - func remove(function: DatabaseFunction) { } - func add(collation: DatabaseCollation) { } - func remove(collation: DatabaseCollation) { } -} - // MARK: - DatabaseValueConvertible private struct UserDatabaseValueConvertible1 : DatabaseValueConvertible { @@ -66,23 +54,6 @@ private class UserDatabaseValueConvertible2 : DatabaseValueConvertible { static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { preconditionFailure() } } -// MARK: - DatabaseWriter - -private class UserDatabaseWriter : DatabaseWriter { - func read(_ block: (Database) throws -> T) throws -> T { preconditionFailure() } - func unsafeRead(_ block: (Database) throws -> T) throws -> T { preconditionFailure() } - func unsafeReentrantRead(_ block: (Database) throws -> T) throws -> T { preconditionFailure() } - func add(function: DatabaseFunction) { } - func remove(function: DatabaseFunction) { } - func add(collation: DatabaseCollation) { } - func remove(collation: DatabaseCollation) { } - func write(_ block: (Database) throws -> T) rethrows -> T { preconditionFailure() } - func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T { preconditionFailure() } - func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T { preconditionFailure() } - func readFromCurrentState(_ block: @escaping (Database) -> Void) throws { preconditionFailure() } - func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future { preconditionFailure() } -} - // MARK: - FTS5Tokenizer #if SQLITE_ENABLE_FTS5 diff --git a/Tests/GRDBTests/DatabaseRegionTests.swift b/Tests/GRDBTests/DatabaseRegionTests.swift index 4f7d992ee..47744ced9 100644 --- a/Tests/GRDBTests/DatabaseRegionTests.swift +++ b/Tests/GRDBTests/DatabaseRegionTests.swift @@ -443,7 +443,7 @@ class DatabaseRegionTests : GRDBTestCase { try XCTAssertEqual(request.databaseRegion(db).description, "a(id,name),b(aid,id,name)[1],c(aid,id,name)") } } - } + } func testDatabaseRegionOfDerivedRequests() throws { let dbQueue = try makeDatabaseQueue() diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 9989a9882..60fa4f0ff 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -166,3 +166,11 @@ class GRDBTestCase: XCTestCase { } } } + +#if !swift(>=4.2) +extension Sequence { + func allSatisfy(_ predicate: (Self.Element) throws -> Bool) rethrows -> Bool { + return try !contains(where: { try !predicate($0) }) + } +} +#endif diff --git a/Tests/GRDBTests/ValueObservationCountTests.swift b/Tests/GRDBTests/ValueObservationCountTests.swift new file mode 100644 index 000000000..70a9f7eca --- /dev/null +++ b/Tests/GRDBTests/ValueObservationCountTests.swift @@ -0,0 +1,49 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + #if SWIFT_PACKAGE + import CSQLite + #else + import SQLite3 + #endif + import GRDB +#endif + +class ValueObservationCountTests: GRDBTestCase { + func testCount() 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 = 5 + + struct T: TableRecord { } + var observation = ValueObservation.trackingCount(T.all()) + observation.extent = .databaseLifetime + _ = 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") // +1 + try db.execute("UPDATE t SET id = id") // = + try db.execute("INSERT INTO t DEFAULT VALUES") // +1 + try db.inTransaction { // +1 + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("INSERT INTO t DEFAULT VALUES") + try db.execute("DELETE FROM t WHERE id = 1") + return .commit + } + try db.execute("DELETE FROM t WHERE id = 2") // -1 + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1, 2, 3, 2]) + } +} diff --git a/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift new file mode 100644 index 000000000..1f5e11562 --- /dev/null +++ b/Tests/GRDBTests/ValueObservationDatabaseValueConvertibleTests.swift @@ -0,0 +1,146 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + #if SWIFT_PACKAGE + import CSQLite + #else + import SQLite3 + #endif + import GRDB +#endif + +private struct Name: DatabaseValueConvertible { + var rawValue: String + + var databaseValue: DatabaseValue { + return rawValue.databaseValue + } + + static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Name? { + guard let rawValue = String.fromDatabaseValue(dbValue) else { + return nil + } + return Name(rawValue: rawValue) + } +} + +class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase { + func testAll() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + + var results: [[Name]] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 4 + + var observation = ValueObservation.trackingAll(SQLRequest("SELECT name FROM t ORDER BY id")) + observation.extent = .databaseLifetime + _ = try observation.start(in: dbQueue) { names in + results.append(names) + notificationExpectation.fulfill() + } + + 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"]]) + } + + func testOne() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + + var results: [Name?] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 7 + + var observation = ValueObservation.trackingOne(SQLRequest("SELECT name FROM t ORDER BY id DESC")) + observation.extent = .databaseLifetime + _ = try observation.start(in: dbQueue) { name in + results.append(name) + notificationExpectation.fulfill() + } + + try dbQueue.inDatabase { db in + try db.execute("INSERT INTO t (id, name) VALUES (1, 'foo')") + try db.execute("UPDATE t SET name = 'foo' WHERE id = 1") + try db.inTransaction { + 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") + try db.execute("INSERT INTO t (id, name) VALUES (1, 'baz')") + try db.execute("UPDATE t SET name = NULL") + try db.execute("DELETE FROM t") + try db.execute("INSERT INTO t (id, name) VALUES (1, NULL)") + try db.execute("UPDATE t SET name = 'qux'") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(results.map { $0.map { $0.rawValue }}, [ + nil, + "foo", + "bar", + nil, + "baz", + nil, + "qux"]) + } + + func testAllOptional() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + + var results: [[Name?]] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 4 + + var observation = ValueObservation.trackingAll(SQLRequest("SELECT name FROM t ORDER BY id")) + observation.extent = .databaseLifetime + _ = try observation.start(in: dbQueue) { names in + results.append(names) + notificationExpectation.fulfill() + } + + 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, NULL)") + 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", nil], + [nil]]) + } +} diff --git a/Tests/GRDBTests/ValueObservationExtentTests.swift b/Tests/GRDBTests/ValueObservationExtentTests.swift new file mode 100644 index 000000000..253507f6f --- /dev/null +++ b/Tests/GRDBTests/ValueObservationExtentTests.swift @@ -0,0 +1,143 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + #if SWIFT_PACKAGE + import CSQLite + #else + import SQLite3 + #endif + import GRDB +#endif + +class ValueObservationExtentTests: GRDBTestCase { + func testDefaultExtentIsObserverLifetime() { + let observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { _ in }) + XCTAssertEqual(observation.extent, .observerLifetime) + } + + func testExtentDatabaseLifetime() 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 + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 3 + + // A reducer + let reducer = AnyValueReducer( + fetch: { _ in }, + value: { $0 }) + + // Create an observation + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + observation.extent = .databaseLifetime + + // Start observation + _ = try observation.start(in: dbQueue) { + notificationExpectation.fulfill() + } + + // notified + try dbQueue.write { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + // notified + try dbQueue.write { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + } + + func testExtentObserverLifetime() 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 changesCount = 0 + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + // A reducer + let reducer = AnyValueReducer( + fetch: { _ in }, + value: { $0 }) + + // Create an observation + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + observation.extent = .observerLifetime + + // Start observation and deallocate observer after second change + var observer: TransactionObserver? + observer = try observation.start(in: dbQueue) { + changesCount += 1 + if changesCount == 2 { + observer = nil + } + notificationExpectation.fulfill() + } + + // notified + try dbQueue.write { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + // not notified + try dbQueue.write { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + // Avoid "Variable 'observer' was written to, but never read" warning + _ = observer + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(changesCount, 2) + } + + func testExtentNextTransaction() 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 + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 2 + + // A reducer + let reducer = AnyValueReducer( + fetch: { _ in }, + value: { $0 }) + + // Create an observation + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer) + observation.extent = .nextTransaction + + // Start observation + let observer = try observation.start(in: dbQueue) { + notificationExpectation.fulfill() + } + + try withExtendedLifetime(observer) { + // notified + try dbQueue.write { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + // not notified + try dbQueue.write { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + } + } +} diff --git a/Tests/GRDBTests/ValueObservationFetchTests.swift b/Tests/GRDBTests/ValueObservationFetchTests.swift new file mode 100644 index 000000000..de6aa1dbe --- /dev/null +++ b/Tests/GRDBTests/ValueObservationFetchTests.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 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 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() + } + + 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, 2]) + } +} diff --git a/Tests/GRDBTests/ValueObservationReadonlyTests.swift b/Tests/GRDBTests/ValueObservationReadonlyTests.swift new file mode 100644 index 000000000..c5bc764c5 --- /dev/null +++ b/Tests/GRDBTests/ValueObservationReadonlyTests.swift @@ -0,0 +1,122 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + #if SWIFT_PACKAGE + import CSQLite + #else + import SQLite3 + #endif + import GRDB +#endif + +class ValueObservationReadonlyTests: GRDBTestCase { + + func testReadOnlyObservation() 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 = 2 + + 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") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1]) + } + + func testWriteObservationFailsByDefault() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + let observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db -> Int in + try db.execute("INSERT INTO t DEFAULT VALUES") + return 0 + }) + + do { + _ = try observation.start( + in: dbQueue, + onError: { _ in fatalError() }, + onChange: { _ in fatalError() }) + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_READONLY) + XCTAssertEqual(error.message, "attempt to write a readonly database") + XCTAssertEqual(error.sql!, "INSERT INTO t DEFAULT VALUES") + XCTAssertEqual(error.description, "SQLite error 8 with statement `INSERT INTO t DEFAULT VALUES`: attempt to write a readonly database") + } + } + + func testWriteObservation() 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 = 2 + + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db -> Int in + XCTAssert(db.isInsideTransaction, "expected a wrapping transaction") + try db.execute("CREATE TEMPORARY TABLE temp AS SELECT * FROM t") + let result = try Int.fetchOne(db, "SELECT COUNT(*) FROM temp")! + try db.execute("DROP TABLE temp") + return result + }) + observation.extent = .databaseLifetime + observation.requiresWriteAccess = true + _ = try observation.start(in: dbQueue) { count in + 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 testWriteObservationIsWrappedInSavepoint() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { + try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") + } + + struct TestError: Error { } + var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + throw TestError() + }) + observation.requiresWriteAccess = true + + do { + _ = try observation.start( + in: dbQueue, + onError: { _ in fatalError() }, + onChange: { _ in fatalError() }) + XCTFail("Expected error") + } catch is TestError { + } + + let count = try dbQueue.read { try Int.fetchOne($0, "SELECT COUNT(*) FROM t")! } + XCTAssertEqual(count, 0) + } +} diff --git a/Tests/GRDBTests/ValueObservationRecordTests.swift b/Tests/GRDBTests/ValueObservationRecordTests.swift new file mode 100644 index 000000000..d145b85ee --- /dev/null +++ b/Tests/GRDBTests/ValueObservationRecordTests.swift @@ -0,0 +1,101 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + #if SWIFT_PACKAGE + import CSQLite + #else + import SQLite3 + #endif + import GRDB +#endif + +private struct Player: FetchableRecord { + var id: Int64 + var name: String + + init(row: Row) { + self.id = row["id"] + self.name = row["name"] + } + + var row: Row { + return ["id": id, "name": name] + } +} + +class ValueObservationRecordTests: GRDBTestCase { + func testAll() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + + var results: [[Player]] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 4 + + var observation = ValueObservation.trackingAll(SQLRequest("SELECT * FROM t ORDER BY id")) + observation.extent = .databaseLifetime + _ = try observation.start(in: dbQueue) { players in + results.append(players) + notificationExpectation.fulfill() + } + + 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.row }}, [ + [], + [["id":1, "name":"foo"]], + [["id":1, "name":"foo"], ["id":2, "name":"bar"]], + [["id":2, "name":"bar"]]]) + } + + func testOne() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + + var results: [Player?] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 4 + + var observation = ValueObservation.trackingOne(SQLRequest("SELECT * FROM t ORDER BY id DESC")) + observation.extent = .databaseLifetime + _ = try observation.start(in: dbQueue) { player in + results.append(player) + notificationExpectation.fulfill() + } + + 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") // -1 + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(results.map { $0.map { $0.row }}, [ + nil, + ["id":1, "name":"foo"], + ["id":2, "name":"bar"], + nil]) + } +} diff --git a/Tests/GRDBTests/ValueObservationReducerTests.swift b/Tests/GRDBTests/ValueObservationReducerTests.swift new file mode 100644 index 000000000..393da3e7c --- /dev/null +++ b/Tests/GRDBTests/ValueObservationReducerTests.swift @@ -0,0 +1,302 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + #if SWIFT_PACKAGE + import CSQLite + #else + import SQLite3 + #endif + import GRDB +#endif + +class ValueObservationReducerTests: GRDBTestCase { + 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")! + }, + value: { count -> String? in + reduceCount += 1 + if dropNext { + // test that reducer can drop values + dropNext = false + 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: 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"]) + } + + 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 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 + } + }, + 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() + }, + onChange: { + changes.append($0) + notificationExpectation.fulfill() + }) + + struct TestError: Error { } + nextError = TestError() + try dbQueue.write { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + 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) + } + + 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() + } + + try dbQueue.write { db in + try db.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [1, 2]) + } + + 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)" + } + + // 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"]) + } + + 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() + } + + try dbQueue.inDatabase { + try $0.execute("INSERT INTO t DEFAULT VALUES") + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, ["0", "1", "2"]) + } +} diff --git a/Tests/GRDBTests/ValueObservationRowTests.swift b/Tests/GRDBTests/ValueObservationRowTests.swift new file mode 100644 index 000000000..1b6656ebf --- /dev/null +++ b/Tests/GRDBTests/ValueObservationRowTests.swift @@ -0,0 +1,87 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + #if SWIFT_PACKAGE + import CSQLite + #else + import SQLite3 + #endif + import GRDB +#endif + +class ValueObservationRowTests: GRDBTestCase { + func testAll() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + + var results: [[Row]] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 4 + + var observation = ValueObservation.trackingAll(SQLRequest("SELECT * FROM t ORDER BY id")) + observation.extent = .databaseLifetime + _ = try observation.start(in: dbQueue) { rows in + results.append(rows) + notificationExpectation.fulfill() + } + + 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, [ + [], + [["id":1, "name":"foo"]], + [["id":1, "name":"foo"], ["id":2, "name":"bar"]], + [["id":2, "name":"bar"]]]) + } + + func testOne() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") } + + var results: [Row?] = [] + let notificationExpectation = expectation(description: "notification") + notificationExpectation.assertForOverFulfill = true + notificationExpectation.expectedFulfillmentCount = 4 + + var observation = ValueObservation.trackingOne(SQLRequest("SELECT * FROM t ORDER BY id DESC")) + observation.extent = .databaseLifetime + _ = try observation.start(in: dbQueue) { row in + results.append(row) + notificationExpectation.fulfill() + } + + 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") // -1 + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(results, [ + nil, + ["id":1, "name":"foo"], + ["id":2, "name":"bar"], + nil]) + } +} diff --git a/Tests/GRDBTests/ValueObservationSchedulingTests.swift b/Tests/GRDBTests/ValueObservationSchedulingTests.swift new file mode 100644 index 000000000..18593a024 --- /dev/null +++ b/Tests/GRDBTests/ValueObservationSchedulingTests.swift @@ -0,0 +1,377 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + #if SWIFT_PACKAGE + import CSQLite + #else + import SQLite3 + #endif + import GRDB +#endif + +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") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [0, 1]) + } + + @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)") } + + 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: 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]) + } + + 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]) + } + + 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() + } + + try dbQueue.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [1]) + } + + 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() + }, + onChange: { _ in fatalError() }) + + try dbQueue.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(errorCount, 1) + } + + 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 + if counts.isEmpty { + // require custom queue on first notification + 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 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() + } + + try dbQueue.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(counts, [1]) + } + + 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() + }, + onChange: { _ in fatalError() }) + + try dbQueue.write { + try $0.execute("INSERT INTO t DEFAULT VALUES") + } + + waitForExpectations(timeout: 1, handler: nil) + XCTAssertEqual(errorCount, 1) + } +}