From e5d97c15ad3c603bfca0d48ae7bf7f20fbdb5ccd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 25 Oct 2018 08:05:55 +0200 Subject: [PATCH] Looking for a good API --- GRDB.xcodeproj/project.pbxproj | 16 +- GRDB/Core/DatabaseWriter+Observation.swift | 644 ------------------- GRDB/Core/ValueObservation.swift | 689 +++++++++++++++++++++ GRDBCipher.xcodeproj/project.pbxproj | 12 +- GRDBCustom.xcodeproj/project.pbxproj | 12 +- 5 files changed, 709 insertions(+), 664 deletions(-) delete mode 100644 GRDB/Core/DatabaseWriter+Observation.swift create mode 100644 GRDB/Core/ValueObservation.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 5f58a5495..446658852 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -116,9 +116,9 @@ 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 /* DatabaseWriter+Observation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06AA217EF0CC00B38F35 /* DatabaseWriter+Observation.swift */; }; - 563B06AC217EF0CC00B38F35 /* DatabaseWriter+Observation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06AA217EF0CC00B38F35 /* DatabaseWriter+Observation.swift */; }; - 563B06AD217EF0CC00B38F35 /* DatabaseWriter+Observation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06AA217EF0CC00B38F35 /* DatabaseWriter+Observation.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 */; }; 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 */; }; @@ -892,7 +892,7 @@ 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 /* DatabaseWriter+Observation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseWriter+Observation.swift"; sourceTree = ""; }; + 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservation.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 = ""; }; @@ -1708,7 +1708,6 @@ 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */, 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */, 563363C31C942C37000BE133 /* DatabaseWriter.swift */, - 563B06AA217EF0CC00B38F35 /* DatabaseWriter+Observation.swift */, 5636E9BB1D22574100B9B05F /* FetchRequest.swift */, 56A238761B9C75030082EB20 /* Row.swift */, 567404871CEF84C8003ED5CC /* RowAdapter.swift */, @@ -1719,6 +1718,7 @@ 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, 5605F1471C672E4000235C62 /* Support */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, + 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */, ); path = Core; sourceTree = ""; @@ -2377,7 +2377,7 @@ 56CEB5671EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 5653EB272094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 565490B91D5AE236005622CB /* DatabasePool.swift in Sources */, - 563B06AD217EF0CC00B38F35 /* DatabaseWriter+Observation.swift in Sources */, + 563B06AD217EF0CC00B38F35 /* ValueObservation.swift in Sources */, 5674A6EF1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 565490D81D5AE252005622CB /* DatabaseMigrator.swift in Sources */, 56CEB5601EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, @@ -2568,7 +2568,7 @@ 5605F1661C672E4000235C62 /* NSNull.swift in Sources */, 569EF0E3200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */, 56A238841B9C75030082EB20 /* DatabaseQueue.swift in Sources */, - 563B06AC217EF0CC00B38F35 /* DatabaseWriter+Observation.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 */, @@ -2946,7 +2946,7 @@ 563EF44A2161F179007DAACD /* Inflections.swift in Sources */, 566B91091FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91231FA4CF810012D5B0 /* Database+Schema.swift in Sources */, - 563B06AB217EF0CC00B38F35 /* DatabaseWriter+Observation.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/DatabaseWriter+Observation.swift b/GRDB/Core/DatabaseWriter+Observation.swift deleted file mode 100644 index d0c14c00b..000000000 --- a/GRDB/Core/DatabaseWriter+Observation.swift +++ /dev/null @@ -1,644 +0,0 @@ -// -// DatabaseWriter+Observation.swift -// GRDB -// -// Created by Gwendal Roué on 23/10/2018. -// Copyright © 2018 Gwendal Roué. All rights reserved. -// - -/// InitialDispatch controls how initial values are dispatched when one starts -/// observing database values. -public enum InitialDispatch { - /// Initial values are not fetched, and not notified. - case none - - /// Initial values are immediately fetched, and notified on the current dispatch queue. - case immediateOnCurrentQueue - - /// Initial values are immediately fetched, and asynchronously notified. - case asynchronous -} - -/// The database transaction observer, generic on the type of fetched values. -private class ValuesObserver: TransactionObserver { - private let region: DatabaseRegion - private let future: () -> Future - private let queue: DispatchQueue - private let onChange: (T) -> Void - private let onError: ((Error) -> Void)? - private let notificationQueue = DispatchQueue(label: "ValuesObserver") - private var changed = false - - init( - region: DatabaseRegion, - future: @escaping () -> Future, - queue: DispatchQueue, - onError: ((Error) -> Void)?, - onChange: @escaping (T) -> Void) - { - self.region = region - self.future = future - self.queue = queue - self.onChange = onChange - self.onError = onError - } - - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - return region.isModified(byEventsOfKind: eventKind) - } - - func databaseDidChange(with event: DatabaseEvent) { - if region.isModified(by: event) { - changed = true - stopObservingDatabaseChangesUntilNextTransaction() - } - } - - func databaseDidCommit(_ db: Database) { - guard changed else { - return - } - - changed = false - - // Fetch future results now... - let future = self.future() - - // ...but wait for them in notificationQueue, which guarantees - // that notifications have the same ordering as transactions. - notificationQueue.async { [weak self] in - guard let strongSelf = self else { return } - - do { - // block notificationQueue until the concurrent fetch is done - let result = try future.wait() - strongSelf.queue.async { - guard let strongSelf = self else { return } - strongSelf.onChange(result) - } - } catch { - strongSelf.queue.async { - guard let strongSelf = self else { return } - strongSelf.onError?(error) - } - } - } - } - - func databaseDidRollback(_ db: Database) { - changed = false - } -} - -extension DatabaseWriter { - /// Observe *region*: fetch fresh results each time the database has been - /// modified, and notify them through to the *onChange* closure. - /// - /// - parameters: - /// - region: The database region to observe. - /// - fetch: A closure that fetches results. - /// - queue: The dispatch queue where change callbacks are called. - /// Default is the main queue. - /// - initialDispatch: When `.immediateOnCurrentQueue` (the default), - /// initial values are fetched right away, and the *onChange* callback - /// is called synchronously, on the current dispatch queue. - /// - /// When `.asynchronous`, initial values are fetched right away, and - /// the *onChange* callback is called asynchronously, on *queue*. - /// - /// When `.none`, initial values are not fetched and not notified. - /// - onError: called when results could not be fetched. - /// - onChange: called with fetched results. - func makeValuesObserver( - observing region: (Database) throws -> DatabaseRegion, - extent: Database.TransactionObservationExtent/* = .observerLifetime*/, - fetch: @escaping (Database) throws -> Result, - queue: DispatchQueue = DispatchQueue.main, - initialDispatch: InitialDispatch = .immediateOnCurrentQueue, - onError: ((Error) -> Void)? = nil, - onChange: @escaping (Result) -> Void) throws -> TransactionObserver - { - // Will be set and notified on the caller queue if initialDispatch is .immediateOnCurrentQueue - var immediateValue: Result? = nil - defer { - if let immediateValue = immediateValue { - onChange(immediateValue) - } - } - - // Enter database in order to start observation, and fetch initial - // value if needed. - // - // We use an unsafe reentrant method so that this initializer can be - // called from a database queue. - return try unsafeReentrantWrite { db in - // Start observing the database (take care of future transactions - // that change the observed region). - // - // Observation stops when transactionObserver is deallocated, - // which happens when self is deallocated. - let transactionObserver = try ValuesObserver( - region: region(db), - future: { [unowned self] in self.concurrentRead { try fetch($0) } }, - queue: queue, - onError: onError, - onChange: onChange) - db.add(transactionObserver: transactionObserver, extent: extent) - - switch initialDispatch { - case .none: - break - case .immediateOnCurrentQueue: - immediateValue = try fetch(db) - case .asynchronous: - let initialValue = try fetch(db) - // We're still on the database writer queue. Let's dispatch - // initial value now, before any future transaction has any - // opportunity to trigger a change notification. - queue.async { - onChange(initialValue) - } - } - - return transactionObserver - } - } -} - -// MARK: - DatabaseRegionConvertible Observation - -extension DatabaseWriter { - /// Observe *regions*: fetch fresh results each time the database has been - /// modified, and notify them through to the *onChange* closure. - /// - /// Database observation lasts until the returned observer is deallocated. - /// - /// For example: - /// - /// let observer = try dbQueue.observe( - /// region: Player.all(), - /// andFetch: { db in return try Player.fetchAll(db) }, - /// onChange: { players: [Player] in - /// print("players have changed: \(players)") - /// }) - /// - /// - parameters: - /// - regions: one or more requests. - /// - fetch: block to execute to fetch the data - /// - queue: The dispatch queue where change callbacks are called. - /// Default is the main queue. - /// - initialDispatch: When `.immediateOnCurrentQueue` (the default), - /// initial values are fetched right away, and the *onChange* callback - /// is called synchronously, on the current dispatch queue. - /// - /// When `.asynchronous`, initial values are fetched right away, and - /// the *onChange* callback is called asynchronously, on *queue*. - /// - /// When `.none`, initial values are not fetched and not notified. - /// - onError: called when results could not be fetched. - /// - onChange: called with fetched results. - /// - returns: A new `TransactionObserver` - /// - throws: A DatabaseError whenever an SQLite error occurs. - public func observe( - region regions: DatabaseRegionConvertible..., - extent: Database.TransactionObservationExtent = .observerLifetime, - andFetch fetch: @escaping (Database) throws -> Result, - queue: DispatchQueue = DispatchQueue.main, - initialDispatch: InitialDispatch = .immediateOnCurrentQueue, - onError: ((Error) -> Void)? = nil, - onChange: @escaping (Result) -> Void) - throws -> TransactionObserver - { - func region(_ db: Database) throws -> DatabaseRegion { - return try regions.reduce(into: DatabaseRegion()) { union, region in - try union.formUnion(region.databaseRegion(db)) - } - } - - return try makeValuesObserver( - observing: region, - extent: extent, - fetch: fetch, - queue: queue, - initialDispatch: initialDispatch, - onError: onError, - onChange: onChange) - } -} - -// MARK: - FetchRequest Observation - -extension DatabaseWriter { - /// Observe *request*: calls a closure with fresh results each time the - /// database has been modified. - /// - /// Database observation lasts until the returned observer is deallocated. - /// - /// For example: - /// - /// let observer = try dbQueue.observeCount( - /// from: Player.all(), - /// onChange: { count: Int in - /// print("Number of players have changed: \(count)") - /// }) - /// - /// - parameters: - /// - request: The request to observe. - /// - queue: The dispatch queue where change callbacks are called. - /// Default is the main queue. - /// - initialDispatch: When `.immediateOnCurrentQueue` (the default), - /// initial values are fetched right away, and the *onChange* callback - /// is called synchronously, on the current dispatch queue. - /// - /// When `.asynchronous`, initial values are fetched right away, and - /// the *onChange* callback is called asynchronously, on *queue*. - /// - /// When `.none`, initial values are not fetched and not notified. - /// - onError: called when results could not be fetched. - /// - onChange: called with fetched results. - /// - returns: A new `TransactionObserver` - /// - throws: A DatabaseError whenever an SQLite error occurs. - public func observeCount( - from request: Request, - extent: Database.TransactionObservationExtent = .observerLifetime, - queue: DispatchQueue = DispatchQueue.main, - initialDispatch: InitialDispatch = .immediateOnCurrentQueue, - onError: ((Error) -> Void)? = nil, - onChange: @escaping (Int) -> Void) - throws -> TransactionObserver - where Request: FetchRequest - { - return try makeValuesObserver( - observing: { try request.databaseRegion($0) }, - extent: extent, - fetch: { try request.fetchCount($0) }, - queue: queue, - initialDispatch: initialDispatch, - onError: onError, - onChange: onChange) - } -} - -// MARK: - Row Observation - -extension DatabaseWriter { - /// Observe *request*: calls a closure with fresh results each time the - /// database has been modified. - /// - /// Database observation lasts until the returned observer is deallocated. - /// - /// For example: - /// - /// let observer = try dbQueue.observeAll( - /// from: SQLRequest("SELECT * FROM player"), - /// onChange: { rows: [Row] in - /// print("players have changed: \(rows)") - /// }) - /// - /// - parameters: - /// - request: The request to observe. - /// - queue: The dispatch queue where change callbacks are called. - /// Default is the main queue. - /// - initialDispatch: When `.immediateOnCurrentQueue` (the default), - /// initial values are fetched right away, and the *onChange* callback - /// is called synchronously, on the current dispatch queue. - /// - /// When `.asynchronous`, initial values are fetched right away, and - /// the *onChange* callback is called asynchronously, on *queue*. - /// - /// When `.none`, initial values are not fetched and not notified. - /// - onError: called when results could not be fetched. - /// - onChange: called with fetched results. - /// - returns: A new `TransactionObserver` - /// - throws: A DatabaseError whenever an SQLite error occurs. - public func observeAll( - from request: Request, - extent: Database.TransactionObservationExtent = .observerLifetime, - queue: DispatchQueue = DispatchQueue.main, - initialDispatch: InitialDispatch = .immediateOnCurrentQueue, - onError: ((Error) -> Void)? = nil, - onChange: @escaping ([Row]) -> Void) - throws -> TransactionObserver - where Request: FetchRequest, Request.RowDecoder == Row - { - return try makeValuesObserver( - observing: { try request.databaseRegion($0) }, - extent: extent, - fetch: { try request.fetchAll($0) }, - queue: queue, - initialDispatch: initialDispatch, - onError: onError, - onChange: onChange) - } - - /// Observe *request*: calls a closure with fresh results each time the - /// database has been modified. - /// - /// Database observation lasts until the returned observer is deallocated. - /// - /// For example: - /// - /// let observer = try dbQueue.observeOne( - /// from: SQLRequest("SELECT * FROM player WHERE id = 1"), - /// onChange: { row: Row? in - /// print("player has changed: \(row)") - /// }) - /// - /// - parameters: - /// - request: The request to observe. - /// - queue: The dispatch queue where change callbacks are called. - /// Default is the main queue. - /// - initialDispatch: When `.immediateOnCurrentQueue` (the default), - /// initial values are fetched right away, and the *onChange* callback - /// is called synchronously, on the current dispatch queue. - /// - /// When `.asynchronous`, initial values are fetched right away, and - /// the *onChange* callback is called asynchronously, on *queue*. - /// - /// When `.none`, initial values are not fetched and not notified. - /// - onError: called when results could not be fetched. - /// - onChange: called with fetched results. - /// - returns: A new `TransactionObserver` - /// - throws: A DatabaseError whenever an SQLite error occurs. - public func observeOne( - from request: Request, - extent: Database.TransactionObservationExtent = .observerLifetime, - queue: DispatchQueue = DispatchQueue.main, - initialDispatch: InitialDispatch = .immediateOnCurrentQueue, - onError: ((Error) -> Void)? = nil, - onChange: @escaping (Row?) -> Void) - throws -> TransactionObserver - where Request: FetchRequest, Request.RowDecoder == Row - { - return try makeValuesObserver( - observing: { try request.databaseRegion($0) }, - extent: extent, - fetch: { try request.fetchOne($0) }, - queue: queue, - initialDispatch: initialDispatch, - onError: onError, - onChange: onChange) - } -} - -// MARK: - FetchableRecord Observation - -extension DatabaseWriter { - /// Observe *request*: calls a closure with fresh results each time the - /// database has been modified. - /// - /// Database observation lasts until the returned observer is deallocated. - /// - /// For example: - /// - /// let observer = try dbQueue.observeAll( - /// from: Player.all(), - /// onChange: { players: [Player] in - /// print("players have changed: \(players)") - /// }) - /// - /// - parameters: - /// - request: The request to observe. - /// - queue: The dispatch queue where change callbacks are called. - /// Default is the main queue. - /// - initialDispatch: When `.immediateOnCurrentQueue` (the default), - /// initial values are fetched right away, and the *onChange* callback - /// is called synchronously, on the current dispatch queue. - /// - /// When `.asynchronous`, initial values are fetched right away, and - /// the *onChange* callback is called asynchronously, on *queue*. - /// - /// When `.none`, initial values are not fetched and not notified. - /// - onError: called when results could not be fetched. - /// - onChange: called with fetched results. - /// - returns: A new `TransactionObserver` - /// - throws: A DatabaseError whenever an SQLite error occurs. - public func observeAll( - from request: Request, - extent: Database.TransactionObservationExtent = .observerLifetime, - queue: DispatchQueue = DispatchQueue.main, - initialDispatch: InitialDispatch = .immediateOnCurrentQueue, - onError: ((Error) -> Void)? = nil, - onChange: @escaping ([Request.RowDecoder]) -> Void) - throws -> TransactionObserver - where Request: FetchRequest, Request.RowDecoder: FetchableRecord - { - return try makeValuesObserver( - observing: { try request.databaseRegion($0) }, - extent: extent, - fetch: { try request.fetchAll($0) }, - queue: queue, - initialDispatch: initialDispatch, - onError: onError, - onChange: onChange) - } - - /// Observe *request*: calls a closure with fresh results each time the - /// database has been modified. - /// - /// Database observation lasts until the returned observer is deallocated. - /// - /// For example: - /// - /// let observer = try dbQueue.observeOne( - /// from: Player.filter(key: 1), - /// onChange: { player: Player? in - /// print("player has changed: \(player)") - /// }) - /// - /// - parameters: - /// - request: The request to observe. - /// - queue: The dispatch queue where change callbacks are called. - /// Default is the main queue. - /// - initialDispatch: When `.immediateOnCurrentQueue` (the default), - /// initial values are fetched right away, and the *onChange* callback - /// is called synchronously, on the current dispatch queue. - /// - /// When `.asynchronous`, initial values are fetched right away, and - /// the *onChange* callback is called asynchronously, on *queue*. - /// - /// When `.none`, initial values are not fetched and not notified. - /// - onError: called when results could not be fetched. - /// - onChange: called with fetched results. - /// - returns: A new `TransactionObserver` - /// - throws: A DatabaseError whenever an SQLite error occurs. - public func observeOne( - from request: Request, - extent: Database.TransactionObservationExtent = .observerLifetime, - queue: DispatchQueue = DispatchQueue.main, - initialDispatch: InitialDispatch = .immediateOnCurrentQueue, - onError: ((Error) -> Void)? = nil, - onChange: @escaping (Request.RowDecoder?) -> Void) - throws -> TransactionObserver - where Request: FetchRequest, Request.RowDecoder: FetchableRecord - { - return try makeValuesObserver( - observing: { try request.databaseRegion($0) }, - extent: extent, - fetch: { try request.fetchOne($0) }, - queue: queue, - initialDispatch: initialDispatch, - onError: onError, - onChange: onChange) - } -} - -// MARK: - DatabaseValueConvertible Observation - -extension DatabaseWriter { - /// Observe *request*: calls a closure with fresh results each time the - /// database has been modified. - /// - /// Database observation lasts until the returned observer is deallocated. - /// - /// For example: - /// - /// let request = Player.select(Column("name"), as: String.self) - /// let observer = try dbQueue.observeAll( - /// from: request, - /// onChange: { names: [String] in - /// print("player names have changed: \(names)") - /// }) - /// - /// - parameters: - /// - request: The request to observe. - /// - queue: The dispatch queue where change callbacks are called. - /// Default is the main queue. - /// - initialDispatch: When `.immediateOnCurrentQueue` (the default), - /// initial values are fetched right away, and the *onChange* callback - /// is called synchronously, on the current dispatch queue. - /// - /// When `.asynchronous`, initial values are fetched right away, and - /// the *onChange* callback is called asynchronously, on *queue*. - /// - /// When `.none`, initial values are not fetched and not notified. - /// - onError: called when results could not be fetched. - /// - onChange: called with fetched results. - /// - returns: A new `TransactionObserver` - /// - throws: A DatabaseError whenever an SQLite error occurs. - public func observeAll( - from request: Request, - extent: Database.TransactionObservationExtent = .observerLifetime, - queue: DispatchQueue = DispatchQueue.main, - initialDispatch: InitialDispatch = .immediateOnCurrentQueue, - onError: ((Error) -> Void)? = nil, - onChange: @escaping ([Request.RowDecoder]) -> Void) - throws -> TransactionObserver - where Request: FetchRequest, Request.RowDecoder: DatabaseValueConvertible - { - return try makeValuesObserver( - observing: { try request.databaseRegion($0) }, - extent: extent, - fetch: { try request.fetchAll($0) }, - queue: queue, - initialDispatch: initialDispatch, - onError: onError, - onChange: onChange) - } - - /// Observe *request*: calls a closure with fresh results each time the - /// database has been modified. - /// - /// Database observation lasts until the returned observer is deallocated. - /// - /// For example: - /// - /// let request = Player - /// .filter(key: 1) - /// .select(Column("name"), as: String.self) - /// let observer = try dbQueue.observeOne( - /// from: request, - /// onChange: { name: String? in - /// print("player's name has changed: \(name)") - /// }) - /// - /// - parameters: - /// - request: The request to observe. - /// - queue: The dispatch queue where change callbacks are called. - /// Default is the main queue. - /// - initialDispatch: When `.immediateOnCurrentQueue` (the default), - /// initial values are fetched right away, and the *onChange* callback - /// is called synchronously, on the current dispatch queue. - /// - /// When `.asynchronous`, initial values are fetched right away, and - /// the *onChange* callback is called asynchronously, on *queue*. - /// - /// When `.none`, initial values are not fetched and not notified. - /// - onError: called when results could not be fetched. - /// - onChange: called with fetched results. - /// - returns: A new `TransactionObserver` - /// - throws: A DatabaseError whenever an SQLite error occurs. - public func observeOne( - from request: Request, - extent: Database.TransactionObservationExtent = .observerLifetime, - queue: DispatchQueue = DispatchQueue.main, - initialDispatch: InitialDispatch = .immediateOnCurrentQueue, - onError: ((Error) -> Void)? = nil, - onChange: @escaping (Request.RowDecoder?) -> Void) - throws -> TransactionObserver - where Request: FetchRequest, Request.RowDecoder: DatabaseValueConvertible - { - return try makeValuesObserver( - observing: { try request.databaseRegion($0) }, - extent: extent, - fetch: { try request.fetchOne($0) }, - queue: queue, - initialDispatch: initialDispatch, - onError: onError, - onChange: onChange) - } -} - -// MARK: - Optional DatabaseValueConvertible Observation - -extension DatabaseWriter { - /// Observe *request*: calls a closure with fresh results each time the - /// database has been modified. - /// - /// Database observation lasts until the returned observer is deallocated. - /// - /// For example: - /// - /// let request = Player.select(Column("email"), as: Optional.self) - /// let observer = try dbQueue.observeAll( - /// from: request, - /// onChange: { emails: [String?] in - /// print("player emails have changed: \(names)") - /// }) - /// - /// - parameters: - /// - request: The request to observe. - /// - queue: The dispatch queue where change callbacks are called. - /// Default is the main queue. - /// - initialDispatch: When `.immediateOnCurrentQueue` (the default), - /// initial values are fetched right away, and the *onChange* callback - /// is called synchronously, on the current dispatch queue. - /// - /// When `.asynchronous`, initial values are fetched right away, and - /// the *onChange* callback is called asynchronously, on *queue*. - /// - /// When `.none`, initial values are not fetched and not notified. - /// - onError: called when results could not be fetched. - /// - onChange: called with fetched results. - /// - returns: A new `TransactionObserver` - /// - throws: A DatabaseError whenever an SQLite error occurs. - public func observeAll( - from request: Request, - extent: Database.TransactionObservationExtent = .observerLifetime, - queue: DispatchQueue = DispatchQueue.main, - initialDispatch: InitialDispatch = .immediateOnCurrentQueue, - onError: ((Error) -> Void)? = nil, - onChange: @escaping ([Request.RowDecoder._Wrapped?]) -> Void) - throws -> TransactionObserver - where Request: FetchRequest, Request.RowDecoder: _OptionalProtocol, Request.RowDecoder._Wrapped: DatabaseValueConvertible - { - return try makeValuesObserver( - observing: { try request.databaseRegion($0) }, - extent: extent, - fetch: { try request.fetchAll($0) }, - queue: queue, - initialDispatch: initialDispatch, - onError: onError, - onChange: onChange) - } -} diff --git a/GRDB/Core/ValueObservation.swift b/GRDB/Core/ValueObservation.swift new file mode 100644 index 000000000..0cb695072 --- /dev/null +++ b/GRDB/Core/ValueObservation.swift @@ -0,0 +1,689 @@ +// +// ValueObservation.swift +// GRDB +// +// Created by Gwendal Roué on 23/10/2018. +// Copyright © 2018 Gwendal Roué. All rights reserved. +// + +/// InitialDispatch controls how initial values are dispatched when one starts +/// observing database values. +public enum InitialDispatch { + /// Initial values are not fetched, and not notified. + case none + + /// Initial values are immediately fetched, and notified on the current dispatch queue. + case immediateOnCurrentQueue + + /// Initial values are immediately fetched, and asynchronously notified. + case asynchronous +} + +/// The database transaction observer, generic on the type of fetched values. +private class ValuesObserver: TransactionObserver { + private let region: DatabaseRegion + private let future: () -> Future + private let queue: DispatchQueue + private let onChange: (T) -> Void + private let onError: ((Error) -> Void)? + private let notificationQueue = DispatchQueue(label: "ValuesObserver") + private var changed = false + + init( + region: DatabaseRegion, + future: @escaping () -> Future, + queue: DispatchQueue, + onError: ((Error) -> Void)?, + onChange: @escaping (T) -> Void) + { + self.region = region + self.future = future + self.queue = queue + self.onChange = onChange + self.onError = onError + } + + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { + return region.isModified(byEventsOfKind: eventKind) + } + + func databaseDidChange(with event: DatabaseEvent) { + if region.isModified(by: event) { + changed = true + stopObservingDatabaseChangesUntilNextTransaction() + } + } + + func databaseDidCommit(_ db: Database) { + guard changed else { + return + } + + changed = false + + // Fetch future results now... + let future = self.future() + + // ...but wait for them in notificationQueue, which guarantees + // that notifications have the same ordering as transactions. + notificationQueue.async { [weak self] in + guard let strongSelf = self else { return } + + do { + // block notificationQueue until the concurrent fetch is done + let result = try future.wait() + strongSelf.queue.async { + guard let strongSelf = self else { return } + strongSelf.onChange(result) + } + } catch { + strongSelf.queue.async { + guard let strongSelf = self else { return } + strongSelf.onError?(error) + } + } + } + } + + func databaseDidRollback(_ db: Database) { + changed = false + } +} + +extension DatabaseWriter { + /// TODO + public func add(observation: ValueObservation) throws -> TransactionObserver { + // Will be set and notified on the caller queue if initialDispatch is .immediateOnCurrentQueue + var immediateValue: Value? = nil + defer { + if let immediateValue = immediateValue { + observation.onChange(immediateValue) + } + } + + // Enter database in order to start observation, and fetch initial + // value if needed. + // + // We use an unsafe reentrant method so that this initializer can be + // called from a database queue. + return try unsafeReentrantWrite { db in + // Start observing the database (take care of future transactions + // that change the observed region). + // + // Observation stops when transactionObserver is deallocated, + // which happens when self is deallocated. + let transactionObserver = try ValuesObserver( + region: observation.observedRegion(db), + future: { [unowned self] in self.concurrentRead { try observation.fetch($0) } }, + queue: observation.queue, + onError: observation.onError, + onChange: observation.onChange) + db.add(transactionObserver: transactionObserver, extent: observation.extent) + + switch observation.initialDispatch { + case .none: + break + case .immediateOnCurrentQueue: + immediateValue = try observation.fetch(db) + case .asynchronous: + let initialValue = try observation.fetch(db) + // We're still on the database writer queue. Let's dispatch + // initial value now, before any future transaction has any + // opportunity to trigger a change notification. + observation.queue.async { + observation.onChange(initialValue) + } + } + + return transactionObserver + } + } +} + +/// TODO +public struct ValueObservation { + /// A closure that is evaluated when the observation startst, and returns + /// the observed database region. + var observedRegion: (Database) throws -> DatabaseRegion + + /// The extent of the database observation. The default is + /// `.observerLifetime`: once started, the observation lasts until the + /// observer is deallocated. + var extent = Database.TransactionObservationExtent.observerLifetime + + /// A closure that fetches fresh results whenever the database changes. + var fetch: (Database) throws -> Value + + /// The dispatch queue where change callbacks are called. Default is the + /// main queue. + /// + /// Note that when *initialDispatch* is `.immediateOnCurrentQueue`, the + /// first values are dispatched on the dispatch queue which starts the + /// observation, regardless of this property. + var queue = DispatchQueue.main + + /// `initialDispatch` controls how initial values are dispatched when + /// observation starts. + /// + /// - When `.immediateOnCurrentQueue` (the default), initial values are + /// fetched right away, and the *onChange* callback is called + /// synchronously, on the dispatch queue which starts the observation. + /// + /// - When `.asynchronous`, initial values are fetched right away, and + /// the *onChange* callback is called asynchronously, on *queue*. + /// + /// - When `.none`, initial values are not fetched and not notified. + var initialDispatch = InitialDispatch.immediateOnCurrentQueue + + /// This callback is called when fresh results could not be fetched. + var onError: ((Error) -> Void)? = nil + + /// This callback is called with fresh results whenever the observed + /// database region is impacted by a database transaction. + var onChange: (Value) -> Void + + /// Creates a ValueObservation which observes *region*, and notifies the + /// *onChange* callback with the values returned by the *fetch* closure + /// whenever the observed region is impacted by a database transaction. + /// + /// For example: + /// + /// let observation = ValueObservation( + /// observing: { db in try Player.all().databaseRegion(db) }, + /// fetch: { db in try Player.fetchAll(db) }, + /// onChange: { player: [Player] in print("players have changed") }) + /// let observer = dbQueue.add(observation: observation) + /// // prints "players have changed" + /// + /// Unless further configured: + /// + /// - The observation notifies fresh values on the main queue. + /// - When started with the `add(observation:)` method, fresh values are + /// immediately notified, on the dispatch queue which starts + /// the observation. + /// - The observation lasts until the returned observer is deallocated. + /// + /// See ValueObservation for more information. + /// + /// - parameter region: a closure that returns the observed region. + /// - parameter fetch: a closure that fetches fresh results. + /// - parameter onChange: called with fresh results. + public init( + observing region: @escaping (Database) throws -> DatabaseRegion, + fetch: @escaping (Database) throws -> Value, + onChange: @escaping (Value) -> Void) + { + self.observedRegion = region + self.fetch = fetch + self.onChange = onChange + } +} + +// MARK: - DatabaseRegionConvertible Observation + +extension ValueObservation { + /// Creates a ValueObservation which observes *regions*, and notifies the + /// *onChange* callback with the values returned by the *fetch* closure + /// whenever one of the observed region is impacted by a + /// database transaction. + /// + /// For example: + /// + /// let observation = ValueObservation( + /// observing: Player.all(), + /// fetch: { db in return try Player.fetchAll(db) }, + /// onChange: { player: [Player] in print("players have changed") }) + /// let observer = dbQueue.add(observation: observation) + /// // prints "players have changed" + /// + /// Unless further configured: + /// + /// - The observation notifies fresh values on the main queue. + /// - When started with the `add(observation:)` method, fresh values are + /// immediately notified, on the dispatch queue which starts + /// the observation. + /// - The observation lasts until the returned observer is deallocated. + /// + /// See ValueObservation for more information. + /// + /// - parameter regions: one or more observed requests. + /// - parameter fetch: a closure that fetches fresh results. + /// - parameter onChange: called with fresh results. + public init( + observing regions: DatabaseRegionConvertible..., + fetch: @escaping (Database) throws -> Value, + onChange: @escaping (Value) -> Void) + { + func region(_ db: Database) throws -> DatabaseRegion { + return try regions.reduce(into: DatabaseRegion()) { union, region in + try union.formUnion(region.databaseRegion(db)) + } + } + + self.init(observing: region, fetch: fetch, onChange: onChange) + } +} + +// MARK: - FetchRequest Observation + +extension ValueObservation where Value == Int { + /// Creates a ValueObservation which observes *request*, and notifies the + /// *onChange* callback with the number of fetched values whenever the + /// request is impacted by a database transaction. + /// + /// For example: + /// + /// let request = Player.all() + /// let observation = ValueObservation(count: request) { count: Int in + /// print("number of players has changed") + /// } + /// let observer = dbQueue.add(observation: observation) + /// // prints "number of players has changed" + /// + /// Unless further configured: + /// + /// - The observation notifies fresh values on the main queue. + /// - When started with the `add(observation:)` method, fresh values are + /// immediately notified, on the dispatch queue which starts + /// the observation. + /// - The observation lasts until the returned observer is deallocated. + /// + /// See ValueObservation for more information. + /// + /// - parameter request: the observed request. + /// - parameter onChange: called with fresh results. + /// - returns: a new ValueObservation. + init(count request: Request, onChange: @escaping (Int) -> Void) { + self.init( + observing: request, + fetch: { try request.fetchCount($0) }, + onChange: onChange) + } +} + +extension FetchRequest { + /// Creates a ValueObservation which observes *self*, and notifies the + /// *onChange* callback with the number of fetched values whenever the + /// request is impacted by a database transaction. + /// + /// For example: + /// + /// let request = Player.all() + /// let observation = request.observeCount { count: Int in + /// print("number of players has changed") + /// } + /// let observer = dbQueue.add(observation: observation) + /// // prints "number of players has changed" + /// + /// Unless further configured: + /// + /// - The observation notifies fresh values on the main queue. + /// - When started with the `add(observation:)` method, fresh values are + /// immediately notified, on the dispatch queue which starts + /// the observation. + /// - The observation lasts until the returned observer is deallocated. + /// + /// See ValueObservation for more information. + /// + /// - parameter request: the observed request. + /// - parameter onChange: called with fresh results. + /// - returns: a new ValueObservation. + func observeCount(onChange: @escaping (Int) -> Void) -> ValueObservation { + return ValueObservation( + observing: self, + fetch: { try self.fetchCount($0) }, + onChange: onChange) + } +} + +// MARK: - Row Observation + +extension ValueObservation where Value == [Row] { + /// Creates a ValueObservation which observes *request*, and notifies the + /// *onChange* callback with fetched rows whenever the request is impacted + /// by a database transaction. + /// + /// For example: + /// + /// let request = SQLRequest("SELECT * FROM player") + /// let observation = ValueObservation(all: request) { rows: [Row] in + /// print("players have changed") + /// } + /// let observer = dbQueue.add(observation: observation) + /// // prints "players have changed" + /// + /// Unless further configured: + /// + /// - The observation notifies fresh values on the main queue. + /// - When started with the `add(observation:)` method, fresh values are + /// immediately notified, on the dispatch queue which starts + /// the observation. + /// - The observation lasts until the returned observer is deallocated. + /// + /// See ValueObservation for more information. + /// + /// - parameter request: the observed request. + /// - parameter onChange: called with fresh results. + /// - returns: a new ValueObservation. + init(all request: Request, onChange: @escaping ([Row]) -> Void) where Request.RowDecoder == Row { + self.init( + observing: request, + fetch: { try request.fetchAll($0) }, + onChange: onChange) + } +} + +extension ValueObservation where Value == Row? { + /// Creates a ValueObservation which observes *request*, and notifies the + /// *onChange* callback with fetched rows whenever the request is impacted + /// by a database transaction. + /// + /// For example: + /// + /// let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1]) + /// let observation = ValueObservation(one: request) { row: Row? in + /// print("players have changed") + /// } + /// let observer = dbQueue.add(observation: observation) + /// // prints "players have changed" + /// + /// Unless further configured: + /// + /// - The observation notifies fresh values on the main queue. + /// - When started with the `add(observation:)` method, fresh values are + /// immediately notified, on the dispatch queue which starts + /// the observation. + /// - The observation lasts until the returned observer is deallocated. + /// + /// See ValueObservation for more information. + /// + /// - parameter request: the observed request. + /// - parameter onChange: called with fresh results. + /// - returns: a new ValueObservation. + init(one request: Request, onChange: @escaping (Row?) -> Void) where Request.RowDecoder == Row { + self.init( + observing: request, + fetch: { try request.fetchOne($0) }, + onChange: onChange) + } +} + +extension FetchRequest where RowDecoder == Row { + /// Creates a ValueObservation which observes *self*, and notifies the + /// *onChange* callback with fetched rows whenever the request is impacted + /// by a database transaction. + /// + /// For example: + /// + /// let request = SQLRequest("SELECT * FROM player") + /// let observation = request.observeAll { rows: [Row] in + /// print("players have changed") + /// } + /// let observer = dbQueue.add(observation: observation) + /// // prints "players have changed" + /// + /// Unless further configured: + /// + /// - The observation notifies fresh values on the main queue. + /// - When started with the `add(observation:)` method, fresh values are + /// immediately notified, on the dispatch queue which starts + /// the observation. + /// - The observation lasts until the returned observer is deallocated. + /// + /// See ValueObservation for more information. + /// + /// - parameter request: the observed request. + /// - parameter onChange: called with fresh results. + /// - returns: a new ValueObservation. + func observeAll(onChange: @escaping ([Row]) -> Void) -> ValueObservation<[Row]> { + return ValueObservation( + observing: self, + fetch: { try self.fetchAll($0) }, + onChange: onChange) + } + + /// Creates a ValueObservation which observes *self*, and notifies the + /// *onChange* callback with a fetched row whenever the request is impacted + /// by a database transaction. + /// + /// For example: + /// + /// let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1]) + /// let observation = request.observeOne { row: Row? in + /// print("player has changed") + /// } + /// let observer = dbQueue.add(observation: observation) + /// // prints "player has changed" + /// + /// Unless further configured: + /// + /// - The observation notifies fresh values on the main queue. + /// - When started with the `add(observation:)` method, fresh values are + /// immediately notified, on the dispatch queue which starts + /// the observation. + /// - The observation lasts until the returned observer is deallocated. + /// + /// See ValueObservation for more information. + /// + /// - parameter request: the observed request. + /// - parameter onChange: called with fresh results. + /// - returns: a new ValueObservation. + func observeOne(onChange: @escaping (Row?) -> Void) -> ValueObservation { + return ValueObservation( + observing: self, + fetch: { try self.fetchOne($0) }, + onChange: onChange) + } +} + +// MARK: - FetchableRecord Observation + +extension DatabaseWriter { + /// Observe *request*: calls a closure with fresh results each time the + /// database has been modified. + /// + /// Database observation lasts until the returned observer is deallocated. + /// + /// For example: + /// + /// let observer = try dbQueue.observeAll( + /// from: Player.all(), + /// onChange: { players: [Player] in + /// print("players have changed: \(players)") + /// }) + /// + /// - parameters: + /// - request: The request to observe. + /// - onChange: called with fresh results. + /// - returns: A new `TransactionObserver` + /// - throws: A DatabaseError whenever an SQLite error occurs. + public func observeAll( + from request: Request, + extent: Database.TransactionObservationExtent = .observerLifetime, + queue: DispatchQueue = DispatchQueue.main, + initialDispatch: InitialDispatch = .immediateOnCurrentQueue, + onError: ((Error) -> Void)? = nil, + onChange: @escaping ([Request.RowDecoder]) -> Void) + throws -> TransactionObserver + where Request: FetchRequest, Request.RowDecoder: FetchableRecord + { + var observation = ValueObservation( + observing: { try request.databaseRegion($0) }, + fetch: { try request.fetchAll($0) }, + onChange: onChange) + observation.extent = extent + observation.queue = queue + observation.initialDispatch = initialDispatch + observation.onError = onError + return try add(observation: observation) + } + + /// Observe *request*: calls a closure with fresh results each time the + /// database has been modified. + /// + /// Database observation lasts until the returned observer is deallocated. + /// + /// For example: + /// + /// let observer = try dbQueue.observeOne( + /// from: Player.filter(key: 1), + /// onChange: { player: Player? in + /// print("player has changed: \(player)") + /// }) + /// + /// - parameters: + /// - request: The request to observe. + /// - onChange: called with fresh results. + /// - returns: A new `TransactionObserver` + /// - throws: A DatabaseError whenever an SQLite error occurs. + public func observeOne( + from request: Request, + extent: Database.TransactionObservationExtent = .observerLifetime, + queue: DispatchQueue = DispatchQueue.main, + initialDispatch: InitialDispatch = .immediateOnCurrentQueue, + onError: ((Error) -> Void)? = nil, + onChange: @escaping (Request.RowDecoder?) -> Void) + throws -> TransactionObserver + where Request: FetchRequest, Request.RowDecoder: FetchableRecord + { + var observation = ValueObservation( + observing: { try request.databaseRegion($0) }, + fetch: { try request.fetchOne($0) }, + onChange: onChange) + observation.extent = extent + observation.queue = queue + observation.initialDispatch = initialDispatch + observation.onError = onError + return try add(observation: observation) + } +} + +// MARK: - DatabaseValueConvertible Observation + +extension DatabaseWriter { + /// Observe *request*: calls a closure with fresh results each time the + /// database has been modified. + /// + /// Database observation lasts until the returned observer is deallocated. + /// + /// For example: + /// + /// let request = Player.select(Column("name"), as: String.self) + /// let observer = try dbQueue.observeAll( + /// from: request, + /// onChange: { names: [String] in + /// print("player names have changed: \(names)") + /// }) + /// + /// - parameters: + /// - request: The request to observe. + /// - onChange: called with fresh results. + /// - returns: A new `TransactionObserver` + /// - throws: A DatabaseError whenever an SQLite error occurs. + public func observeAll( + from request: Request, + extent: Database.TransactionObservationExtent = .observerLifetime, + queue: DispatchQueue = DispatchQueue.main, + initialDispatch: InitialDispatch = .immediateOnCurrentQueue, + onError: ((Error) -> Void)? = nil, + onChange: @escaping ([Request.RowDecoder]) -> Void) + throws -> TransactionObserver + where Request: FetchRequest, Request.RowDecoder: DatabaseValueConvertible + { + var observation = ValueObservation( + observing: { try request.databaseRegion($0) }, + fetch: { try request.fetchAll($0) }, + onChange: onChange) + observation.extent = extent + observation.queue = queue + observation.initialDispatch = initialDispatch + observation.onError = onError + return try add(observation: observation) + } + + /// Observe *request*: calls a closure with fresh results each time the + /// database has been modified. + /// + /// Database observation lasts until the returned observer is deallocated. + /// + /// For example: + /// + /// let request = Player + /// .filter(key: 1) + /// .select(Column("name"), as: String.self) + /// let observer = try dbQueue.observeOne( + /// from: request, + /// onChange: { name: String? in + /// print("player's name has changed: \(name)") + /// }) + /// + /// - parameters: + /// - request: The request to observe. + /// - onChange: called with fresh results. + /// - returns: A new `TransactionObserver` + /// - throws: A DatabaseError whenever an SQLite error occurs. + public func observeOne( + from request: Request, + extent: Database.TransactionObservationExtent = .observerLifetime, + queue: DispatchQueue = DispatchQueue.main, + initialDispatch: InitialDispatch = .immediateOnCurrentQueue, + onError: ((Error) -> Void)? = nil, + onChange: @escaping (Request.RowDecoder?) -> Void) + throws -> TransactionObserver + where Request: FetchRequest, Request.RowDecoder: DatabaseValueConvertible + { + var observation = ValueObservation( + observing: { try request.databaseRegion($0) }, + fetch: { try request.fetchOne($0) }, + onChange: onChange) + observation.extent = extent + observation.queue = queue + observation.initialDispatch = initialDispatch + observation.onError = onError + return try add(observation: observation) + } +} + +// MARK: - Optional DatabaseValueConvertible Observation + +extension DatabaseWriter { + /// Observe *request*: calls a closure with fresh results each time the + /// database has been modified. + /// + /// Database observation lasts until the returned observer is deallocated. + /// + /// For example: + /// + /// let request = Player.select(Column("email"), as: Optional.self) + /// let observer = try dbQueue.observeAll( + /// from: request, + /// onChange: { emails: [String?] in + /// print("player emails have changed: \(names)") + /// }) + /// + /// - parameters: + /// - request: The request to observe. + /// - onChange: called with fresh results. + /// - returns: A new `TransactionObserver` + /// - throws: A DatabaseError whenever an SQLite error occurs. + public func observeAll( + from request: Request, + extent: Database.TransactionObservationExtent = .observerLifetime, + queue: DispatchQueue = DispatchQueue.main, + initialDispatch: InitialDispatch = .immediateOnCurrentQueue, + onError: ((Error) -> Void)? = nil, + onChange: @escaping ([Request.RowDecoder._Wrapped?]) -> Void) + throws -> TransactionObserver + where Request: FetchRequest, Request.RowDecoder: _OptionalProtocol, Request.RowDecoder._Wrapped: DatabaseValueConvertible + { + var observation = ValueObservation( + observing: { try request.databaseRegion($0) }, + fetch: { try request.fetchAll($0) }, + onChange: onChange) + observation.extent = extent + observation.queue = queue + observation.initialDispatch = initialDispatch + observation.onError = onError + return try add(observation: observation) + } +} diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 29ac9bf88..1c579c2d0 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -180,8 +180,8 @@ 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 /* FetchResultsObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06B4217F3C5900B38F35 /* FetchResultsObserver.swift */; }; - 563B06B7217F3C5A00B38F35 /* FetchResultsObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06B4217F3C5900B38F35 /* FetchResultsObserver.swift */; }; + 563B06B6217F3C5A00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06B4217F3C5900B38F35 /* ValueObservation.swift */; }; + 563B06B7217F3C5A00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06B4217F3C5900B38F35 /* ValueObservation.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 */; }; @@ -990,7 +990,7 @@ 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 /* FetchResultsObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchResultsObserver.swift; sourceTree = ""; }; + 563B06B4217F3C5900B38F35 /* ValueObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservation.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 = ""; }; @@ -1762,7 +1762,6 @@ 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */, 563363C31C942C37000BE133 /* DatabaseWriter.swift */, 5636E9BB1D22574100B9B05F /* FetchRequest.swift */, - 563B06B4217F3C5900B38F35 /* FetchResultsObserver.swift */, 56A238761B9C75030082EB20 /* Row.swift */, 567404871CEF84C8003ED5CC /* RowAdapter.swift */, 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */, @@ -1772,6 +1771,7 @@ 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, 5605F1471C672E4000235C62 /* Support */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, + 563B06B4217F3C5900B38F35 /* ValueObservation.swift */, ); path = Core; sourceTree = ""; @@ -2248,7 +2248,7 @@ 5644DE7C20F8C903001FFDDE /* DatabaseValueConversion.swift in Sources */, 560FC5321CB003810014AA8E /* DatabasePool.swift in Sources */, 560FC5331CB003810014AA8E /* Migration.swift in Sources */, - 563B06B6217F3C5A00B38F35 /* FetchResultsObserver.swift in Sources */, + 563B06B6217F3C5A00B38F35 /* ValueObservation.swift in Sources */, 560FC5341CB003810014AA8E /* QueryInterfaceQuery.swift in Sources */, 566B912C1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 560FC5351CB003810014AA8E /* Statement.swift in Sources */, @@ -2698,7 +2698,7 @@ 5644DE7D20F8C903001FFDDE /* DatabaseValueConversion.swift in Sources */, 56AFCA071CB1A8BB00F48B96 /* DatabasePool.swift in Sources */, 56AFCA081CB1A8BB00F48B96 /* Statement.swift in Sources */, - 563B06B7217F3C5A00B38F35 /* FetchResultsObserver.swift in Sources */, + 563B06B7217F3C5A00B38F35 /* ValueObservation.swift in Sources */, 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceQuery.swift in Sources */, 566B912F1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56AFCA0A1CB1A8BB00F48B96 /* Migration.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 4fcd90a72..19dfe3741 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -43,8 +43,8 @@ 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 /* FetchResultsObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06B8217F3C6E00B38F35 /* FetchResultsObserver.swift */; }; - 563B06BB217F3C6E00B38F35 /* FetchResultsObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06B8217F3C6E00B38F35 /* FetchResultsObserver.swift */; }; + 563B06BA217F3C6E00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06B8217F3C6E00B38F35 /* ValueObservation.swift */; }; + 563B06BB217F3C6E00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06B8217F3C6E00B38F35 /* ValueObservation.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 */; }; @@ -651,7 +651,7 @@ 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 /* FetchResultsObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchResultsObserver.swift; sourceTree = ""; }; + 563B06B8217F3C6E00B38F35 /* ValueObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservation.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 = ""; }; @@ -1396,7 +1396,6 @@ 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */, 563363C31C942C37000BE133 /* DatabaseWriter.swift */, 5636E9BB1D22574100B9B05F /* FetchRequest.swift */, - 563B06B8217F3C6E00B38F35 /* FetchResultsObserver.swift */, 56A238761B9C75030082EB20 /* Row.swift */, 567404871CEF84C8003ED5CC /* RowAdapter.swift */, 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */, @@ -1406,6 +1405,7 @@ 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, 5605F1471C672E4000235C62 /* Support */, 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, + 563B06B8217F3C6E00B38F35 /* ValueObservation.swift */, ); path = Core; sourceTree = ""; @@ -1911,7 +1911,7 @@ 5644DE7920F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */, 56DAA2E01DE9C827006E10C8 /* Cursor.swift in Sources */, F3BA800C1CFB286F003DC1BA /* DatabaseError.swift in Sources */, - 563B06BB217F3C6E00B38F35 /* FetchResultsObserver.swift in Sources */, + 563B06BB217F3C6E00B38F35 /* ValueObservation.swift in Sources */, 566B91301FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA80221CFB288C003DC1BA /* NSNumber.swift in Sources */, 5653EB4620961F6100F46237 /* AssociationQuery.swift in Sources */, @@ -2194,7 +2194,7 @@ 5644DE7820F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */, 56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */, F3BA80681CFB2E55003DC1BA /* DatabaseError.swift in Sources */, - 563B06BA217F3C6E00B38F35 /* FetchResultsObserver.swift in Sources */, + 563B06BA217F3C6E00B38F35 /* ValueObservation.swift in Sources */, 566B912D1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA807E1CFB2E61003DC1BA /* NSNumber.swift in Sources */, 5653EB4520961F6100F46237 /* AssociationQuery.swift in Sources */,