From 0df481508661aafce4e4547f795f44c5174d8660 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 25 Oct 2018 20:39:04 +0200 Subject: [PATCH] Move ValueObservation support to DatabaseReader --- GRDB/Core/DatabaseReader.swift | 19 +++++ GRDB/Core/DatabaseSnapshot.swift | 56 +++++++------ GRDB/Core/DatabaseWriter.swift | 125 +++++++++++++++++++++++++++++ GRDB/Core/ValueObservation.swift | 130 +------------------------------ 4 files changed, 179 insertions(+), 151 deletions(-) diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 9e17ef96b..42c2c90e8 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -149,6 +149,14 @@ public protocol DatabaseReader : class { /// Remove a collation. func remove(collation: DatabaseCollation) + + // MARK: - Value Observation + + /// TODO + func add( + observation: ValueObservation, + onError: ((Error) -> Void)?, + onChange: @escaping (Value) -> Void) throws -> TransactionObserver } extension DatabaseReader { @@ -228,4 +236,15 @@ public final class AnyDatabaseReader : DatabaseReader { public func remove(collation: DatabaseCollation) { base.remove(collation: collation) } + + // MARK: - Value Observation + + /// TODO + public func add( + observation: ValueObservation, + onError: ((Error) -> Void)? = nil, + onChange: @escaping (Value) -> Void) throws -> TransactionObserver + { + return try base.add(observation: observation, onError: onError, onChange: onChange) + } } diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 423822fcf..e720e89ab 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -81,45 +81,55 @@ 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)? = nil, + onChange: @escaping (Value) -> Void) throws -> TransactionObserver + { + // Deal with initial value + switch observation.initialDispatch { + case .none: + break + case .deferred: + let initialValue = try unsafeReentrantRead { try observation.read($0) } + observation.queue.async { + onChange(initialValue) + } + case .immediateOnCurrentQueue: + let initialValue = try unsafeReentrantRead { try observation.read($0) } + onChange(initialValue) + } + + // Return a dummy observer, because snapshots never change + return SnapshotValueObserver() + } } +/// 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..07265459c 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -229,6 +229,131 @@ extension DatabaseWriter { } } +/// The database transaction observer, support for ValueObservation. +private class ValueObserver: TransactionObserver { + private let region: DatabaseRegion + private let future: () -> Future + private let queue: DispatchQueue + private let onChange: (Value) -> Void + private let onError: ((Error) -> Void)? + private let notificationQueue = DispatchQueue(label: "ValueObserver") + private var changed = false + + init( + region: DatabaseRegion, + future: @escaping () -> Future, + queue: DispatchQueue, + onError: ((Error) -> Void)?, + onChange: @escaping (Value) -> 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 value now, from the database writer queue + let futureValue = future() + + // Wait for future value in notificationQueue, in order to guarantee + // that notifications have the same ordering as transactions. + notificationQueue.async { [weak self] in + guard let strongSelf = self else { return } + + do { + let value = try futureValue.wait() + strongSelf.queue.async { + guard let strongSelf = self else { return } + strongSelf.onChange(value) + } + } catch { + strongSelf.queue.async { + guard let strongSelf = self else { return } + strongSelf.onError?(error) + } + } + } + } + + func databaseDidRollback(_ db: Database) { + changed = false + } +} + +extension DatabaseWriter { + public func add( + observation: ValueObservation, + onError: ((Error) -> Void)? = nil, + onChange: @escaping (Value) -> Void) + throws -> TransactionObserver + { + // Will be set and notified on the caller queue if initialDispatch is .immediateOnCurrentQueue + var immediateValue: Value? = 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 ValueObserver( + region: observation.observedRegion(db), + future: { [unowned self] in self.concurrentRead { try observation.read($0) } }, + queue: observation.queue, + onError: onError, + onChange: onChange) + db.add(transactionObserver: transactionObserver, extent: observation.extent) + + switch observation.initialDispatch { + case .none: + break + case .immediateOnCurrentQueue: + immediateValue = try observation.read(db) + case .deferred: + // We're still on the database writer queue. Let's dispatch + // initial value right now, before any future transaction has + // any opportunity to trigger a change notification, and mess + // with the ordering of value notifications. + let initialValue = try observation.read(db) + observation.queue.async { + onChange(initialValue) + } + } + + return transactionObserver + } + } +} + /// A future value. public class Future { private var consumed = false diff --git a/GRDB/Core/ValueObservation.swift b/GRDB/Core/ValueObservation.swift index 8e60c5b5a..b6630bf95 100644 --- a/GRDB/Core/ValueObservation.swift +++ b/GRDB/Core/ValueObservation.swift @@ -19,140 +19,14 @@ public enum InitialDispatch { case deferred } -/// The database transaction observer, generic on the type of fetched values. -private class ValueObserver: 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: "ValueObserver") - 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, - onError: ((Error) -> Void)? = nil, - onChange: @escaping (Value) -> Void) - throws -> TransactionObserver - { - // Will be set and notified on the caller queue if initialDispatch is .immediateOnCurrentQueue - var immediateValue: Value? = 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 ValueObserver( - region: observation.observedRegion(db), - future: { [unowned self] in self.concurrentRead { try observation.read($0) } }, - queue: observation.queue, - onError: onError, - onChange: onChange) - db.add(transactionObserver: transactionObserver, extent: observation.extent) - - switch observation.initialDispatch { - case .none: - break - case .immediateOnCurrentQueue: - immediateValue = try observation.read(db) - case .deferred: - let initialValue = try observation.read(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 { - onChange(initialValue) - } - } - - return transactionObserver - } - } -} - /// TODO public struct ValueObservation { /// A closure that is evaluated when the observation startst, and returns /// the observed database region. - fileprivate var observedRegion: (Database) throws -> DatabaseRegion + var observedRegion: (Database) throws -> DatabaseRegion /// A closure that fetches fresh results whenever the database changes. - fileprivate var read: (Database) throws -> Value + var read: (Database) throws -> Value /// The extent of the database observation. The default is /// `.observerLifetime`: once started, the observation lasts until the