Documentation

This commit is contained in:
Gwendal Roué committed 2020-07-12 14:17:58 +02:00
1 parent 519410fc3a
commit 07092169bf
30 files changed
+180 -140

No files matched your search

+3 -3
View File
@@ -806,7 +806,7 @@ extension DatabasePool: DatabaseReader {
// MARK: - Database Observation
/// :nodoc:
public func _add<Reducer: _ValueReducer>(
public func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
@@ -836,7 +836,7 @@ extension DatabasePool: DatabaseReader {
/// A concurrent observation fetches the initial value without waiting for
/// the writer.
private func _addConcurrent<Reducer: _ValueReducer>(
private func _addConcurrent<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
@@ -926,7 +926,7 @@ extension DatabasePool: DatabaseReader {
}
// Support for _addConcurrent(observation:)
private func add<Reducer: _ValueReducer>(
private func add<Reducer: ValueReducer>(
observer: ValueObserver<Reducer>,
from initialSnapshot: DatabaseSnapshot)
{
+1 -1
View File
@@ -473,7 +473,7 @@ extension DatabaseQueue {
// MARK: - Database Observation
/// :nodoc:
public func _add<Reducer: _ValueReducer>(
public func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
+8 -7
View File
@@ -3,16 +3,17 @@ import Combine
#endif
import Dispatch
/// The protocol for all types that can fetch values from a database.
/// `DatabaseReader` is the protocol for all types that can fetch values from
/// an SQLite database.
///
/// It is adopted by DatabaseQueue and DatabasePool.
/// It is adopted by `DatabaseQueue`, `DatabasePool`, and `DatabaseSnapshot`.
///
/// The protocol comes with isolation guarantees that describe the behavior of
/// adopting types in a multithreaded application.
///
/// Types that adopt the protocol can provide in practice stronger guarantees.
/// For example, DatabaseQueue provides a stronger isolation level
/// than DatabasePool.
/// For example, `DatabaseQueue` provides a stronger isolation level
/// than `DatabasePool`.
///
/// **Warning**: Isolation guarantees stand as long as there is no external
/// connection to the database. Should you have to cope with external
@@ -252,7 +253,7 @@ public protocol DatabaseReader: AnyObject {
/// - returns: a TransactionObserver
///
/// :nodoc:
func _add<Reducer: _ValueReducer>(
func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
@@ -378,7 +379,7 @@ extension DatabaseReader {
/// Adding an observation in a read-only database emits only the
/// initial value.
func _addReadOnly<Reducer: _ValueReducer>(
func _addReadOnly<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
@@ -486,7 +487,7 @@ public final class AnyDatabaseReader: DatabaseReader {
// MARK: - Value Observation
/// :nodoc:
public func _add<Reducer: _ValueReducer>(
public func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
+4
View File
@@ -315,6 +315,10 @@ private struct TableRegion: Equatable {
// MARK: - DatabaseRegionConvertible
/// `DatabaseRegionConvertible` is the protocol for values that can be turned
/// into a `DatabaseRegion`.
///
/// Such values specify the region obserbed by `DatabaseRegionObservation`.
public protocol DatabaseRegionConvertible {
/// Returns a database region.
///
+1 -1
View File
@@ -151,7 +151,7 @@ extension DatabaseSnapshot {
// MARK: - Database Observation
/// :nodoc:
public func _add<Reducer: _ValueReducer>(
public func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
+11 -10
View File
@@ -3,16 +3,17 @@ import Combine
#endif
import Dispatch
/// The protocol for all types that can update a database.
/// `DatabaseWriter` is the protocol for all types that can write into an
/// SQLite database.
///
/// It is adopted by DatabaseQueue and DatabasePool.
/// It is adopted by `DatabaseQueue` and `DatabasePool`.
///
/// The protocol comes with isolation guarantees that describe the behavior of
/// adopting types in a multithreaded application.
///
/// Types that adopt the protocol can in practice provide stronger guarantees.
/// For example, DatabaseQueue provides a stronger isolation level
/// than DatabasePool.
/// For example, `DatabaseQueue` provides a stronger isolation level
/// than `DatabasePool`.
///
/// **Warning**: Isolation guarantees stand as long as there is no external
/// connection to the database. Should you have to cope with external
@@ -312,7 +313,7 @@ extension DatabaseWriter {
// MARK: - Database Observation
/// A write-only observation only uses the serialized writer
func _addWriteOnly<Reducer: _ValueReducer>(
func _addWriteOnly<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
@@ -488,10 +489,10 @@ extension DatabasePublishers {
///
/// See:
///
/// - `DatabaseReader.writePublisher(updates:)`.
/// - `DatabaseReader.writePublisher(updates:thenRead:)`.
/// - `DatabaseReader.writePublisher(receiveOn:updates:)`.
/// - `DatabaseReader.writePublisher(receiveOn:updates:thenRead:)`.
/// - `DatabaseWriter.writePublisher(updates:)`.
/// - `DatabaseWriter.writePublisher(updates:thenRead:)`.
/// - `DatabaseWriter.writePublisher(receiveOn:updates:)`.
/// - `DatabaseWriter.writePublisher(receiveOn:updates:thenRead:)`.
public struct Write<Output>: Publisher {
public typealias Output = Output
public typealias Failure = Error
@@ -662,7 +663,7 @@ public final class AnyDatabaseWriter: DatabaseWriter {
// MARK: - Database Observation
/// :nodoc:
public func _add<Reducer: _ValueReducer>(
public func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
+2 -1
View File
@@ -1,6 +1,6 @@
// MARK: - FetchRequest
/// Implementation details of FetchRequest.
/// Implementation details of `FetchRequest`.
///
/// :nodoc:
public protocol _FetchRequest {
@@ -15,6 +15,7 @@ public protocol _FetchRequest {
/// let request: ... // Some FetchRequest that fetches Player
/// try request.fetchCursor(db) // Cursor of Player
/// try request.fetchAll(db) // [Player]
/// try request.fetchSet(db) // Set<Player>
/// try request.fetchOne(db) // Player?
/// try request.fetchCount(db) // Int
public protocol FetchRequest: _FetchRequest, DatabaseRegionConvertible, SQLExpression, SQLCollection {
+1 -1
View File
@@ -877,7 +877,7 @@ typealias StatementObservation = (TransactionObservation, DatabaseEventPredicate
// MARK: - Database events
/// A kind of database event. See the TransactionObserver protocol for
/// A kind of database event. See the `TransactionObserver` protocol for
/// more information.
public enum DatabaseEventKind {
/// The insertion of a row in a database table
+8 -11
View File
@@ -20,8 +20,8 @@ extension AnyFetchRequest {
}
@available(*, unavailable, message: "Custom reducers are no longer supported. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
public struct AnyValueReducer<Fetched, Value>: _ValueReducer {
public var isSelectedRegionDeterministic: Bool
public struct AnyValueReducer<Fetched, Value>: ValueReducer {
public var _isSelectedRegionDeterministic: Bool
{ preconditionFailure() }
public init(fetch: @escaping (Database) throws -> Fetched, value: @escaping (Fetched) -> Value?)
@@ -30,10 +30,10 @@ public struct AnyValueReducer<Fetched, Value>: _ValueReducer {
public init<Base: _ValueReducer>(_ reducer: Base) where Base.Fetched == Fetched, Base.Value == Value
{ preconditionFailure() }
public func fetch(_ db: Database) throws -> Fetched
public func _fetch(_ db: Database) throws -> Fetched
{ preconditionFailure() }
public func value(_ fetched: Fetched) -> Value?
public func _value(_ fetched: Fetched) -> Value?
{ preconditionFailure() }
}
@@ -522,20 +522,17 @@ extension ValueObservation where Reducer.Value: Equatable {
extension ValueReducers {
@available(*, unavailable)
public enum Unavailable<T>: _ValueReducer {
public var isSelectedRegionDeterministic: Bool
public enum Unavailable<T>: ValueReducer {
public var _isSelectedRegionDeterministic: Bool
{ preconditionFailure() }
public func fetch(_ db: Database) throws -> Never
public func _fetch(_ db: Database) throws -> Never
{ preconditionFailure() }
public mutating func value(_ fetched: Never) -> T? { }
public mutating func _value(_ fetched: Never) -> T? { }
}
}
@available(*, unavailable, message: "Custom reducers are no longer supported. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
typealias ValueReducer = _ValueReducer
@available(*, unavailable, message: "ValueObservation now schedules its values asynchronously on the main queue by default. See ValueObservation.start() for possible configuration")
enum ValueScheduling {
case mainQueue
@@ -1,6 +1,6 @@
import Foundation
/// Implementation details of Association.
/// Implementation details of `Association`.
///
/// :nodoc:
public protocol _Association {
@@ -493,7 +493,7 @@ extension OrderedRequest {
// MARK: - JoinableRequest
/// Implementation details of the JoinableRequest protocol.
/// Implementation details of `JoinableRequest`.
///
/// :nodoc:
public protocol _JoinableRequest {
+1 -1
View File
@@ -1,6 +1,6 @@
// MARK: - SQLCollection
/// Implementation details of SQLCollection.
/// Implementation details of `SQLCollection`.
///
/// :nodoc:
public protocol _SQLCollection {
+1 -1
View File
@@ -1,6 +1,6 @@
// MARK: - SQLExpression
/// Implementation details of SQLExpression.
/// Implementation details of `SQLExpression`.
///
/// :nodoc:
public protocol _SQLExpression {
+32 -6
View File
@@ -182,22 +182,48 @@ extension SQLSpecificExpressible {
// MARK: - Date functions
/// A date modifier for SQLite date functions.
/// A date modifier for SQLite date functions such as `julianDay(_:_:)` and
/// `dateTime(_:_:)`.
///
/// For more information, see https://www.sqlite.org/lang_datefunc.html
public enum SQLDateModifier: SQLExpression {
case day(Int)
case hour(Int)
case minute(Int)
/// Adds the specified amount of seconds
case second(Double)
/// Adds the specified amount of minutes
case minute(Int)
/// Adds the specified amount of hours
case hour(Int)
/// Adds the specified amount of days
case day(Int)
/// Adds the specified amount of months
case month(Int)
/// Adds the specified amount of years
case year(Int)
case startOfMonth
case startOfYear
/// Shifts the date backwards to the beginning of the current day
case startOfDay
/// Shifts the date backwards to the beginning of the current month
case startOfMonth
/// Shifts the date backwards to the beginning of the current year
case startOfYear
/// See https://www.sqlite.org/lang_datefunc.html
case weekday(Int)
/// See https://www.sqlite.org/lang_datefunc.html
case unixEpoch
/// See https://www.sqlite.org/lang_datefunc.html
case localTime
/// See https://www.sqlite.org/lang_datefunc.html
case utc
var rawValue: String {
+1 -2
View File
@@ -1,6 +1,6 @@
// MARK: - SQLOrderingTerm
/// Implementation details of SQLOrderingTerm.
/// Implementation details of `SQLOrderingTerm`.
///
/// :nodoc:
public protocol _SQLOrderingTerm {
@@ -16,7 +16,6 @@ public protocol _SQLOrderingTerm {
/// The protocol for all types that can be used as an SQL ordering term, as
/// described at https://www.sqlite.org/syntax/ordering-term.html
///
public protocol SQLOrderingTerm: _SQLOrderingTerm { }
// MARK: - _SQLOrdering
+1 -1
View File
@@ -1,6 +1,6 @@
// MARK: - SQLSelectable
/// Implementation details of SQLSelectable.
/// Implementation details of `SQLSelectable`.
///
/// :nodoc:
public protocol _SQLSelectable {
+6 -6
View File
@@ -313,13 +313,13 @@ extension Row {
// MARK: - DatabaseDateEncodingStrategy
/// DatabaseDateEncodingStrategy specifies how EncodableRecord types that also
/// adopt the standard Encodable protocol encode their date properties.
/// `DatabaseDateEncodingStrategy` specifies how `EncodableRecord` types that
/// also adopt the standard `Encodable` protocol encode their `Date` properties.
///
/// For example:
///
/// struct Player: EncodableRecord, Encodable {
/// static let databaseDateEncodingStrategy: DatabaseDateEncodingStrategy = .timeIntervalSince1970
/// static let databaseDateEncodingStrategy = DatabaseDateEncodingStrategy.timeIntervalSince1970
///
/// var name: String
/// var registrationDate: Date // encoded as an epoch timestamp
@@ -360,13 +360,13 @@ public enum DatabaseDateEncodingStrategy {
// MARK: - DatabaseUUIDEncodingStrategy
/// DatabaseUUIDEncodingStrategy specifies how EncodableRecord types that also
/// adopt the standard Encodable protocol encode their UUID properties.
/// `DatabaseUUIDEncodingStrategy` specifies how `EncodableRecord` types that
/// also adopt the standard `Encodable` protocol encode their `UUID` properties.
///
/// For example:
///
/// struct Player: EncodableProtocol, Encodable {
/// static let databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy = .string
/// static let databaseUUIDEncodingStrategy = DatabaseUUIDEncodingStrategy.string
///
/// // encoded in a string like "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
/// var uuid: UUID
+4 -3
View File
@@ -537,13 +537,14 @@ public final class RecordCursor<Record: FetchableRecord>: Cursor {
// MARK: - DatabaseDateDecodingStrategy
/// DatabaseDateDecodingStrategy specifies how FetchableRecord types that also
/// adopt the standard Decodable protocol decode their date properties.
/// `DatabaseDateDecodingStrategy` specifies how `FetchableRecord` types that
/// also adopt the standard `Decodable` protocol decode their
/// `Date` properties.
///
/// For example:
///
/// struct Player: FetchableRecord, Decodable {
/// static let databaseDateDecodingStrategy: DatabaseDateDecodingStrategy = .timeIntervalSince1970
/// static let databaseDateDecodingStrategy = DatabaseDateDecodingStrategy.timeIntervalSince1970
///
/// var name: String
/// var registrationDate: Date // decoded from epoch timestamp
+4 -4
View File
@@ -13,11 +13,11 @@ extension Database.ConflictResolution {
/// An error thrown by a type that adopts PersistableRecord.
public enum PersistenceError: Error, CustomStringConvertible {
/// Thrown by MutablePersistableRecord.update() when no matching row could be
/// found in the database.
/// Thrown by `MutablePersistableRecord.update(_:)` methods when no matching
/// row could be found in the database.
///
/// - databaseTableName: the table of the unfound record
/// - key: the key of the unfound record (column and values)
/// - `databaseTableName`: the table of the unfound record
/// - `key`: the key of the unfound record (column and values)
case recordNotFound(databaseTableName: String, key: [String: DatabaseValue])
}
+1 -1
View File
@@ -19,7 +19,7 @@ import Foundation
/// onChange: { players: [Player] in
/// print("Players have changed.")
/// })
public struct ValueObservation<Reducer: _ValueReducer> {
public struct ValueObservation<Reducer: ValueReducer> {
var events = ValueObservationEvents()
/// The reducer is created when observation starts, and is triggered upon
@@ -1,7 +1,7 @@
import Dispatch
import Foundation
/// ValueObservationScheduler determines how ValueObservation notifies its
/// ValueObservationScheduler determines how `ValueObservation` notifies its
/// fresh values.
public class ValueObservationScheduler {
private let impl: ValueObservationSchedulerImpl
+7 -6
View File
@@ -2,7 +2,7 @@ import Foundation
/// Support for ValueObservation.
/// See DatabaseWriter.add(observation:onError:onChange:)
final class ValueObserver<Reducer: _ValueReducer> {
final class ValueObserver<Reducer: ValueReducer> {
var isCompleted: Bool { synchronized { _isCompleted } }
let events: ValueObservationEvents
private var observedRegion: DatabaseRegion? {
@@ -90,10 +90,10 @@ extension ValueObserver: TransactionObserver {
events.databaseDidChange?()
// 1. Fetch
let fetchedValue: DatabaseFuture<Reducer.Fetched>
let fetchedFuture: DatabaseFuture<Reducer.Fetched>
if requiresWriteAccess || needsRecordingSelectedRegion {
// Synchronously
fetchedValue = DatabaseFuture(Result {
fetchedFuture = DatabaseFuture(Result {
try recordingSelectedRegionIfNeeded(db) {
try reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
@@ -101,7 +101,7 @@ extension ValueObserver: TransactionObserver {
} else {
// Concurrently
guard let writer = writer else { return }
fetchedValue = writer.concurrentRead(reducer.fetch)
fetchedFuture = writer.concurrentRead(reducer._fetch)
}
// 2. Reduce
@@ -113,7 +113,8 @@ extension ValueObserver: TransactionObserver {
reduceQueue.async {
if self.isCompleted { return }
do {
if let value = try self.reducer.value(fetchedValue.wait()) {
let fetchedValue = try fetchedFuture.wait()
if let value = self.reducer._value(fetchedValue) {
self.notifyChange(value)
}
} catch {
@@ -199,7 +200,7 @@ extension ValueObserver {
}
private var needsRecordingSelectedRegion: Bool {
observedRegion == nil || !reducer.isSelectedRegionDeterministic
observedRegion == nil || !reducer._isSelectedRegionDeterministic
}
private func recordingSelectedRegionIfNeeded<T>(
+12 -11
View File
@@ -1,10 +1,9 @@
extension ValueReducers {
/// A reducer which passes raw fetched values through.
///
/// :nodoc:
public struct Fetch<Value>: _ValueReducer {
private let _fetch: (Database) throws -> Value
public let isSelectedRegionDeterministic: Bool
public struct Fetch<Value>: ValueReducer {
private let __fetch: (Database) throws -> Value
/// :nodoc:
public let _isSelectedRegionDeterministic: Bool
/// Creates a reducer, which passes raw fetched values through.
///
@@ -19,16 +18,18 @@ extension ValueReducers {
/// each fetch.
///
/// - parameter fetch: A function that fetches the observed value.
public init(isSelectedRegionDeterministic: Bool, fetch: @escaping (Database) throws -> Value) {
self.isSelectedRegionDeterministic = isSelectedRegionDeterministic
self._fetch = fetch
init(isSelectedRegionDeterministic: Bool, fetch: @escaping (Database) throws -> Value) {
self._isSelectedRegionDeterministic = isSelectedRegionDeterministic
self.__fetch = fetch
}
public func fetch(_ db: Database) throws -> Value {
try _fetch(db)
/// :nodoc:
public func _fetch(_ db: Database) throws -> Value {
try __fetch(db)
}
public func value(_ fetched: Value) -> Value? {
/// :nodoc:
public func _value(_ fetched: Value) -> Value? {
fetched
}
}
+9 -8
View File
@@ -14,24 +14,25 @@ extension ValueReducers {
/// passed through a transform function.
///
/// See `ValueObservation.map(_:)`
///
/// :nodoc:
public struct Map<Base: _ValueReducer, Value>: _ValueReducer {
public struct Map<Base: ValueReducer, Value>: ValueReducer {
private var base: Base
private let transform: (Base.Value) -> Value
public var isSelectedRegionDeterministic: Bool { base.isSelectedRegionDeterministic }
/// :nodoc:
public var _isSelectedRegionDeterministic: Bool { base._isSelectedRegionDeterministic }
init(_ base: Base, _ transform: @escaping (Base.Value) -> Value) {
self.base = base
self.transform = transform
}
public func fetch(_ db: Database) throws -> Base.Fetched {
try base.fetch(db)
/// :nodoc:
public func _fetch(_ db: Database) throws -> Base.Fetched {
try base._fetch(db)
}
public mutating func value(_ fetched: Base.Fetched) -> Value? {
guard let value = base.value(fetched) else { return nil }
/// :nodoc:
public mutating func _value(_ fetched: Base.Fetched) -> Value? {
guard let value = base._value(fetched) else { return nil }
return transform(value)
}
}
@@ -10,23 +10,24 @@ extension ValueObservation where Reducer.Value: Equatable {
extension ValueReducers {
/// See `ValueObservation.removeDuplicates()`
///
/// :nodoc:
public struct RemoveDuplicates<Base: _ValueReducer>: _ValueReducer where Base.Value: Equatable {
public struct RemoveDuplicates<Base: ValueReducer>: ValueReducer where Base.Value: Equatable {
private var base: Base
private var previousValue: Base.Value?
public var isSelectedRegionDeterministic: Bool { base.isSelectedRegionDeterministic }
/// :nodoc:
public var _isSelectedRegionDeterministic: Bool { base._isSelectedRegionDeterministic }
init(_ base: Base) {
self.base = base
}
public func fetch(_ db: Database) throws -> Base.Fetched {
try base.fetch(db)
/// :nodoc:
public func _fetch(_ db: Database) throws -> Base.Fetched {
try base._fetch(db)
}
public mutating func value(_ fetched: Base.Fetched) -> Base.Value? {
guard let value = base.value(fetched) else {
/// :nodoc:
public mutating func _value(_ fetched: Base.Fetched) -> Base.Value? {
guard let value = base._value(fetched) else {
return nil
}
if let previousValue = previousValue, previousValue == value {
+10 -7
View File
@@ -1,18 +1,21 @@
extension ValueReducers {
/// :nodoc:
public struct Trace<Base: _ValueReducer>: _ValueReducer {
/// See `ValueObservation.handleEvents()`
public struct Trace<Base: ValueReducer>: ValueReducer {
var base: Base
let willFetch: () -> Void
let didReceiveValue: (Base.Value) -> Void
public var isSelectedRegionDeterministic: Bool { base.isSelectedRegionDeterministic }
/// :nodoc:
public var _isSelectedRegionDeterministic: Bool { base._isSelectedRegionDeterministic }
public func fetch(_ db: Database) throws -> Base.Fetched {
/// :nodoc:
public func _fetch(_ db: Database) throws -> Base.Fetched {
willFetch()
return try base.fetch(db)
return try base._fetch(db)
}
public mutating func value(_ fetched: Base.Fetched) -> Base.Value? {
guard let value = base.value(fetched) else {
/// :nodoc:
public mutating func _value(_ fetched: Base.Fetched) -> Base.Value? {
guard let value = base._value(fetched) else {
return nil
}
didReceiveValue(value)
@@ -1,4 +1,4 @@
/// The _ValueReducer protocol supports ValueObservation.
/// Implementation details of `ValueReducer`.
public protocol _ValueReducer {
/// The type of fetched database values
associatedtype Fetched
@@ -6,63 +6,66 @@ public protocol _ValueReducer {
/// The type of observed values
associatedtype Value
/// Returns whether the database region selected by the fetch(_:) method
/// Returns whether the database region selected by the `fetch(_:)` method
/// is constant.
var isSelectedRegionDeterministic: Bool { get }
var _isSelectedRegionDeterministic: Bool { get }
/// Fetches database values upon changes in an observed database region.
///
/// _ValueReducer semantics require that this method does not depend on
/// ValueReducer semantics require that this method does not depend on
/// the state of the reducer.
func fetch(_ db: Database) throws -> Fetched
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 in some unspecified dispatch queue.
///
/// _ValueReducer semantics require that the first invocation of this
/// ValueReducer semantics require that the first invocation of this
/// method returns a non-nil value:
///
/// let reducer = MyReducer()
/// reducer.value(...) // MUST NOT be nil
/// reducer.value(...) // MAY be nil
/// reducer.value(...) // MAY be nil
mutating func value(_ fetched: Fetched) -> Value?
/// reducer._value(...) // MUST NOT be nil
/// reducer._value(...) // MAY be nil
/// reducer._value(...) // MAY be nil
mutating func _value(_ fetched: Fetched) -> Value?
}
extension _ValueReducer {
/// The `ValueReducer` protocol supports `ValueObservation`.
public protocol ValueReducer: _ValueReducer { }
extension ValueReducer {
func fetch(_ db: Database, requiringWriteAccess: Bool) throws -> Fetched {
if requiringWriteAccess {
var fetchedValue: Fetched?
try db.inSavepoint {
fetchedValue = try fetch(db)
fetchedValue = try _fetch(db)
return .commit
}
return fetchedValue!
} else {
return try db.readOnly {
try fetch(db)
try _fetch(db)
}
}
}
mutating func fetchAndReduce(_ db: Database, requiringWriteAccess: Bool) throws -> Value? {
let fetchedValue = try fetch(db, requiringWriteAccess: requiringWriteAccess)
return value(fetchedValue)
return _value(fetchedValue)
}
}
/// A namespace for types related to the _ValueReducer protocol.
/// A namespace for types related to the `ValueReducer` protocol.
public enum ValueReducers {
// ValueReducers.Auto allows us to define ValueObservation factory methods.
//
// For example, ValueObservation.tracking(_:) is, practically,
// ValueObservation<ValueReducers.Auto>.tracking(_:).
/// :nodoc:
public enum Auto: _ValueReducer {
public var isSelectedRegionDeterministic: Bool { preconditionFailure() }
public func fetch(_ db: Database) throws -> Never { preconditionFailure() }
public mutating func value(_ fetched: Never) -> Never? { }
public enum Auto: ValueReducer {
public var _isSelectedRegionDeterministic: Bool { preconditionFailure() }
public func _fetch(_ db: Database) throws -> Never { preconditionFailure() }
public mutating func _value(_ fetched: Never) -> Never? { }
}
}
+11 -11
View File
@@ -215,7 +215,7 @@ class GRDBTestCase: XCTestCase {
try _assertEqualSQL(databaseReader, request, sql, file: file, line: line)
}
#endif
func sql<Request: FetchRequest>(_ databaseReader: DatabaseReader, _ request: Request) -> String {
try! databaseReader.unsafeRead { db in
try request.makeStatement(db).makeCursor().next()
@@ -238,25 +238,25 @@ extension FetchRequest {
}
/// A type-erased ValueReducer.
public struct AnyValueReducer<Fetched, Value>: _ValueReducer {
private var _fetch: (Database) throws -> Fetched
private var _value: (Fetched) -> Value?
public struct AnyValueReducer<Fetched, Value>: ValueReducer {
private var __fetch: (Database) throws -> Fetched
private var __value: (Fetched) -> Value?
public var isSelectedRegionDeterministic: Bool { false }
public var _isSelectedRegionDeterministic: Bool { false }
public init(
fetch: @escaping (Database) throws -> Fetched,
value: @escaping (Fetched) -> Value?)
{
self._fetch = fetch
self._value = value
self.__fetch = fetch
self.__value = value
}
public func fetch(_ db: Database) throws -> Fetched {
try _fetch(db)
public func _fetch(_ db: Database) throws -> Fetched {
try __fetch(db)
}
public func value(_ fetched: Fetched) -> Value? {
_value(fetched)
public func _value(_ fetched: Fetched) -> Value? {
__value(fetched)
}
}
@@ -601,7 +601,7 @@ class ValueObservationPrintTests: GRDBTestCase {
}
func test_handleEvents() throws {
func waitFor<R: _ValueReducer>(_ observation: ValueObservation<R>) throws {
func waitFor<R: ValueReducer>(_ observation: ValueObservation<R>) throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)")
@@ -624,7 +624,7 @@ class ValueObservationPrintTests: GRDBTestCase {
}
}
func waitForError<R: _ValueReducer>(_ observation: ValueObservation<R>) throws {
func waitForError<R: ValueReducer>(_ observation: ValueObservation<R>) throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)")
@@ -648,7 +648,7 @@ class ValueObservationPrintTests: GRDBTestCase {
}
}
func waitForCancel<R: _ValueReducer>(_ observation: ValueObservation<R>) throws {
func waitForCancel<R: ValueReducer>(_ observation: ValueObservation<R>) throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)")
@@ -412,7 +412,7 @@ extension XCTestCase {
// MARK: - GRDBTestCase + ValueObservationExpectation
extension GRDBTestCase {
func _assertValueObservation<Reducer: _ValueReducer>(
func _assertValueObservation<Reducer: ValueReducer>(
_ observation: ValueObservation<Reducer>,
records expectedValues: [Reducer.Value],
setup: (Database) throws -> Void,
@@ -631,7 +631,7 @@ extension GRDBTestCase {
}
}
func _assertValueObservation<Reducer: _ValueReducer, Failure: Error>(
func _assertValueObservation<Reducer: ValueReducer, Failure: Error>(
_ observation: ValueObservation<Reducer>,
fails testFailure: (Failure, DatabaseWriter) throws -> Void,
setup: (Database) throws -> Void,
@@ -735,7 +735,7 @@ extension GRDBTestCase {
try _assertValueObservation(observation, fails: testFailure, setup: setup, file: file, line: line)
}
#else
func assertValueObservation<Reducer: _ValueReducer>(
func assertValueObservation<Reducer: ValueReducer>(
_ observation: ValueObservation<Reducer>,
records expectedValues: [Reducer.Value],
setup: (Database) throws -> Void,
@@ -753,7 +753,7 @@ extension GRDBTestCase {
file: file, line: line)
}
func assertValueObservation<Reducer: _ValueReducer, Failure: Error>(
func assertValueObservation<Reducer: ValueReducer, Failure: Error>(
_ observation: ValueObservation<Reducer>,
fails testFailure: (Failure, DatabaseWriter) throws -> Void,
setup: (Database) throws -> Void,