Sendable annotations

This commit is contained in:
Gwendal Roué committed 2023-11-03 10:53:49 +01:00
1 parent 61e0e97b39
commit e7eac0d500
88 files changed
+957 -711

No files matched your search

+1 -1
View File
@@ -223,7 +223,7 @@ public struct Configuration {
///
/// On newly created databases files, ``DatabasePool`` activates the WAL
/// mode after the preparation functions have run.
public mutating func prepareDatabase(_ setup: @escaping (Database) throws -> Void) {
public mutating func prepareDatabase(_ setup: @escaping @Sendable (Database) throws -> Void) {
setups.append(setup)
}
+19 -11
View File
@@ -130,20 +130,28 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// MARK: - Configuration
@LockedBox private static var logErrorFunction: LogErrorFunction? = nil
/// The error logging function.
///
/// Related SQLite documentation: <https://www.sqlite.org/errlog.html>
public static var logError: LogErrorFunction? = nil {
didSet {
if logError != nil {
_registerErrorLogCallback { (_, code, message) in
guard let logError = Database.logError else { return }
guard let message = message.map(String.init) else { return }
let resultCode = ResultCode(rawValue: code)
logError(resultCode, message)
public static var logError: LogErrorFunction? {
get {
logErrorFunction
}
set {
$logErrorFunction.update {
$0 = newValue
if $0 != nil {
_registerErrorLogCallback { (_, code, message) in
guard let logError = Database.logError else { return }
guard let message = message.map(String.init) else { return }
let resultCode = ResultCode(rawValue: code)
logError(resultCode, message)
}
} else {
_registerErrorLogCallback(nil)
}
} else {
_registerErrorLogCallback(nil)
}
}
}
@@ -1785,7 +1793,7 @@ extension Database {
/// Related SQLite documentation:
/// - <https://www.sqlite.org/datatype3.html#collating_sequences>
/// - <https://www.sqlite.org/datatype3.html#collation>
public struct CollationName: RawRepresentable, Hashable {
public struct CollationName: RawRepresentable, Hashable, Sendable {
public let rawValue: String
/// Creates a collation name.
+16 -21
View File
@@ -257,7 +257,9 @@ extension DatabasePool {
// has freed its memory. That's better than nothing.
releaseMemoryEventually()
writer.async { _ in
application.endBackgroundTask(task)
DispatchQueue.main.async {
application.endBackgroundTask(task)
}
}
}
}
@@ -357,7 +359,7 @@ extension DatabasePool: DatabaseReader {
}
}
public func asyncRead(_ value: @escaping (Result<Database, any Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -401,7 +403,7 @@ extension DatabasePool: DatabaseReader {
}
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, any Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -446,25 +448,18 @@ extension DatabasePool: DatabaseReader {
}
}
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
// The semaphore that blocks until futureResult is defined:
let futureSemaphore = DispatchSemaphore(value: 0)
var futureResult: Result<T, any Error>? = nil
public func concurrentRead<T: Sendable>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T> {
let builder = DatabaseFutureBuilder<T>()
asyncConcurrentRead { dbResult in
// Fetch and release the future
futureResult = dbResult.flatMap { db in Result { try value(db) } }
futureSemaphore.signal()
builder.resolve(dbResult.flatMap { db in Result { try value(db) } })
}
return DatabaseFuture {
// Block the future until results are fetched
_ = futureSemaphore.wait(timeout: .distantFuture)
return try futureResult!.get()
}
return builder.future()
}
public func spawnConcurrentRead(_ value: @escaping (Result<Database, any Error>) -> Void) {
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
asyncConcurrentRead(value)
}
@@ -505,7 +500,7 @@ extension DatabasePool: DatabaseReader {
/// ```
///
/// - parameter value: A function that accesses the database.
public func asyncConcurrentRead(_ value: @escaping (Result<Database, any Error>) -> Void) {
public func asyncConcurrentRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
// Check that we're on the writer queue...
writer.execute { db in
// ... and that no transaction is opened.
@@ -665,7 +660,7 @@ extension DatabasePool: DatabaseReader {
///
/// - important: The `completion` argument is executed in a serial
/// dispatch queue, so make sure you use the transaction asynchronously.
func asyncWALSnapshotTransaction(_ completion: @escaping (Result<WALSnapshotTransaction, any Error>) -> Void) {
func asyncWALSnapshotTransaction(_ completion: @escaping @Sendable (Result<WALSnapshotTransaction, any Error>) -> Void) {
guard let readerPool else {
completion(.failure(DatabaseError.connectionIsClosed()))
return
@@ -691,7 +686,7 @@ extension DatabasePool: DatabaseReader {
public func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
if configuration.readonly {
@@ -722,7 +717,7 @@ extension DatabasePool: DatabaseReader {
private func _addConcurrent<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
@@ -756,7 +751,7 @@ extension DatabasePool: DatabaseWriter {
}
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, any Error>) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, any Error>) -> Void) {
guard let readerPool else {
updates(.failure(DatabaseError.connectionIsClosed()))
return
@@ -809,7 +804,7 @@ extension DatabasePool: DatabaseWriter {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
writer.async(updates)
}
}
+10 -8
View File
@@ -169,7 +169,9 @@ extension DatabaseQueue {
// Release memory asynchronously
writer.async { db in
db.releaseMemory()
application.endBackgroundTask(task)
DispatchQueue.main.async {
application.endBackgroundTask(task)
}
}
}
}
@@ -233,7 +235,7 @@ extension DatabaseQueue: DatabaseReader {
}
}
public func asyncRead(_ value: @escaping (Result<Database, any Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
writer.async { db in
defer {
// Ignore error because we can not notify it.
@@ -258,7 +260,7 @@ extension DatabaseQueue: DatabaseReader {
try writer.sync(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, any Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
writer.async { value(.success($0)) }
}
@@ -266,7 +268,7 @@ extension DatabaseQueue: DatabaseReader {
try writer.reentrantSync(value)
}
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
public func concurrentRead<T>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T> {
// DatabaseQueue can't perform parallel reads.
// Perform a blocking read instead.
return DatabaseFuture(Result {
@@ -279,7 +281,7 @@ extension DatabaseQueue: DatabaseReader {
})
}
public func spawnConcurrentRead(_ value: @escaping (Result<Database, any Error>) -> Void) {
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
// Check that we're on the writer queue...
writer.execute { db in
// ... and that no transaction is opened.
@@ -309,7 +311,7 @@ extension DatabaseQueue: DatabaseReader {
public func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
if configuration.readonly {
@@ -379,7 +381,7 @@ extension DatabaseQueue: DatabaseWriter {
try writer.sync(updates)
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, any Error>) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, any Error>) -> Void) {
writer.async { updates(.success($0)) }
}
@@ -425,7 +427,7 @@ extension DatabaseQueue: DatabaseWriter {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
writer.async(updates)
}
}
+18 -20
View File
@@ -213,7 +213,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// - parameter value: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func asyncRead(_ value: @escaping (Result<Database, any Error>) -> Void)
func asyncRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -284,7 +284,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// - parameter value: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func asyncUnsafeRead(_ value: @escaping (Result<Database, any Error>) -> Void)
func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -342,7 +342,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
}
@@ -458,7 +458,7 @@ extension DatabaseReader {
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
/// would happen while establishing the database access.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func read<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
public func read<T>(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncRead { result in
do {
@@ -504,7 +504,7 @@ extension DatabaseReader {
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
/// would happen while establishing the database access.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func unsafeRead<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
public func unsafeRead<T>(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncUnsafeRead { result in
do {
@@ -551,14 +551,12 @@ extension DatabaseReader {
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func readPublisher<Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
value: @escaping (Database) throws -> Output)
value: @escaping @Sendable (Database) throws -> Output)
-> DatabasePublishers.Read<Output>
{
Deferred {
Future { fulfill in
self.asyncRead { dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db) } })
}
OnDemandFuture{ fulfill in
self.asyncRead { dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db) } })
}
}
.receiveValues(on: scheduler)
@@ -601,7 +599,7 @@ extension DatabaseReader {
func _addReadOnly<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
if scheduler.immediateInitialValue() {
@@ -619,16 +617,16 @@ extension DatabaseReader {
}
return AnyDatabaseCancellable(cancel: { /* nothing to cancel */ })
} else {
var isCancelled = false
let cancellable = AnyDatabaseCancellable { }
asyncRead { dbResult in
guard !isCancelled else { return }
guard !cancellable.isCancelled else { return }
let result = dbResult.flatMap { db in
Result { try observation.fetchInitialValue(db) }
}
scheduler.schedule {
guard !isCancelled else { return }
guard !cancellable.isCancelled else { return }
do {
try onChange(result.get())
} catch {
@@ -636,7 +634,7 @@ extension DatabaseReader {
}
}
}
return AnyDatabaseCancellable(cancel: { isCancelled = true })
return cancellable
}
}
}
@@ -677,7 +675,7 @@ extension AnyDatabaseReader: DatabaseReader {
try base.read(value)
}
public func asyncRead(_ value: @escaping (Result<Database, any Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
base.asyncRead(value)
}
@@ -686,7 +684,7 @@ extension AnyDatabaseReader: DatabaseReader {
try base.unsafeRead(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, any Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
base.asyncUnsafeRead(value)
}
@@ -697,7 +695,7 @@ extension AnyDatabaseReader: DatabaseReader {
public func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
base._add(
@@ -757,7 +755,7 @@ extension DatabaseSnapshotReader {
}
// There is no such thing as an unsafe access to a snapshot.
public func asyncUnsafeRead(_ value: @escaping (Result<Database, any Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
asyncRead(value)
}
}
+4 -4
View File
@@ -378,11 +378,11 @@ private struct TableRegion: Equatable {
/// ### Supporting Types
///
/// - ``AnyDatabaseRegionConvertible``
public protocol DatabaseRegionConvertible {
public protocol DatabaseRegionConvertible: Sendable {
/// Returns a database region.
///
/// - parameter db: A database connection.
func databaseRegion(_ db: Database) throws -> DatabaseRegion
@Sendable func databaseRegion(_ db: Database) throws -> DatabaseRegion
}
extension DatabaseRegionConvertible where Self == DatabaseRegion {
@@ -399,9 +399,9 @@ extension DatabaseRegion: DatabaseRegionConvertible {
/// A type-erased DatabaseRegionConvertible
public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
let _region: (Database) throws -> DatabaseRegion
let _region: @Sendable (Database) throws -> DatabaseRegion
public init(_ region: @escaping (Database) throws -> DatabaseRegion) {
public init(_ region: @escaping @Sendable (Database) throws -> DatabaseRegion) {
_region = region
}
+13 -13
View File
@@ -43,7 +43,7 @@ extension DatabaseRegionObservation {
extension DatabaseRegionObservation {
/// The state of a started DatabaseRegionObservation
private enum ObservationState {
private enum ObservationState: Sendable {
case cancelled
case pending
case started(DatabaseRegionObserver)
@@ -85,23 +85,23 @@ extension DatabaseRegionObservation {
/// - returns: A DatabaseCancellable that can stop the observation.
public func start(
in writer: some DatabaseWriter,
onError: @escaping (any Error) -> Void,
onChange: @escaping (Database) -> Void)
onError: @escaping @Sendable (any Error) -> Void,
onChange: @escaping @Sendable (Database) -> Void)
-> AnyDatabaseCancellable
{
@LockedBox var state = ObservationState.pending
let state = LockedBox(wrappedValue: ObservationState.pending)
// Use unsafeReentrantWrite so that observation can start from any
// dispatch queue.
writer.unsafeReentrantWrite { db in
do {
let region = try observedRegion(db).observableRegion(db)
$state.update {
let observer = DatabaseRegionObserver(region: region, onChange: {
if case .cancelled = state {
state.update {
let observer = DatabaseRegionObserver(region: region, onChange: { db in
if case .cancelled = state.wrappedValue {
return
}
onChange($0)
onChange(db)
})
// Use the `.observerLifetime` extent so that we can cancel
@@ -122,7 +122,7 @@ extension DatabaseRegionObservation {
// Deallocates the transaction observer. This makes sure that the
// `onChange` callback will never be called again, because the
// observation was started with the `.observerLifetime` extent.
state = .cancelled
state.wrappedValue = .cancelled
}
}
}
@@ -147,12 +147,12 @@ extension DatabaseRegionObservation {
}
#endif
private class DatabaseRegionObserver: TransactionObserver {
private class DatabaseRegionObserver: TransactionObserver, @unchecked Sendable {
let region: DatabaseRegion
let onChange: (Database) -> Void
let onChange: @Sendable (Database) -> Void
var isChanged = false
init(region: DatabaseRegion, onChange: @escaping (Database) -> Void) {
init(region: DatabaseRegion, onChange: @escaping @Sendable (Database) -> Void) {
self.region = region
self.onChange = onChange
}
@@ -207,7 +207,7 @@ extension DatabasePublishers {
}
}
private class DatabaseRegionSubscription<Downstream: Subscriber>: Subscription
private class DatabaseRegionSubscription<Downstream: Subscriber>: Subscription, @unchecked Sendable
where Downstream.Failure == any Error, Downstream.Input == Database
{
private struct WaitingForDemand {
+3 -3
View File
@@ -154,7 +154,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
try reader.sync(block)
}
public func asyncRead(_ value: @escaping (Result<Database, any Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
reader.async { value(.success($0)) }
}
@@ -162,7 +162,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
try reader.sync(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, any Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
reader.async { value(.success($0)) }
}
@@ -175,7 +175,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
public func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
_addReadOnly(
+2 -2
View File
@@ -292,7 +292,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
}
public func asyncRead(_ value: @escaping (Result<Database, any Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
return
@@ -330,7 +330,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
public func _add<Reducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable where Reducer: ValueReducer
{
_addReadOnly(observation: observation, scheduling: scheduler, onChange: onChange)
+12 -12
View File
@@ -301,7 +301,7 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
@Sendable public static func fetchAll(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -335,7 +335,7 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
@Sendable public static func fetchOne(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -370,7 +370,7 @@ extension DatabaseValueConvertible where Self: Hashable {
/// - adapter: Optional RowAdapter
/// - returns: A set.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
@Sendable public static func fetchSet(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -447,7 +447,7 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
@Sendable public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -482,7 +482,7 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
@Sendable public static func fetchOne(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -516,7 +516,7 @@ extension DatabaseValueConvertible where Self: Hashable {
/// - adapter: Optional RowAdapter
/// - returns: A set.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
@Sendable public static func fetchSet(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -603,7 +603,7 @@ extension DatabaseValueConvertible {
/// - request: A FetchRequest.
/// - returns: An array.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
@Sendable public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchAll(request.statement, adapter: request.adapter)
}
@@ -640,7 +640,7 @@ extension DatabaseValueConvertible {
/// - request: A FetchRequest.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
@Sendable public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
let request = try request.makePreparedRequest(db, forSingleResult: true)
return try fetchOne(request.statement, adapter: request.adapter)
}
@@ -676,7 +676,7 @@ extension DatabaseValueConvertible where Self: Hashable {
/// - request: A FetchRequest.
/// - returns: A set.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
@Sendable public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchSet(request.statement, adapter: request.adapter)
}
@@ -753,7 +753,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
@Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] {
try RowDecoder.fetchAll(db, self)
}
@@ -787,7 +787,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
@Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? {
try RowDecoder.fetchOne(db, self)
}
}
@@ -820,7 +820,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable {
/// - parameter db: A database connection.
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
@Sendable public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
try RowDecoder.fetchSet(db, self)
}
}
+48 -23
View File
@@ -181,7 +181,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// - parameter updates: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the barrier access to the database.
func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, any Error>) -> Void)
func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, any Error>) -> Void)
/// Schedules database operations for execution, and returns immediately.
///
@@ -213,7 +213,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// <doc:Concurrency#Rule-2:-Mind-your-transactions> for more information.
///
/// - parameter updates: A closure which accesses the database.
func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void)
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -292,7 +292,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// returned ``DatabaseFuture`` blocks a thread. You may prefer
/// ``spawnConcurrentRead(_:)`` instead.
/// - parameter value: A closure which accesses the database.
func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T>
func concurrentRead<T>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T>
// Exposed for RxGRDB and GRBCombine. Naming is not stabilized.
/// Schedules read-only database operations for execution.
@@ -340,7 +340,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// - parameter value: A closure which accesses the database. Its argument
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func spawnConcurrentRead(_ value: @escaping (Result<Database, any Error>) -> Void)
func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void)
}
extension DatabaseWriter {
@@ -426,8 +426,8 @@ extension DatabaseWriter {
/// - parameter updates: A closure which accesses the database.
/// - parameter completion: A closure called with the transaction result.
public func asyncWrite<T>(
_ updates: @escaping (Database) throws -> T,
completion: @escaping (Database, Result<T, any Error>) -> Void)
_ updates: @escaping @Sendable (Database) throws -> T,
completion: @escaping @Sendable (Database, Result<T, any Error>) -> Void)
{
asyncWriteWithoutTransaction { db in
do {
@@ -557,7 +557,7 @@ extension DatabaseWriter {
func _addWriteOnly<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
@@ -608,7 +608,7 @@ extension DatabaseWriter {
/// would happen while establishing the database access or committing
/// the transaction.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func write<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
public func write<T>(_ updates: @escaping @Sendable (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncWrite(updates, completion: { _, result in
continuation.resume(with: result)
@@ -646,7 +646,7 @@ extension DatabaseWriter {
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func writeWithoutTransaction<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
public func writeWithoutTransaction<T>(_ updates: @escaping @Sendable (Database) throws -> T) async throws -> T {
try await withUnsafeThrowingContinuation { continuation in
asyncWriteWithoutTransaction { db in
do {
@@ -699,7 +699,7 @@ extension DatabaseWriter {
/// - throws: The error thrown by `updates`.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func barrierWriteWithoutTransaction<T>(
_ updates: @Sendable @escaping (Database) throws -> T)
_ updates: @escaping @Sendable (Database) throws -> T)
async throws -> T
{
try await withUnsafeThrowingContinuation { continuation in
@@ -803,7 +803,7 @@ extension DatabaseWriter {
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func writePublisher<Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
updates: @escaping (Database) throws -> Output)
updates: @escaping @Sendable (Database) throws -> Output)
-> DatabasePublishers.Write<Output>
{
OnDemandFuture { fulfill in
@@ -866,10 +866,10 @@ extension DatabaseWriter {
/// - parameter updates: A closure which writes in the database.
/// - parameter value: A closure which reads from the database.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
public func writePublisher<S, T, Output>(
public func writePublisher<S, T: Sendable, Output: Sendable>(
receiveOn scheduler: S = DispatchQueue.main,
updates: @escaping (Database) throws -> T,
thenRead value: @escaping (Database, T) throws -> Output)
updates: @escaping @Sendable (Database) throws -> T,
thenRead value: @escaping @Sendable (Database, T) throws -> Output)
-> DatabasePublishers.Write<Output>
where S: Scheduler
{
@@ -885,7 +885,7 @@ extension DatabaseWriter {
fulfill(.failure(error))
return
}
self.spawnConcurrentRead { dbResult in
self.spawnConcurrentRead { [updatesValue] dbResult in
fulfill(dbResult.flatMap { db in Result { try value(db, updatesValue!) } })
}
}
@@ -941,7 +941,7 @@ extension Publisher where Failure == any Error {
///
/// let count: Int = try futureCount.wait()
/// ```
public class DatabaseFuture<Value> {
public class DatabaseFuture<Value: Sendable> {
private var consumed = false
private let _wait: () throws -> Value
@@ -967,6 +967,31 @@ public class DatabaseFuture<Value> {
}
}
/// Helps building DatabaseFuture with strict concurrency checkings
final class DatabaseFutureBuilder<Value: Sendable>: @unchecked Sendable {
/// The semaphore that blocks until result is set.
let semaphore = DispatchSemaphore(value: 0)
var result: Result<Value, any Error>? = nil
init() { }
/// - precondition: MUST be called once.
func resolve(_ result: Result<Value, any Error>) {
self.result = result
semaphore.signal()
}
/// - precondition: MUST be called once.
func future() -> DatabaseFuture<Value> {
DatabaseFuture { [self] in
// Block the future until results are fetched
_ = semaphore.wait(timeout: .distantFuture)
return try result!.get()
}
}
}
/// A type-erased database writer.
///
/// An instance of `AnyDatabaseWriter` forwards its operations to an underlying
@@ -1003,7 +1028,7 @@ extension AnyDatabaseWriter: DatabaseReader {
try base.read(value)
}
public func asyncRead(_ value: @escaping (Result<Database, any Error>) -> Void) {
public func asyncRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
base.asyncRead(value)
}
@@ -1012,7 +1037,7 @@ extension AnyDatabaseWriter: DatabaseReader {
try base.unsafeRead(value)
}
public func asyncUnsafeRead(_ value: @escaping (Result<Database, any Error>) -> Void) {
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
base.asyncUnsafeRead(value)
}
@@ -1023,7 +1048,7 @@ extension AnyDatabaseWriter: DatabaseReader {
public func _add<Reducer: ValueReducer>(
observation: ValueObservation<Reducer>,
scheduling scheduler: some ValueObservationScheduler,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
{
base._add(
@@ -1044,11 +1069,11 @@ extension AnyDatabaseWriter: DatabaseWriter {
try base.barrierWriteWithoutTransaction(updates)
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, any Error>) -> Void) {
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, any Error>) -> Void) {
base.asyncBarrierWriteWithoutTransaction(updates)
}
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
base.asyncWriteWithoutTransaction(updates)
}
@@ -1056,11 +1081,11 @@ extension AnyDatabaseWriter: DatabaseWriter {
try base.unsafeReentrantWrite(updates)
}
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
public func concurrentRead<T>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T> {
base.concurrentRead(value)
}
public func spawnConcurrentRead(_ value: @escaping (Result<Database, any Error>) -> Void) {
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
base.spawnConcurrentRead(value)
}
}
+6 -6
View File
@@ -166,7 +166,7 @@ extension FetchRequest {
///
/// - parameter adapter: A closure that accepts a database connection and
/// returns a row adapter.
public func adapted(_ adapter: @escaping (Database) throws -> any RowAdapter) -> AdaptedFetchRequest<Self> {
public func adapted(_ adapter: @escaping @Sendable (Database) throws -> any RowAdapter) -> AdaptedFetchRequest<Self> {
AdaptedFetchRequest(self, adapter)
}
}
@@ -176,11 +176,11 @@ extension FetchRequest {
/// See ``FetchRequest/adapted(_:)``.
public struct AdaptedFetchRequest<Base: FetchRequest> {
let base: Base
let adapter: (Database) throws -> any RowAdapter
let adapter: @Sendable (Database) throws -> any RowAdapter
/// Creates an adapted request from a base request and a closure that builds
/// a row adapter from a database connection.
init(_ base: Base, _ adapter: @escaping (Database) throws -> any RowAdapter) {
init(_ base: Base, _ adapter: @escaping @Sendable (Database) throws -> any RowAdapter) {
self.base = base
self.adapter = adapter
}
@@ -195,7 +195,7 @@ extension AdaptedFetchRequest: SQLSubqueryable {
extension AdaptedFetchRequest: FetchRequest {
public typealias RowDecoder = Base.RowDecoder
public func fetchCount(_ db: Database) throws -> Int {
@Sendable public func fetchCount(_ db: Database) throws -> Int {
try base.fetchCount(db)
}
@@ -255,7 +255,7 @@ extension AnyFetchRequest: SQLSubqueryable {
}
extension AnyFetchRequest: FetchRequest {
public func fetchCount(_ db: Database) throws -> Int {
@Sendable public func fetchCount(_ db: Database) throws -> Int {
try request.fetchCount(db)
}
@@ -269,7 +269,7 @@ extension AnyFetchRequest: FetchRequest {
}
// Class-based type erasure, so that we preserve full type information.
private class FetchRequestEraser: FetchRequest {
private class FetchRequestEraser: FetchRequest, @unchecked Sendable {
typealias RowDecoder = Void
var sqlSubquery: SQLSubquery {
+12 -12
View File
@@ -1447,7 +1447,7 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: An array of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
@Sendable public static func fetchAll(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -1476,7 +1476,7 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: A set of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
@Sendable public static func fetchSet(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -1505,7 +1505,7 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
@Sendable public static func fetchOne(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -1589,7 +1589,7 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: An array of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
@Sendable public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -1618,7 +1618,7 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: A set of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
@Sendable public static func fetchSet(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -1647,7 +1647,7 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
@Sendable public static func fetchOne(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -1736,7 +1736,7 @@ extension Row {
/// - request: A FetchRequest.
/// - returns: An array of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Row] {
@Sendable public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Row] {
let request = try request.makePreparedRequest(db, forSingleResult: false)
let rows = try fetchAll(request.statement, adapter: request.adapter)
try request.supplementaryFetch?(db, rows, nil)
@@ -1768,7 +1768,7 @@ extension Row {
/// - request: A FetchRequest.
/// - returns: A set of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Row> {
@Sendable public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Row> {
let request = try request.makePreparedRequest(db, forSingleResult: false)
if let supplementaryFetch = request.supplementaryFetch {
let rows = try fetchAll(request.statement, adapter: request.adapter)
@@ -1804,7 +1804,7 @@ extension Row {
/// - request: A FetchRequest.
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Row? {
@Sendable public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Row? {
let request = try request.makePreparedRequest(db, forSingleResult: true)
guard let row = try fetchOne(request.statement, adapter: request.adapter) else {
return nil
@@ -1874,7 +1874,7 @@ extension FetchRequest<Row> {
/// - parameter db: A database connection.
/// - returns: An array of fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [Row] {
@Sendable public func fetchAll(_ db: Database) throws -> [Row] {
try Row.fetchAll(db, self)
}
@@ -1895,7 +1895,7 @@ extension FetchRequest<Row> {
/// - parameter db: A database connection.
/// - returns: A set of fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<Row> {
@Sendable public func fetchSet(_ db: Database) throws -> Set<Row> {
try Row.fetchSet(db, self)
}
@@ -1916,7 +1916,7 @@ extension FetchRequest<Row> {
/// - parameter db: A database connection.
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> Row? {
@Sendable public func fetchOne(_ db: Database) throws -> Row? {
try Row.fetchOne(db, self)
}
}
+3 -3
View File
@@ -318,7 +318,7 @@ extension Statement: _RowLayout {
/// - ``RenameColumnAdapter``
/// - ``ScopeAdapter``
/// - ``SuffixRowAdapter``
public protocol RowAdapter {
public protocol RowAdapter: Sendable {
/// You never call this method directly. It is called for you whenever an
/// adapter has to be applied.
///
@@ -656,11 +656,11 @@ struct ChainedAdapter: RowAdapter {
/// print(Array(adaptedRow.columnNames))
/// ```
public struct RenameColumnAdapter: RowAdapter {
let transform: (String) -> String
let transform: @Sendable (String) -> String
/// Creates a `RenameColumnAdapter` adapter that renames columns according to the
/// provided transform function.
public init(_ transform: @escaping (String) -> String) {
public init(_ transform: @escaping @Sendable (String) -> String) {
self.transform = transform
}
+1 -1
View File
@@ -191,7 +191,7 @@ extension SQLRequest: FetchRequest {
.literal(sqlLiteral)
}
public func fetchCount(_ db: Database) throws -> Int {
@Sendable public func fetchCount(_ db: Database) throws -> Int {
try SQLRequest<Int>("SELECT COUNT(*) FROM (\(self))").fetchOne(db)!
}
+1 -1
View File
@@ -223,7 +223,7 @@ final class SerializedDatabase {
}
/// Schedules database operations for execution, and returns immediately.
func async(_ block: @escaping (Database) -> Void) {
func async(_ block: @escaping @Sendable (Database) -> Void) {
queue.async {
block(self.db)
self.preconditionNoUnsafeTransactionLeft(self.db)
+12 -12
View File
@@ -312,7 +312,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
@Sendable public static func fetchAll(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -346,7 +346,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
@Sendable public static func fetchOne(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -384,7 +384,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
/// - adapter: Optional RowAdapter
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
@Sendable public static func fetchSet(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -461,7 +461,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
@Sendable public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -496,7 +496,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
@Sendable public static func fetchOne(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -530,7 +530,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
/// - adapter: Optional RowAdapter
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
@Sendable public static func fetchSet(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -619,7 +619,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - request: A FetchRequest.
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
@Sendable public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchAll(request.statement, adapter: request.adapter)
}
@@ -656,7 +656,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - request: A FetchRequest.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
@Sendable public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
let request = try request.makePreparedRequest(db, forSingleResult: true)
return try fetchOne(request.statement, adapter: request.adapter)
}
@@ -692,7 +692,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
/// - request: A FetchRequest.
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
@Sendable public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchSet(request.statement, adapter: request.adapter)
}
@@ -769,7 +769,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
@Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] {
try RowDecoder.fetchAll(db, self)
}
@@ -803,7 +803,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
@Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? {
try RowDecoder.fetchOne(db, self)
}
}
@@ -836,7 +836,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// - parameter db: A database connection.
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
@Sendable public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
try RowDecoder.fetchSet(db, self)
}
}
@@ -4,7 +4,7 @@ import Foundation
public struct DatabaseDateComponents {
/// The SQLite formats for date components.
public enum Format: String {
public enum Format: String, Sendable {
/// The format "yyyy-MM-dd".
case YMD = "yyyy-MM-dd"
@@ -1,6 +1,7 @@
#if !os(Linux)
import Foundation
// GRDB7: remove conformance because NSData is not Sendable.
/// NSData is convertible to and from DatabaseValue.
extension NSData: DatabaseValueConvertible {
@@ -1,6 +1,7 @@
#if !os(Linux)
import Foundation
// GRDB7: remove conformance because NSString is not Sendable.
/// NSString adopts DatabaseValueConvertible
extension NSString: DatabaseValueConvertible {
+4 -4
View File
@@ -10,7 +10,7 @@ import Foundation
///
/// - ``DefaultTransactionClock``
/// - ``CustomTransactionClock``
public protocol TransactionClock {
public protocol TransactionClock: Sendable {
/// Returns the date of the current transaction.
///
/// This function is called whenever a transaction starts - precisely
@@ -36,7 +36,7 @@ extension TransactionClock where Self == CustomTransactionClock {
///
/// It is also called when the ``Database/transactionDate`` property is
/// called, and the database connection is not in a transaction.
public static func custom(_ now: @escaping (Database) throws -> Date) -> Self {
public static func custom(_ now: @escaping @Sendable (Database) throws -> Date) -> Self {
CustomTransactionClock(now)
}
}
@@ -53,9 +53,9 @@ public struct DefaultTransactionClock: TransactionClock {
/// A custom transaction clock.
public struct CustomTransactionClock: TransactionClock {
let _now: (Database) throws -> Date
let _now: @Sendable (Database) throws -> Date
public init(_ now: @escaping (Database) throws -> Date) {
public init(_ now: @escaping @Sendable (Database) throws -> Date) {
self._now = now
}
+8 -5
View File
@@ -101,14 +101,17 @@ extension Database {
/// - parameter onCommit: A closure executed on transaction commit.
/// - parameter onRollback: A closure executed on transaction rollback.
public func afterNextTransaction(
onCommit: @escaping (Database) -> Void,
onRollback: @escaping (Database) -> Void = { _ in })
onCommit: @escaping @Sendable (Database) -> Void,
onRollback: @escaping @Sendable (Database) -> Void = { _ in })
{
class TransactionHandler: TransactionObserver {
let onCommit: (Database) -> Void
let onRollback: (Database) -> Void
let onCommit: @Sendable (Database) -> Void
let onRollback: @Sendable (Database) -> Void
init(onCommit: @escaping (Database) -> Void, onRollback: @escaping (Database) -> Void) {
init(
onCommit: @escaping @Sendable (Database) -> Void,
onRollback: @escaping @Sendable (Database) -> Void)
{
self.onCommit = onCommit
self.onRollback = onRollback
}
+4 -4
View File
@@ -4,9 +4,9 @@
///
/// `WALSnapshotTransaction` **takes ownership** of its reader
/// `SerializedDatabase` (TODO: make it a move-only type eventually).
class WALSnapshotTransaction {
final class WALSnapshotTransaction: Sendable {
private let reader: SerializedDatabase
private let release: (_ isInsideTransaction: Bool) -> Void
private let release: @Sendable (_ isInsideTransaction: Bool) -> Void
/// The state of the database at the beginning of the transaction.
let walSnapshot: WALSnapshot
@@ -37,7 +37,7 @@ class WALSnapshotTransaction {
/// is no longer used.
init(
onReader reader: SerializedDatabase,
release: @escaping (_ isInsideTransaction: Bool) -> Void)
release: @escaping @Sendable (_ isInsideTransaction: Bool) -> Void)
throws
{
assert(reader.configuration.readonly)
@@ -71,7 +71,7 @@ class WALSnapshotTransaction {
/// Schedules database operations for execution, and
/// returns immediately.
func asyncRead(_ value: @escaping (Database) -> Void) {
func asyncRead(_ value: @escaping @Sendable (Database) -> Void) {
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
reader.async(value)
}
+1 -1
View File
@@ -50,7 +50,7 @@ extension Database {
init(
db: Database,
constructor: @escaping (Database, [String], UnsafeMutablePointer<OpaquePointer?>?) -> CInt)
constructor: @escaping @Sendable (Database, [String], UnsafeMutablePointer<OpaquePointer?>?) -> CInt)
{
self.db = db
self.constructor = constructor
+3 -3
View File
@@ -40,7 +40,7 @@ import Foundation
/// - ``completedMigrations(_:)``
/// - ``hasBeenSuperseded(_:)``
/// - ``hasCompletedMigrations(_:)``
public struct DatabaseMigrator {
public struct DatabaseMigrator: Sendable {
/// Controls how a migration handle foreign keys constraints.
public enum ForeignKeyChecks {
/// The migration runs with disabled foreign keys.
@@ -207,7 +207,7 @@ public struct DatabaseMigrator {
public mutating func registerMigration(
_ identifier: String,
foreignKeyChecks: ForeignKeyChecks = .deferred,
migrate: @escaping (Database) throws -> Void)
migrate: @escaping @Sendable (Database) throws -> Void)
{
let migrationChecks: Migration.ForeignKeyChecks
switch foreignKeyChecks {
@@ -264,7 +264,7 @@ public struct DatabaseMigrator {
/// from succeeding.
public func asyncMigrate(
_ writer: some DatabaseWriter,
completion: @escaping (Result<Database, any Error>) -> Void)
completion: @escaping @Sendable (Result<Database, any Error>) -> Void)
{
writer.asyncBarrierWriteWithoutTransaction { dbResult in
do {
+2 -2
View File
@@ -1,5 +1,5 @@
/// An internal struct that defines a migration.
struct Migration {
struct Migration: Sendable {
enum ForeignKeyChecks {
case deferred
case immediate
@@ -8,7 +8,7 @@ struct Migration {
let identifier: String
var foreignKeyChecks: ForeignKeyChecks
let migrate: (Database) throws -> Void
let migrate: @Sendable (Database) throws -> Void
func run(_ db: Database) throws {
if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false {
+1 -1
View File
@@ -80,7 +80,7 @@
/// using: Book.translatorForeignKey)
/// }
/// ```
public struct ForeignKey: Equatable {
public struct ForeignKey: Equatable, Sendable {
var originColumns: [String]
var destinationColumns: [String]?
@@ -173,7 +173,7 @@ extension Association {
// SelectionRequest conformance
extension Association {
public func selectWhenConnected(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self {
public func selectWhenConnected(_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]) -> Self {
withDestinationRelation { relation in
relation = relation.selectWhenConnected { db in
try selection(db).map(\.sqlSelection)
@@ -181,7 +181,7 @@ extension Association {
}
}
public func annotatedWhenConnected(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self {
public func annotatedWhenConnected(with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]) -> Self {
withDestinationRelation { relation in
relation = relation.annotatedWhenConnected { db in
try selection(db).map(\.sqlSelection)
@@ -192,7 +192,7 @@ extension Association {
// FilteredRequest conformance
extension Association {
public func filterWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self {
public func filterWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible) -> Self {
withDestinationRelation { relation in
relation = relation.filterWhenConnected { db in
try predicate(db).sqlExpression
@@ -203,7 +203,7 @@ extension Association {
// OrderedRequest conformance
extension Association {
public func orderWhenConnected(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self {
public func orderWhenConnected(_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm]) -> Self {
withDestinationRelation { relation in
relation = relation.orderWhenConnected { db in
try orderings(db).map(\.sqlOrdering)
@@ -239,7 +239,7 @@ extension Association {
// AggregatingRequest conformance
extension Association {
public func groupWhenConnected(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self {
public func groupWhenConnected(_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible]) -> Self {
withDestinationRelation { relation in
relation = relation.groupWhenConnected { db in
try expressions(db).map(\.sqlExpression)
@@ -247,7 +247,7 @@ extension Association {
}
}
public func havingWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self {
public func havingWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible) -> Self {
withDestinationRelation { relation in
relation = relation.havingWhenConnected { db in
try predicate(db).sqlExpression
@@ -385,7 +385,7 @@ extension CommonTableExpression {
/// - returns: An association to the common table expression.
public func association<Destination>(
to cte: CommonTableExpression<Destination>,
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
-> JoinAssociation<RowDecoder, Destination>
{
JoinAssociation(
@@ -421,7 +421,7 @@ extension CommonTableExpression {
/// - returns: An association to the common table expression.
public func association<Destination>(
to destination: Destination.Type,
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
-> JoinAssociation<RowDecoder, Destination>
where Destination: TableRecord
{
@@ -458,7 +458,7 @@ extension CommonTableExpression {
/// - returns: An association to the common table expression.
public func association<Destination>(
to destination: Table<Destination>,
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
-> JoinAssociation<RowDecoder, Destination>
{
JoinAssociation(
@@ -86,7 +86,7 @@ extension QueryInterfaceRequest: FetchRequest {
.relation(relation)
}
public func fetchCount(_ db: Database) throws -> Int {
@Sendable public func fetchCount(_ db: Database) throws -> Int {
try relation.fetchCount(db)
}
@@ -117,7 +117,7 @@ extension QueryInterfaceRequest: FetchRequest {
extension QueryInterfaceRequest: SelectionRequest {
public func selectWhenConnected(
_ selection: @escaping (Database) throws -> [any SQLSelectable])
_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
-> Self
{
with {
@@ -281,7 +281,7 @@ extension QueryInterfaceRequest: SelectionRequest {
}
public func annotatedWhenConnected(
with selection: @escaping (Database) throws -> [any SQLSelectable])
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
-> Self
{
with {
@@ -294,7 +294,7 @@ extension QueryInterfaceRequest: SelectionRequest {
extension QueryInterfaceRequest: FilteredRequest {
public func filterWhenConnected(
_ predicate: @escaping (Database) throws -> any SQLExpressible)
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible)
-> Self
{
with {
@@ -307,7 +307,7 @@ extension QueryInterfaceRequest: FilteredRequest {
extension QueryInterfaceRequest: OrderedRequest {
public func orderWhenConnected(
_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm])
_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm])
-> Self
{
with {
@@ -354,7 +354,7 @@ extension QueryInterfaceRequest: OrderedRequest {
extension QueryInterfaceRequest: AggregatingRequest {
public func groupWhenConnected(
_ expressions: @escaping (Database) throws -> [any SQLExpressible])
_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible])
-> Self
{
with {
@@ -365,7 +365,7 @@ extension QueryInterfaceRequest: AggregatingRequest {
}
public func havingWhenConnected(
_ predicate: @escaping (Database) throws -> any SQLExpressible)
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible)
-> Self
{
with {
@@ -58,7 +58,7 @@ public protocol SelectionRequest {
///
/// - parameter selection: A closure that accepts a database connection and
/// returns an array of result columns.
func selectWhenConnected(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self
func selectWhenConnected(_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]) -> Self
/// Appends result columns to the selected columns.
///
@@ -78,7 +78,7 @@ public protocol SelectionRequest {
///
/// - parameter selection: A closure that accepts a database connection and
/// returns an array of result columns.
func annotatedWhenConnected(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self
func annotatedWhenConnected(with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]) -> Self
}
extension SelectionRequest {
@@ -240,7 +240,7 @@ public protocol FilteredRequest {
///
/// - parameter predicate: A closure that accepts a database connection and
/// returns a boolean SQL expression.
func filterWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self
func filterWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible) -> Self
}
extension FilteredRequest {
@@ -729,7 +729,7 @@ public protocol AggregatingRequest {
///
/// - parameter expressions: A closure that accepts a database connection
/// and returns an array of SQL expressions.
func groupWhenConnected(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self
func groupWhenConnected(_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible]) -> Self
/// Filters the aggregated groups with a boolean SQL expression.
///
@@ -753,7 +753,7 @@ public protocol AggregatingRequest {
///
/// - parameter predicate: A closure that accepts a database connection and
/// returns a boolean SQL expression.
func havingWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self
func havingWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible) -> Self
}
extension AggregatingRequest {
@@ -934,7 +934,7 @@ public protocol OrderedRequest {
///
/// - parameter orderings: A closure that accepts a database connection and
/// returns an array of SQL ordering terms.
func orderWhenConnected(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self
func orderWhenConnected(_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm]) -> Self
/// Returns a request with reversed ordering.
///
@@ -21,9 +21,9 @@
///
/// Such late computations are backed by DatabasePromise. In our example,
/// see SQLRelation.filterPromise.
struct DatabasePromise<T> {
struct DatabasePromise<T: Sendable> {
/// Returns the resolved value.
let resolve: (Database) throws -> T
let resolve: @Sendable (Database) throws -> T
/// Creates a promise that resolves to a value.
init(value: T) {
@@ -31,12 +31,12 @@ struct DatabasePromise<T> {
}
/// Creates a promise from a closure.
init(_ resolve: @escaping (Database) throws -> T) {
init(_ resolve: @escaping @Sendable (Database) throws -> T) {
self.resolve = resolve
}
/// Returns a promise whose value is transformed by the given closure.
func map<U>(_ transform: @escaping (T) throws -> U) -> DatabasePromise<U> {
func map<U>(_ transform: @escaping @Sendable (T) throws -> U) -> DatabasePromise<U> {
DatabasePromise<U> { db in
try transform(resolve(db))
}
+3 -3
View File
@@ -57,7 +57,7 @@ public struct SQLExpression {
var preferredJSONInterpretation = JSONInterpretation.deferredToSQLite
/// The private implementation of the public `SQLExpression`.
private enum Impl {
private enum Impl: Sendable {
/// A column.
///
/// id
@@ -315,7 +315,7 @@ public struct SQLExpression {
/// 1000.databaseValue]
/// let request = Player.select(values.joined(operator: .add))
/// ```
public struct AssociativeBinaryOperator: Hashable {
public struct AssociativeBinaryOperator: Hashable, Sendable {
/// The SQL operator
let sql: String
@@ -2109,7 +2109,7 @@ extension SQLExpression {
/// A type that can be used as an SQL expression.
///
/// Related SQLite documentation <https://www.sqlite.org/syntax/expr.html>
public protocol SQLExpressible {
public protocol SQLExpressible: Sendable {
/// Returns an SQL expression.
var sqlExpression: SQLExpression { get }
}
+1 -1
View File
@@ -138,7 +138,7 @@ extension SQLOrdering {
/// ### Supporting Type
///
/// - ``SQLOrdering``
public protocol SQLOrderingTerm {
public protocol SQLOrderingTerm: Sendable {
/// Returns an SQL ordering.
var sqlOrdering: SQLOrdering { get }
}
+15 -15
View File
@@ -90,8 +90,8 @@
/// // JOIN passport ON passport.citizenId = citizens.id
/// // AND passport.countryCode IN ('BE', 'DE', 'FR', ...);
/// Country.including(all: Country.citizens)
struct SQLRelation {
struct Child: Refinable {
struct SQLRelation: Sendable {
struct Child: Refinable, Sendable {
enum Kind {
// Record.including(optional: association)
case oneOptional
@@ -187,7 +187,7 @@ extension SQLRelation {
/// Convenience factory methods which selects all rows from a table.
static func all(
fromTable tableName: String,
selection: @escaping (Database) -> [SQLSelection] = { _ in [.allColumns] })
selection: @escaping @Sendable (Database) -> [SQLSelection] = { _ in [.allColumns] })
-> Self
{
SQLRelation(
@@ -197,7 +197,7 @@ extension SQLRelation {
}
extension SQLRelation: Refinable {
func selectWhenConnected(_ selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
func selectWhenConnected(_ selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self {
with {
$0.selectionPromise = DatabasePromise(selection)
}
@@ -228,7 +228,7 @@ extension SQLRelation: Refinable {
}
}
func annotatedWhenConnected(with selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
func annotatedWhenConnected(with selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self {
with {
let old = $0.selectionPromise
$0.selectionPromise = DatabasePromise { db in
@@ -242,7 +242,7 @@ extension SQLRelation: Refinable {
annotatedWhenConnected(with: { _ in selection })
}
func filterWhenConnected(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
func filterWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self {
with {
if let old = $0.filterPromise {
$0.filterPromise = DatabasePromise { db in
@@ -259,7 +259,7 @@ extension SQLRelation: Refinable {
filterWhenConnected { _ in predicate }
}
func orderWhenConnected(_ orderings: @escaping (Database) throws -> [SQLOrdering]) -> Self {
func orderWhenConnected(_ orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) -> Self {
with {
$0.ordering = SQLRelation.Ordering(orderings: orderings)
}
@@ -313,13 +313,13 @@ extension SQLRelation: Refinable {
}
}
func groupWhenConnected(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self {
func groupWhenConnected(_ expressions: @escaping @Sendable (Database) throws -> [SQLExpression]) -> Self {
with {
$0.groupPromise = DatabasePromise(expressions)
}
}
func havingWhenConnected(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
func havingWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self {
with {
if let old = $0.havingExpressionPromise {
$0.havingExpressionPromise = DatabasePromise { db in
@@ -672,7 +672,7 @@ struct SQLLimit {
// MARK: - SQLSource
struct SQLSource {
struct SQLSource: Sendable {
var tableName: String
var alias: TableAlias?
@@ -691,7 +691,7 @@ struct SQLSource {
extension SQLRelation {
/// SQLRelation.Ordering provides the order clause to SQLRelation.
struct Ordering {
struct Ordering: Sendable {
private enum Element {
case terms(DatabasePromise<[SQLOrdering]>)
case ordering(SQLRelation.Ordering)
@@ -740,7 +740,7 @@ extension SQLRelation {
isReversed: false)
}
init(orderings: @escaping (Database) throws -> [SQLOrdering]) {
init(orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) {
self.init(
elements: [.terms(DatabasePromise(orderings))],
isReversed: false)
@@ -796,7 +796,7 @@ extension SQLRelation {
/// // SELECT * FROM book WHERE author.id = 1
/// // ~~~~~~~~~~~~~
/// author.request(for: Author.books)
enum SQLAssociationCondition {
enum SQLAssociationCondition: Sendable {
/// A condition based on a foreign key.
case foreignKey(SQLForeignKeyCondition)
@@ -814,7 +814,7 @@ enum SQLAssociationCondition {
/// player[Column("id")] == bonus[Column("playerID")]
/// })
/// Player.with(bonus).joining(required: association)
case expression((_ left: TableAlias, _ right: TableAlias) -> SQLExpression?)
case expression(@Sendable (_ left: TableAlias, _ right: TableAlias) -> SQLExpression?)
/// The condition that does not constrain the two associated tables
/// in any way.
@@ -847,7 +847,7 @@ enum SQLAssociationCondition {
}
/// An association condition based on a foreign key.
struct SQLForeignKeyCondition: Equatable {
struct SQLForeignKeyCondition: Equatable, Sendable {
/// The destination table of an association.
///
/// In `Author.hasMany(Book.self)`, the destination is `book`.
+2 -2
View File
@@ -19,7 +19,7 @@ public struct SQLSelection {
private var impl: Impl
/// The private implementation of the public `SQLSelection`.
private enum Impl {
private enum Impl: Sendable {
/// All columns: `*`
case allColumns
@@ -301,7 +301,7 @@ enum SQLCount {
///
/// - ``AllColumns``
/// - ``SQLSelection``
public protocol SQLSelectable {
public protocol SQLSelectable: Sendable {
/// Returns an SQL selection.
var sqlSelection: SQLSelection { get }
}
+15 -15
View File
@@ -138,7 +138,7 @@
/// ### Database Observation Support
///
/// - ``databaseRegion(_:)``
public struct Table<RowDecoder> {
public struct Table<RowDecoder>: Sendable {
/// The table name.
public var tableName: String
@@ -800,7 +800,7 @@ extension Table {
/// ```
///
/// - parameter db: A database connection.
public func fetchCount(_ db: Database) throws -> Int {
@Sendable public func fetchCount(_ db: Database) throws -> Int {
try all().fetchCount(db)
}
}
@@ -860,7 +860,7 @@ extension Table where RowDecoder: FetchableRecord {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
@Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] {
try all().fetchAll(db)
}
@@ -880,7 +880,7 @@ extension Table where RowDecoder: FetchableRecord {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
@Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? {
try all().fetchOne(db)
}
}
@@ -902,7 +902,7 @@ extension Table where RowDecoder: FetchableRecord & Hashable {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
@Sendable public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
try all().fetchSet(db)
}
}
@@ -961,7 +961,7 @@ extension Table where RowDecoder == Row {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [Row] {
@Sendable public func fetchAll(_ db: Database) throws -> [Row] {
try all().fetchAll(db)
}
@@ -980,7 +980,7 @@ extension Table where RowDecoder == Row {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> Row? {
@Sendable public func fetchOne(_ db: Database) throws -> Row? {
try all().fetchOne(db)
}
@@ -999,7 +999,7 @@ extension Table where RowDecoder == Row {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<Row> {
@Sendable public func fetchSet(_ db: Database) throws -> Set<Row> {
try all().fetchSet(db)
}
}
@@ -1034,7 +1034,7 @@ extension Table where RowDecoder: DatabaseValueConvertible {
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
@Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] {
try all().fetchAll(db)
}
@@ -1048,7 +1048,7 @@ extension Table where RowDecoder: DatabaseValueConvertible {
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
@Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? {
try all().fetchOne(db)
}
}
@@ -1061,7 +1061,7 @@ extension Table where RowDecoder: DatabaseValueConvertible & Hashable {
/// - parameter db: A database connection.
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
@Sendable public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
try all().fetchSet(db)
}
}
@@ -1096,7 +1096,7 @@ extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConv
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
@Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] {
try all().fetchAll(db)
}
@@ -1110,7 +1110,7 @@ extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConv
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
@Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? {
try all().fetchOne(db)
}
}
@@ -1123,7 +1123,7 @@ extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConv
/// - parameter db: A database connection.
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
@Sendable public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
try all().fetchSet(db)
}
}
@@ -1297,7 +1297,7 @@ extension Table {
/// - returns: An association to the common table expression.
public func association<Destination>(
to cte: CommonTableExpression<Destination>,
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
-> JoinAssociation<RowDecoder, Destination>
{
JoinAssociation(
@@ -547,7 +547,7 @@ struct SQLQueryGenerator: Refinable {
/// ORDER BY ... -- ordering
/// LIMIT ... -- limit
private struct SQLQualifiedRelation {
private struct SQLQualifiedRelation: Sendable {
/// All aliases, including aliases of joined relations
var allAliases: [TableAlias] {
joins.reduce(into: [source.alias].compactMap { $0 }) {
@@ -713,7 +713,7 @@ private struct SQLQualifiedRelation {
extension SQLQualifiedRelation: Refinable { }
/// A "qualified" source, where all tables are identified with a table alias.
private struct SQLQualifiedSource {
private struct SQLQualifiedSource: Sendable {
var tableName: String
var alias: TableAlias
@@ -339,7 +339,7 @@ extension TableRecord {
/// - returns: An association to the common table expression.
public static func association<Destination>(
to cte: CommonTableExpression<Destination>,
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
-> JoinAssociation<Self, Destination>
{
JoinAssociation(
@@ -540,6 +540,7 @@ extension TableRecord {
// MARK: - Request for associated records
extension TableRecord where Self: EncodableRecord {
// TODO: GRDB7: require that Self is Sendable
/// Returns a request for the associated record(s).
///
/// For example:
+12 -12
View File
@@ -52,7 +52,7 @@ extension FetchableRecord where Self: TableRecord {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(_ db: Database) throws -> [Self] {
@Sendable public static func fetchAll(_ db: Database) throws -> [Self] {
try all().fetchAll(db)
}
@@ -71,7 +71,7 @@ extension FetchableRecord where Self: TableRecord {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database) throws -> Self? {
@Sendable public static func fetchOne(_ db: Database) throws -> Self? {
try all().fetchOne(db)
}
}
@@ -92,7 +92,7 @@ extension FetchableRecord where Self: TableRecord & Hashable {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(_ db: Database) throws -> Set<Self> {
@Sendable public static func fetchSet(_ db: Database) throws -> Set<Self> {
try all().fetchSet(db)
}
}
@@ -154,7 +154,7 @@ extension FetchableRecord where Self: TableRecord {
/// - keys: A sequence of primary keys.
/// - returns: An array of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll<Keys>(_ db: Database, keys: Keys)
@Sendable public static func fetchAll<Keys>(_ db: Database, keys: Keys)
throws -> [Self]
where Keys: Sequence, Keys.Element: DatabaseValueConvertible
{
@@ -182,7 +182,7 @@ extension FetchableRecord where Self: TableRecord {
/// - key: A primary key value.
/// - returns: An optional record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Self? {
@Sendable public static func fetchOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Self? {
if key.databaseValue.isNull {
// Don't hit the database
return nil
@@ -275,7 +275,7 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa
/// - ids: A collection of primary keys.
/// - returns: An array of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll<IDS>(_ db: Database, ids: IDS) throws -> [Self]
@Sendable public static func fetchAll<IDS>(_ db: Database, ids: IDS) throws -> [Self]
where IDS: Collection, IDS.Element == ID
{
if ids.isEmpty {
@@ -301,7 +301,7 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa
/// - id: A primary key value.
/// - returns: An optional record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, id: ID) throws -> Self? {
@Sendable public static func fetchOne(_ db: Database, id: ID) throws -> Self? {
try filter(id: id).fetchOne(db)
}
@@ -346,7 +346,7 @@ extension FetchableRecord where Self: TableRecord & Hashable {
/// - keys: A sequence of primary keys.
/// - returns: A set of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet<Keys>(_ db: Database, keys: Keys)
@Sendable public static func fetchSet<Keys>(_ db: Database, keys: Keys)
throws -> Set<Self>
where Keys: Sequence, Keys.Element: DatabaseValueConvertible
{
@@ -377,7 +377,7 @@ extension FetchableRecord where Self: TableRecord & Hashable & Identifiable, ID:
/// - ids: A collection of primary keys.
/// - returns: A set of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet<IDS>(_ db: Database, ids: IDS) throws -> Set<Self>
@Sendable public static func fetchSet<IDS>(_ db: Database, ids: IDS) throws -> Set<Self>
where IDS: Collection, IDS.Element == ID
{
if ids.isEmpty {
@@ -449,7 +449,7 @@ extension FetchableRecord where Self: TableRecord {
/// - keys: An array of key dictionaries.
/// - returns: An array of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> [Self] {
@Sendable public static func fetchAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> [Self] {
if keys.isEmpty {
// Avoid hitting the database
return []
@@ -473,7 +473,7 @@ extension FetchableRecord where Self: TableRecord {
/// - key: A key dictionary.
/// - returns: An optional record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]?) throws -> Self? {
@Sendable public static func fetchOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]?) throws -> Self? {
guard let key else {
// Avoid hitting the database
return nil
@@ -527,7 +527,7 @@ extension FetchableRecord where Self: TableRecord & Hashable {
/// - keys: An array of key dictionaries.
/// - returns: A set of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Set<Self> {
@Sendable public static func fetchSet(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Set<Self> {
if keys.isEmpty {
// Avoid hitting the database
return []
+12 -12
View File
@@ -320,7 +320,7 @@ extension FetchableRecord {
/// - adapter: Optional RowAdapter
/// - returns: An array of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
@Sendable public static func fetchAll(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -348,7 +348,7 @@ extension FetchableRecord {
/// - adapter: Optional RowAdapter
/// - returns: An optional record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
@Sendable public static func fetchOne(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -378,7 +378,7 @@ extension FetchableRecord where Self: Hashable {
/// - adapter: Optional RowAdapter
/// - returns: A set of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
@Sendable public static func fetchSet(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
@@ -449,7 +449,7 @@ extension FetchableRecord {
/// - adapter: Optional RowAdapter
/// - returns: An array of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
@Sendable public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -478,7 +478,7 @@ extension FetchableRecord {
/// - adapter: Optional RowAdapter
/// - returns: An optional record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
@Sendable public static func fetchOne(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -509,7 +509,7 @@ extension FetchableRecord where Self: Hashable {
/// - adapter: Optional RowAdapter
/// - returns: A set of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
@Sendable public static func fetchSet(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
@@ -589,7 +589,7 @@ extension FetchableRecord {
/// - sql: a FetchRequest.
/// - returns: An array of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
@Sendable public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
let request = try request.makePreparedRequest(db, forSingleResult: false)
if let supplementaryFetch = request.supplementaryFetch {
let rows = try Row.fetchAll(request.statement, adapter: request.adapter)
@@ -624,7 +624,7 @@ extension FetchableRecord {
/// - sql: a FetchRequest.
/// - returns: An optional record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
@Sendable public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
let request = try request.makePreparedRequest(db, forSingleResult: true)
if let supplementaryFetch = request.supplementaryFetch {
guard let row = try Row.fetchOne(request.statement, adapter: request.adapter) else {
@@ -664,7 +664,7 @@ extension FetchableRecord where Self: Hashable {
/// - sql: a FetchRequest.
/// - returns: A set of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
@Sendable public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
let request = try request.makePreparedRequest(db, forSingleResult: false)
if let supplementaryFetch = request.supplementaryFetch {
let rows = try Row.fetchAll(request.statement, adapter: request.adapter)
@@ -746,7 +746,7 @@ extension FetchRequest where RowDecoder: FetchableRecord {
/// - sql: a FetchRequest.
/// - returns: An array of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
@Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] {
try RowDecoder.fetchAll(db, self)
}
@@ -774,7 +774,7 @@ extension FetchRequest where RowDecoder: FetchableRecord {
/// - sql: a FetchRequest.
/// - returns: An optional record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
@Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? {
try RowDecoder.fetchOne(db, self)
}
}
@@ -805,7 +805,7 @@ extension FetchRequest where RowDecoder: FetchableRecord & Hashable {
/// - sql: a FetchRequest.
/// - returns: A set of records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
@Sendable public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
try RowDecoder.fetchSet(db, self)
}
}
+1 -1
View File
@@ -224,7 +224,7 @@ extension TableRecord {
/// ```
///
/// - parameter db: A database connection.
public static func fetchCount(_ db: Database) throws -> Int {
@Sendable public static func fetchCount(_ db: Database) throws -> Int {
try all().fetchCount(db)
}
}
+2 -3
View File
@@ -43,8 +43,7 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
extension Inflections {
/// The default inflections
public static var `default`: Inflections = {
static func makeEnglishInflections() -> Self {
// Defines the standard inflection rules. These are the starting point
// for new projects and are not considered complete. The current set of
// inflection rules is frozen. This means, we do not change them to
@@ -134,5 +133,5 @@ extension Inflections {
inflections.irregularSuffix("zombie", "zombies")
return inflections
}()
}
}
+8
View File
@@ -32,6 +32,14 @@ extension String {
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
public struct Inflections {
@LockedBox fileprivate static var defaultInflections: Inflections = makeEnglishInflections()
/// The default inflections
public static var `default`: Inflections {
get { defaultInflections }
set { defaultInflections = newValue }
}
private var pluralizeRules: [(NSRegularExpression, String)] = []
private var singularizeRules: [(NSRegularExpression, String)] = []
private var uncountablesRegularExpressions: [String: NSRegularExpression] = [:]
+4 -5
View File
@@ -16,12 +16,11 @@ import Foundation
/// queue, and fulfill GRDB preconditions.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
struct OnDemandFuture<Output, Failure: Error>: Publisher {
typealias Promise = (Result<Output, Failure>) -> Void
typealias Output = Output
typealias Failure = Failure
fileprivate let attemptToFulfill: (@escaping Promise) -> Void
fileprivate let attemptToFulfill: (@escaping @Sendable (Result<Output, Failure>) -> Void) -> Void
init(_ attemptToFulfill: @escaping (@escaping Promise) -> Void) {
init(_ attemptToFulfill: @escaping (@escaping @Sendable (Result<Output, Failure>) -> Void) -> Void) {
self.attemptToFulfill = attemptToFulfill
}
@@ -34,8 +33,8 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
private class OnDemandFutureSubscription<Downstream: Subscriber>: Subscription {
typealias Promise = (Result<Downstream.Input, Downstream.Failure>) -> Void
private final class OnDemandFutureSubscription<Downstream: Subscriber>: Subscription, @unchecked Sendable {
typealias Promise = @Sendable (Result<Downstream.Input, Downstream.Failure>) -> Void
private enum State {
case waitingForDemand(downstream: Downstream, attemptToFulfill: (@escaping Promise) -> Void)
+2
View File
@@ -207,6 +207,8 @@ extension OrderedDictionary: CustomStringConvertible {
}
}
extension OrderedDictionary: Sendable where Key: Sendable, Value: Sendable { }
extension Dictionary {
init(_ orderedDictionary: OrderedDictionary<Key, Value>) {
self = orderedDictionary.dictionary
+6 -5
View File
@@ -35,8 +35,9 @@ import Dispatch
/// got 2
/// got 1
/// got 3
final class Pool<T> {
private class Item {
final class Pool<T: Sendable>: @unchecked Sendable {
// @unchecked Sendable because protected by Pool.
private class Item: @unchecked Sendable {
let element: T
var isAvailable: Bool
@@ -75,7 +76,7 @@ final class Pool<T> {
/// Returns a tuple (element, release)
/// Client must call release(), only once, after the element has been used.
func get() throws -> (element: T, release: (PoolCompletion) -> Void) {
func get() throws -> (element: T, release: @Sendable (PoolCompletion) -> Void) {
try barrierQueue.sync {
itemsSemaphore.wait()
itemsGroup.enter()
@@ -107,7 +108,7 @@ final class Pool<T> {
///
/// - important: The `execute` argument is executed in a serial dispatch
/// queue, so make sure you use the element asynchronously.
func asyncGet(_ execute: @escaping (Result<(element: T, release: (PoolCompletion) -> Void), any Error>) -> Void) {
func asyncGet(_ execute: @escaping @Sendable (Result<(element: T, release: @Sendable (PoolCompletion) -> Void), any Error>) -> Void) {
// Inspired by https://khanlou.com/2016/04/the-GCD-handbook/
// > We wait on the semaphore in the serial queue, which means that
// > we’ll have at most one blocked thread when we reach maximum
@@ -172,7 +173,7 @@ final class Pool<T> {
/// Asynchronously runs the `barrier` function when no element is used, and
/// before any other element is dequeued.
func asyncBarrier(execute barrier: @escaping () -> Void) {
func asyncBarrier(execute barrier: @escaping @Sendable () -> Void) {
barrierQueue.async(flags: [.barrier]) {
self.itemsGroup.wait()
barrier()
+16 -3
View File
@@ -67,7 +67,7 @@ extension Dictionary {
}
extension DispatchQueue {
private static var mainKey: DispatchSpecificKey<()> = {
private static let mainKey: DispatchSpecificKey<()> = {
let key = DispatchSpecificKey<()>()
DispatchQueue.main.setSpecific(key: key, value: ())
return key
@@ -124,8 +124,21 @@ struct PrintOutputStream: TextOutputStream {
}
}
final class LockedTextOutputStream: @unchecked Sendable {
var stream: any TextOutputStream
let lock = NSLock()
init(stream: any TextOutputStream) {
self.stream = stream
}
func write(_ string: String) {
lock.lock()
defer { lock.unlock() }
stream.write(string)
}
}
/// Concatenates two functions
func concat(_ rhs: (() -> Void)?, _ lhs: (() -> Void)?) -> (() -> Void)? {
func concat(_ rhs: (@Sendable () -> Void)?, _ lhs: (@Sendable () -> Void)?) -> (@Sendable () -> Void)? {
switch (rhs, lhs) {
case let (rhs, nil):
return rhs
@@ -140,7 +153,7 @@ func concat(_ rhs: (() -> Void)?, _ lhs: (() -> Void)?) -> (() -> Void)? {
}
/// Concatenates two functions
func concat<T>(_ rhs: ((T) -> Void)?, _ lhs: ((T) -> Void)?) -> ((T) -> Void)? {
func concat<T>(_ rhs: (@Sendable (T) -> Void)?, _ lhs: (@Sendable(T) -> Void)?) -> (@Sendable(T) -> Void)? {
switch (rhs, lhs) {
case let (rhs, nil):
return rhs
+16 -12
View File
@@ -5,7 +5,7 @@
/// ### Supporting Types
///
/// - ``AnyDatabaseCancellable``
public protocol DatabaseCancellable {
public protocol DatabaseCancellable: Sendable {
/// Cancel the activity.
func cancel()
}
@@ -15,31 +15,35 @@ public protocol DatabaseCancellable {
///
/// An `AnyDatabaseCancellable` instance automatically calls ``cancel()``
/// when deinitialized.
public class AnyDatabaseCancellable: DatabaseCancellable {
private var _cancel: (() -> Void)?
public class AnyDatabaseCancellable: DatabaseCancellable, @unchecked Sendable {
@LockedBox private var _cancel: (() -> Void)?
var isCancelled: Bool {
_cancel == nil
}
/// Initializes the cancellable object with the given cancel-time closure.
public init(cancel: @escaping () -> Void) {
public init(cancel: @escaping @Sendable () -> Void) {
_cancel = cancel
}
/// Creates a cancellable object that forwards cancellation to `base`.
public convenience init(_ base: some DatabaseCancellable) {
var cancellable = Optional.some(base)
self.init {
cancellable?.cancel()
cancellable = nil // Release memory
base.cancel()
}
}
deinit {
_cancel?()
cancel()
}
public func cancel() {
// Don't prevent multiple concurrent calls to _cancel, because it is
// pointless. But release memory!
_cancel?()
_cancel = nil
let cancel = $_cancel.update {
let result = $0
$0 = nil
return result
}
cancel?()
}
}
@@ -18,7 +18,7 @@ import Foundation
/// reducing stage.
///
/// **Notify** is calling user callbacks, in case of database change or error.
final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObservationScheduler> {
final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObservationScheduler>: @unchecked Sendable {
// MARK: - Configuration
//
// Configuration is not mutable.
@@ -72,7 +72,7 @@ final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObser
// be notified. See error catching clauses.
/// Ability to access the database
private struct DatabaseAccess {
private struct DatabaseAccess: Sendable {
/// The observed DatabasePool.
let dbPool: DatabasePool
@@ -117,7 +117,7 @@ final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObser
/// Ability to notify observation events
private struct NotificationCallbacks {
let events: ValueObservationEvents
let onChange: (Reducer.Value) -> Void
let onChange: @Sendable (Reducer.Value) -> Void
}
/// Relationship with the `TransactionObserver` protocol
@@ -161,7 +161,7 @@ final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObser
trackingMode: ValueObservationTrackingMode,
reducer: Reducer,
events: ValueObservationEvents,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
{
// Configuration
self.scheduler = scheduler
@@ -373,7 +373,7 @@ extension ValueConcurrentObserver {
//
// Reducing is performed asynchronously, so that we do not lock
// a database dispatch queue longer than necessary.
self.reduceQueue.async {
self.reduceQueue.async { [fetchedValue] in
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
guard isNotifying else { return /* Cancelled */ }
@@ -383,7 +383,7 @@ extension ValueConcurrentObserver {
}
// Notify
self.scheduler.schedule {
self.scheduler.schedule { [initialValue] in
let onChange = self.lock.synchronized { self.notificationCallbacks?.onChange }
guard let onChange else { return /* Cancelled */ }
onChange(initialValue)
@@ -419,24 +419,24 @@ extension ValueConcurrentObserver {
initialFetchTransaction: WALSnapshotTransaction,
initialRegion: DatabaseRegion)
{
// We'll start the observation when we can access the writer
// connection. Until then, maybe the database has been modified
// since the initial fetch: we'll then need to notify a fresh value.
//
// To know if the database has been modified between the initial
// fetch and the writer access, we'll compare WAL snapshots.
//
// WAL snapshots can only be compared if the database is not
// checkpointed. That's why we'll keep `initialFetchTransaction`
// alive until the comparison is done.
//
// However, we want to release `initialFetchTransaction` as soon as
// possible, so that the reader connection it holds becomes
// available for other reads. It will be released when this optional
// is set to nil:
var initialFetchTransaction: WALSnapshotTransaction? = initialFetchTransaction
databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in
databaseAccess.dbPool.asyncWriteWithoutTransaction { [initialFetchTransaction] writerDB in
// We'll start the observation when we can access the writer
// connection. Until then, maybe the database has been modified
// since the initial fetch: we'll then need to notify a fresh value.
//
// To know if the database has been modified between the initial
// fetch and the writer access, we'll compare WAL snapshots.
//
// WAL snapshots can only be compared if the database is not
// checkpointed. That's why we'll keep `initialFetchTransaction`
// alive until the comparison is done.
//
// However, we want to release `initialFetchTransaction` as soon as
// possible, so that the reader connection it holds becomes
// available for other reads. It will be released when this optional
// is set to nil:
var initialFetchTransaction: WALSnapshotTransaction? = initialFetchTransaction
let events = self.lock.synchronized { self.notificationCallbacks?.events }
guard let events else { return /* Cancelled */ }
@@ -21,7 +21,7 @@ import Foundation
final class ValueWriteOnlyObserver<
Writer: DatabaseWriter,
Reducer: ValueReducer,
Scheduler: ValueObservationScheduler>
Scheduler: ValueObservationScheduler>: @unchecked Sendable
{
// MARK: - Configuration
//
@@ -76,7 +76,7 @@ final class ValueWriteOnlyObserver<
// be notified. See error catching clauses.
/// Ability to access the database
private struct DatabaseAccess {
private struct DatabaseAccess: Sendable {
/// The observed DatabaseWriter.
let writer: Writer
@@ -112,7 +112,7 @@ final class ValueWriteOnlyObserver<
/// Ability to notify observation events
private struct NotificationCallbacks {
let events: ValueObservationEvents
let onChange: (Reducer.Value) -> Void
let onChange: @Sendable (Reducer.Value) -> Void
}
/// Relationship with the `TransactionObserver` protocol
@@ -150,7 +150,7 @@ final class ValueWriteOnlyObserver<
trackingMode: ValueObservationTrackingMode,
reducer: Reducer,
events: ValueObservationEvents,
onChange: @escaping (Reducer.Value) -> Void)
onChange: @escaping @Sendable (Reducer.Value) -> Void)
{
// Configuration
self.scheduler = scheduler
+3 -3
View File
@@ -1,10 +1,10 @@
extension ValueReducers {
/// A `ValueReducer` that perform database fetches.
public struct Fetch<Value>: ValueReducer {
private let __fetch: (Database) throws -> Value
public struct Fetch<Value: Sendable>: ValueReducer {
private let __fetch: @Sendable (Database) throws -> Value
/// Creates a reducer which passes raw fetched values through.
init(fetch: @escaping (Database) throws -> Value) {
init(fetch: @escaping @Sendable (Database) throws -> Value) {
self.__fetch = fetch
}
+4 -4
View File
@@ -18,7 +18,7 @@ extension ValueObservation {
///
/// - parameter transform: A closure that takes one value as its parameter
/// and returns a new value.
public func map<T>(_ transform: @escaping (Reducer.Value) throws -> T)
public func map<T>(_ transform: @escaping @Sendable (Reducer.Value) throws -> T)
-> ValueObservation<ValueReducers.Map<Reducer, T>>
{
mapReducer { ValueReducers.Map($0, transform) }
@@ -30,11 +30,11 @@ extension ValueReducers {
/// passed through a transform function.
///
/// See ``ValueObservation/map(_:)``.
public struct Map<Base: _ValueReducer, Value>: _ValueReducer {
public struct Map<Base: _ValueReducer, Value: Sendable>: _ValueReducer {
private var base: Base
private let transform: (Base.Value) throws -> Value
private let transform: @Sendable (Base.Value) throws -> Value
init(_ base: Base, _ transform: @escaping (Base.Value) throws -> Value) {
init(_ base: Base, _ transform: @escaping @Sendable (Base.Value) throws -> Value) {
self.base = base
self.transform = transform
}
@@ -5,7 +5,7 @@ extension ValueObservation {
/// - parameter predicate: A closure to evaluate whether two values are
/// equivalent, for purposes of filtering. Return true from this closure
/// to indicate that the second element is a duplicate of the first.
public func removeDuplicates(by predicate: @escaping (Reducer.Value, Reducer.Value) -> Bool)
public func removeDuplicates(by predicate: @escaping @Sendable (Reducer.Value, Reducer.Value) -> Bool)
-> ValueObservation<ValueReducers.RemoveDuplicates<Reducer>>
{
mapReducer { ValueReducers.RemoveDuplicates($0, predicate: predicate) }
@@ -58,7 +58,9 @@ extension ValueObservation where Reducer.Value: Equatable {
public func removeDuplicates()
-> ValueObservation<ValueReducers.RemoveDuplicates<Reducer>>
{
mapReducer { ValueReducers.RemoveDuplicates($0, predicate: ==) }
mapReducer {
ValueReducers.RemoveDuplicates($0, predicate: { $0 == $1 })
}
}
}
@@ -70,9 +72,9 @@ extension ValueReducers {
public struct RemoveDuplicates<Base: _ValueReducer>: _ValueReducer {
private var base: Base
private var previousValue: Base.Value?
private var predicate: (Base.Value, Base.Value) -> Bool
private var predicate: @Sendable (Base.Value, Base.Value) -> Bool
init(_ base: Base, predicate: @escaping (Base.Value, Base.Value) -> Bool) {
init(_ base: Base, predicate: @escaping @Sendable (Base.Value, Base.Value) -> Bool) {
self.base = base
self.predicate = predicate
}
+2 -2
View File
@@ -6,8 +6,8 @@ extension ValueReducers {
/// and ``ValueObservation/print(_:to:)``.
public struct Trace<Base: _ValueReducer>: _ValueReducer {
var base: Base
let willFetch: () -> Void
let didReceiveValue: (Base.Value) -> Void
let willFetch: @Sendable () -> Void
let didReceiveValue: @Sendable (Base.Value) -> Void
public mutating func _value(_ fetched: Base.Fetched) throws -> Base.Value? {
guard let value = try base._value(fetched) else {
@@ -1,10 +1,10 @@
/// Implementation details of `ValueReducer`.
public protocol _ValueReducer {
public protocol _ValueReducer: Sendable {
/// The type of fetched database values
associatedtype Fetched
associatedtype Fetched: Sendable
/// The type of observed values
associatedtype Value
associatedtype Value: Sendable
/// Transforms a fetched value into an eventual observed value. Returns nil
/// when observer should not be notified.
@@ -1,7 +1,7 @@
import Foundation
/// The extent of the shared subscription to a ``SharedValueObservation``.
public enum SharedValueObservationExtent {
public enum SharedValueObservationExtent: Sendable {
/// The ``SharedValueObservation`` starts a single database observation,
/// which stops when the `SharedValueObservation` is deallocated and all
/// subscriptions terminated.
@@ -167,7 +167,7 @@ extension ValueObservation {
/// let cancellable1 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...)
/// let cancellable2 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...)
/// ```
public final class SharedValueObservation<Element> {
public final class SharedValueObservation<Element: Sendable>: @unchecked Sendable {
private let scheduler: any ValueObservationScheduler
private let extent: SharedValueObservationExtent
private let startObservation: ValueObservationStart<Element>
@@ -179,11 +179,14 @@ public final class SharedValueObservation<Element> {
private var cancellable: AnyDatabaseCancellable?
private var lastResult: Result<Element, any Error>?
private final class Client {
var onError: (any Error) -> Void
var onChange: (Element) -> Void
private final class Client: Sendable {
let onError: @Sendable (any Error) -> Void
let onChange: @Sendable (Element) -> Void
init(onError: @escaping (any Error) -> Void, onChange: @escaping (Element) -> Void) {
init(
onError: @escaping @Sendable (any Error) -> Void,
onChange: @escaping @Sendable (Element) -> Void)
{
self.onError = onError
self.onChange = onChange
}
@@ -224,8 +227,8 @@ public final class SharedValueObservation<Element> {
/// fresh value.
/// - returns: A DatabaseCancellable that can stop the observation.
public func start(
onError: @escaping (any Error) -> Void,
onChange: @escaping (Element) -> Void)
onError: @escaping @Sendable (any Error) -> Void,
onChange: @escaping @Sendable (Element) -> Void)
-> AnyDatabaseCancellable
{
synchronized {
+29 -37
View File
@@ -4,7 +4,7 @@ import Combine
import Dispatch
import Foundation
public struct ValueObservation<Reducer: _ValueReducer> {
public struct ValueObservation<Reducer: _ValueReducer>: Sendable {
var events = ValueObservationEvents()
/// A boolean value indicating whether the observation requires write access
@@ -30,10 +30,10 @@ public struct ValueObservation<Reducer: _ValueReducer> {
/// The reducer is created when observation starts, and is triggered upon
/// each database change.
var makeReducer: () -> Reducer
var makeReducer: @Sendable () -> Reducer
/// Returns a ValueObservation with a transformed reducer.
func mapReducer<R>(_ transform: @escaping (Reducer) -> R) -> ValueObservation<R> {
func mapReducer<R>(_ transform: @escaping @Sendable (Reducer) -> R) -> ValueObservation<R> {
let makeReducer = self.makeReducer
return ValueObservation<R>(
events: events,
@@ -44,7 +44,7 @@ public struct ValueObservation<Reducer: _ValueReducer> {
}
/// Configures the tracked region
enum ValueObservationTrackingMode {
enum ValueObservationTrackingMode: Sendable {
/// The tracked region is constant and explicit.
///
/// Use case:
@@ -73,17 +73,17 @@ enum ValueObservationTrackingMode {
case nonConstantRegionRecordedFromSelection
}
struct ValueObservationEvents: Refinable {
var willStart: (() -> Void)?
var willTrackRegion: ((DatabaseRegion) -> Void)?
var databaseDidChange: (() -> Void)?
var didFail: ((any Error) -> Void)?
var didCancel: (() -> Void)?
struct ValueObservationEvents: Sendable, Refinable {
var willStart: (@Sendable () -> Void)?
var willTrackRegion: (@Sendable (DatabaseRegion) -> Void)?
var databaseDidChange: (@Sendable () -> Void)?
var didFail: (@Sendable (any Error) -> Void)?
var didCancel: (@Sendable () -> Void)?
}
typealias ValueObservationStart<T> = (
_ onError: @escaping (any Error) -> Void,
_ onChange: @escaping (T) -> Void)
typealias ValueObservationStart<T> = @Sendable (
_ onError: @escaping @Sendable (any Error) -> Void,
_ onChange: @escaping @Sendable (T) -> Void)
-> AnyDatabaseCancellable
extension ValueObservation: Refinable {
@@ -138,8 +138,8 @@ extension ValueObservation: Refinable {
public func start(
in reader: some DatabaseReader,
scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main),
onError: @escaping (any Error) -> Void,
onChange: @escaping (Reducer.Value) -> Void)
onError: @escaping @Sendable (any Error) -> Void,
onChange: @escaping @Sendable (Reducer.Value) -> Void)
-> AnyDatabaseCancellable
where Reducer: ValueReducer
{
@@ -175,13 +175,13 @@ extension ValueObservation: Refinable {
/// - returns: A `ValueObservation` that performs the specified closures
/// when ValueObservation events occur.
public func handleEvents(
willStart: (() -> Void)? = nil,
willFetch: (() -> Void)? = nil,
willTrackRegion: ((DatabaseRegion) -> Void)? = nil,
databaseDidChange: (() -> Void)? = nil,
didReceiveValue: ((Reducer.Value) -> Void)? = nil,
didFail: ((any Error) -> Void)? = nil,
didCancel: (() -> Void)? = nil)
willStart: (@Sendable () -> Void)? = nil,
willFetch: (@Sendable () -> Void)? = nil,
willTrackRegion: (@Sendable (DatabaseRegion) -> Void)? = nil,
databaseDidChange: (@Sendable () -> Void)? = nil,
didReceiveValue: (@Sendable (Reducer.Value) -> Void)? = nil,
didFail: (@Sendable (any Error) -> Void)? = nil,
didCancel: (@Sendable () -> Void)? = nil)
-> ValueObservation<ValueReducers.Trace<Reducer>>
{
self
@@ -231,33 +231,25 @@ extension ValueObservation: Refinable {
/// used to log messages to other destinations.
public func print(
_ prefix: String = "",
to stream: (any TextOutputStream)? = nil)
to stream: (any TextOutputStream & Sendable)? = nil)
-> ValueObservation<ValueReducers.Trace<Reducer>>
{
let lock = NSLock()
let prefix = prefix.isEmpty ? "" : "\(prefix): "
var stream = stream ?? PrintOutputStream()
let stream = LockedTextOutputStream(stream: stream ?? PrintOutputStream())
return handleEvents(
willStart: {
lock.lock(); defer { lock.unlock() }
stream.write("\(prefix)start") },
willFetch: {
lock.lock(); defer { lock.unlock() }
stream.write("\(prefix)fetch") },
willTrackRegion: {
lock.lock(); defer { lock.unlock() }
stream.write("\(prefix)tracked region: \($0)") },
databaseDidChange: {
lock.lock(); defer { lock.unlock() }
stream.write("\(prefix)database did change") },
didReceiveValue: {
lock.lock(); defer { lock.unlock() }
stream.write("\(prefix)value: \($0)") },
didFail: {
lock.lock(); defer { lock.unlock() }
stream.write("\(prefix)failure: \($0)") },
didCancel: {
lock.lock(); defer { lock.unlock() }
stream.write("\(prefix)cancel") })
}
@@ -472,7 +464,7 @@ extension DatabasePublishers {
}
}
private class ValueSubscription<Downstream: Subscriber>: Subscription
private class ValueSubscription<Downstream: Subscriber>: Subscription, @unchecked Sendable
where Downstream.Failure == any Error
{
private struct WaitingForDemand {
@@ -703,7 +695,7 @@ extension ValueObservation {
///
/// - parameter fetch: The closure that fetches the observed value.
public static func trackingConstantRegion<Value>(
_ fetch: @escaping (Database) throws -> Value)
_ fetch: @escaping @Sendable (Database) throws -> Value)
-> Self
where Reducer == ValueReducers.Fetch<Value>
{
@@ -764,7 +756,7 @@ extension ValueObservation {
public static func tracking<Value>(
region: any DatabaseRegionConvertible,
_ otherRegions: any DatabaseRegionConvertible...,
fetch: @escaping (Database) throws -> Value)
fetch: @escaping @Sendable (Database) throws -> Value)
-> Self
where Reducer == ValueReducers.Fetch<Value>
{
@@ -820,7 +812,7 @@ extension ValueObservation {
/// - parameter fetch: The closure that fetches the observed value.
public static func tracking<Value>(
regions: [any DatabaseRegionConvertible],
fetch: @escaping (Database) throws -> Value)
fetch: @escaping @Sendable (Database) throws -> Value)
-> Self
where Reducer == ValueReducers.Fetch<Value>
{
@@ -877,7 +869,7 @@ extension ValueObservation {
///
/// - parameter fetch: The closure that fetches the observed value.
public static func tracking<Value>(
_ fetch: @escaping (Database) throws -> Value)
_ fetch: @escaping @Sendable (Database) throws -> Value)
-> Self
where Reducer == ValueReducers.Fetch<Value>
{
@@ -11,17 +11,17 @@ import Foundation
/// - ``immediate``
/// - ``AsyncValueObservationScheduler``
/// - ``ImmediateValueObservationScheduler``
public protocol ValueObservationScheduler {
public protocol ValueObservationScheduler: Sendable {
/// Returns whether the initial value should be immediately notified.
///
/// If the result is true, then this method was called on the main thread.
func immediateInitialValue() -> Bool
func schedule(_ action: @escaping () -> Void)
func schedule(_ action: @escaping @Sendable () -> Void)
}
extension ValueObservationScheduler {
func scheduleInitial(_ action: @escaping () -> Void) {
func scheduleInitial(_ action: @escaping @Sendable () -> Void) {
if immediateInitialValue() {
action()
} else {
@@ -42,7 +42,7 @@ public struct AsyncValueObservationScheduler: ValueObservationScheduler {
public func immediateInitialValue() -> Bool { false }
public func schedule(_ action: @escaping () -> Void) {
public func schedule(_ action: @escaping @Sendable () -> Void) {
queue.async(execute: action)
}
}
@@ -86,7 +86,7 @@ public struct ImmediateValueObservationScheduler: ValueObservationScheduler {
return true
}
public func schedule(_ action: @escaping () -> Void) {
public func schedule(_ action: @escaping @Sendable () -> Void) {
DispatchQueue.main.async(execute: action)
}
}
@@ -43,7 +43,7 @@ private struct UserDatabaseValueConvertible1 : DatabaseValueConvertible {
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UserDatabaseValueConvertible1? { preconditionFailure() }
}
private class UserDatabaseValueConvertible2 : DatabaseValueConvertible {
private final class UserDatabaseValueConvertible2 : DatabaseValueConvertible {
var databaseValue: DatabaseValue { preconditionFailure() }
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { preconditionFailure() }
}
@@ -39,10 +39,11 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
func assertTransaction_registerBefore(start startSQL: String, end endSQL: String, isNotifiedAs expectedCompletion: Database.TransactionCompletion) throws {
class Witness { }
class Recorder { var commitCount = 0 }
let dbQueue = try makeDatabaseQueue()
try dbQueue.writeWithoutTransaction { db in
var commitCount = 0
let recorder = Recorder()
weak var deallocationWitness: Witness? = nil
do {
let witness = Witness()
@@ -51,19 +52,19 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
db.afterNextTransaction { _ in
// use witness
withExtendedLifetime(witness, { })
commitCount += 1
recorder.commitCount += 1
}
}
XCTAssertNotNil(deallocationWitness)
XCTAssertEqual(commitCount, 0)
XCTAssertEqual(recorder.commitCount, 0)
try db.execute(sql: startSQL)
try db.execute(sql: endSQL)
switch expectedCompletion {
case .commit:
XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)")
XCTAssertEqual(recorder.commitCount, 1, "\(startSQL); \(endSQL)")
case .rollback:
XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)")
XCTAssertEqual(recorder.commitCount, 0, "\(startSQL); \(endSQL)")
}
XCTAssertNil(deallocationWitness)
@@ -73,20 +74,23 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
}
switch expectedCompletion {
case .commit:
XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)")
XCTAssertEqual(recorder.commitCount, 1, "\(startSQL); \(endSQL)")
case .rollback:
XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)")
XCTAssertEqual(recorder.commitCount, 0, "\(startSQL); \(endSQL)")
}
}
}
func assertTransaction_registerBetween(start startSQL: String, end endSQL: String, isNotifiedAs expectedCompletion: Database.TransactionCompletion) throws {
class Witness { }
class Recorder {
var commitCount = 0
var rollbackCount = 0
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.writeWithoutTransaction { db in
var commitCount = 0
var rollbackCount = 0
let recorder = Recorder()
try db.execute(sql: startSQL)
weak var deallocationWitness: Witness? = nil
@@ -98,25 +102,25 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
onCommit: { _ in
// use witness
withExtendedLifetime(witness, { })
commitCount += 1
recorder.commitCount += 1
},
onRollback: { _ in
// use witness
withExtendedLifetime(witness, { })
rollbackCount += 1
recorder.rollbackCount += 1
})
}
XCTAssertNotNil(deallocationWitness)
XCTAssertEqual(commitCount, 0)
XCTAssertEqual(recorder.commitCount, 0)
try db.execute(sql: endSQL)
switch expectedCompletion {
case .commit:
XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)")
XCTAssertEqual(rollbackCount, 0, "\(startSQL); \(endSQL)")
XCTAssertEqual(recorder.commitCount, 1, "\(startSQL); \(endSQL)")
XCTAssertEqual(recorder.rollbackCount, 0, "\(startSQL); \(endSQL)")
case .rollback:
XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)")
XCTAssertEqual(rollbackCount, 1, "\(startSQL); \(endSQL)")
XCTAssertEqual(recorder.commitCount, 0, "\(startSQL); \(endSQL)")
XCTAssertEqual(recorder.rollbackCount, 1, "\(startSQL); \(endSQL)")
}
XCTAssertNil(deallocationWitness)
@@ -126,11 +130,11 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
}
switch expectedCompletion {
case .commit:
XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)")
XCTAssertEqual(rollbackCount, 0, "\(startSQL); \(endSQL)")
XCTAssertEqual(recorder.commitCount, 1, "\(startSQL); \(endSQL)")
XCTAssertEqual(recorder.rollbackCount, 0, "\(startSQL); \(endSQL)")
case .rollback:
XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)")
XCTAssertEqual(rollbackCount, 1, "\(startSQL); \(endSQL)")
XCTAssertEqual(recorder.commitCount, 0, "\(startSQL); \(endSQL)")
XCTAssertEqual(recorder.rollbackCount, 1, "\(startSQL); \(endSQL)")
}
}
}
@@ -6,40 +6,46 @@ class DatabaseConfigurationTests: GRDBTestCase {
func testPrepareDatabase() throws {
// prepareDatabase is called when connection opens
var connectionCount = 0
class Recorder {
var connectionCount = 0
}
let recorder = Recorder()
var configuration = Configuration()
configuration.prepareDatabase { db in
connectionCount += 1
recorder.connectionCount += 1
}
_ = try DatabaseQueue(configuration: configuration)
XCTAssertEqual(connectionCount, 1)
XCTAssertEqual(recorder.connectionCount, 1)
_ = try makeDatabaseQueue(configuration: configuration)
XCTAssertEqual(connectionCount, 2)
XCTAssertEqual(recorder.connectionCount, 2)
let pool = try makeDatabasePool(configuration: configuration)
XCTAssertEqual(connectionCount, 3)
XCTAssertEqual(recorder.connectionCount, 3)
try pool.read { _ in }
XCTAssertEqual(connectionCount, 4)
XCTAssertEqual(recorder.connectionCount, 4)
try pool.makeSnapshot().read { _ in }
XCTAssertEqual(connectionCount, 5)
XCTAssertEqual(recorder.connectionCount, 5)
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
try pool.makeSnapshotPool().read { _ in }
XCTAssertEqual(connectionCount, 6)
XCTAssertEqual(recorder.connectionCount, 6)
#endif
}
func testPrepareDatabaseError() throws {
struct TestError: Error { }
var error: TestError?
class Context {
var error: TestError?
}
let context = Context()
var configuration = Configuration()
configuration.prepareDatabase { db in
if let error {
if let error = context.error {
throw error
}
}
@@ -47,36 +53,36 @@ class DatabaseConfigurationTests: GRDBTestCase {
// TODO: what about in-memory DatabaseQueue???
do {
error = TestError()
context.error = TestError()
_ = try makeDatabaseQueue(configuration: configuration)
XCTFail("Expected TestError")
} catch is TestError { }
do {
error = TestError()
context.error = TestError()
_ = try makeDatabasePool(configuration: configuration)
XCTFail("Expected TestError")
} catch is TestError { }
do {
error = nil
context.error = nil
let pool = try makeDatabasePool(configuration: configuration)
do {
error = TestError()
context.error = TestError()
try pool.read { _ in }
XCTFail("Expected TestError")
} catch is TestError { }
do {
error = TestError()
context.error = TestError()
_ = try pool.makeSnapshot()
XCTFail("Expected TestError")
} catch is TestError { }
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
do {
error = TestError()
context.error = TestError()
_ = try pool.makeSnapshotPool()
XCTFail("Expected TestError")
} catch is TestError { }
+7 -4
View File
@@ -122,7 +122,7 @@ class DatabaseMigratorTests : GRDBTestCase {
}
let expectation = self.expectation(description: "")
migrator.asyncMigrate(writer, completion: { dbResult in
migrator.asyncMigrate(writer, completion: { [migrator2] dbResult in
// No migration error
let db = try! dbResult.get()
@@ -789,13 +789,16 @@ class DatabaseMigratorTests : GRDBTestCase {
var migrator = DatabaseMigrator()
migrator.eraseDatabaseOnSchemaChange = true
var witness = 1
class Context {
var value = 1
}
let context = Context()
migrator.registerMigration("1") { db in
try db.execute(sql: """
CREATE TABLE t1(id INTEGER PRIMARY KEY);
INSERT INTO t1(id) VALUES (?)
""", arguments: [witness])
witness += 1
""", arguments: [context.value])
context.value += 1
}
let dbQueue = try makeDatabaseQueue()
@@ -1146,13 +1146,16 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
func testAsyncConcurrentReadOpensATransaction() throws {
let dbPool = try makeDatabasePool()
var isInsideTransaction: Bool? = nil
class Recorder {
var isInsideTransaction: Bool? = nil
}
let recorder = Recorder()
let expectation = self.expectation(description: "read")
dbPool.writeWithoutTransaction { db in
dbPool.asyncConcurrentRead { dbResult in
do {
let db = try dbResult.get()
isInsideTransaction = db.isInsideTransaction
recorder.isInsideTransaction = db.isInsideTransaction
do {
try db.execute(sql: "BEGIN DEFERRED TRANSACTION")
XCTFail("Expected error")
@@ -1165,7 +1168,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
}
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(isInsideTransaction, true)
XCTAssertEqual(recorder.isInsideTransaction, true)
}
func testAsyncConcurrentReadOutsideOfTransaction() throws {
@@ -1188,14 +1191,17 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
// <
// }
var count: Int? = nil
class Recorder {
var count: Int? = nil
}
let recorder = Recorder()
let expectation = self.expectation(description: "read")
try dbPool.writeWithoutTransaction { db in
dbPool.asyncConcurrentRead { dbResult in
do {
_ = s1.wait(timeout: .distantFuture)
let db = try dbResult.get()
count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM persons")!
recorder.count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM persons")!
} catch {
XCTFail("Unexpected error: \(error)")
}
@@ -1205,14 +1211,17 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
s1.signal()
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(count, 0)
XCTAssertEqual(recorder.count, 0)
}
func testAsyncConcurrentReadError() throws {
// Necessary for this test to run as quickly as possible
dbConfiguration.readonlyBusyMode = .immediateError
let dbPool = try makeDatabasePool()
var readError: DatabaseError? = nil
class Recorder {
var readError: DatabaseError? = nil
}
let recorder = Recorder()
let expectation = self.expectation(description: "read")
try dbPool.writeWithoutTransaction { db in
try db.execute(sql: "PRAGMA locking_mode=EXCLUSIVE")
@@ -1224,12 +1233,12 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
XCTFail("Unexpected result: \(dbResult)")
return
}
readError = dbError
recorder.readError = dbError
expectation.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(readError!.resultCode, .SQLITE_BUSY)
XCTAssertEqual(readError!.message!, "database is locked")
XCTAssertEqual(recorder.readError!.resultCode, .SQLITE_BUSY)
XCTAssertEqual(recorder.readError!.message!, "database is locked")
}
}
+7 -3
View File
@@ -205,15 +205,19 @@ class DatabaseReaderTests : GRDBTestCase {
// MARK: - AsyncRead
func testAsyncRead() throws {
class Recorder {
var count: Int?
}
func test(_ dbReader: some DatabaseReader) throws {
let expectation = self.expectation(description: "updates")
let semaphore = DispatchSemaphore(value: 0)
var count: Int?
let recorder = Recorder()
dbReader.asyncRead { dbResult in
// Make sure this block executes asynchronously
semaphore.wait()
do {
count = try Int.fetchOne(dbResult.get(), sql: "SELECT COUNT(*) FROM sqlite_master")
recorder.count = try Int.fetchOne(dbResult.get(), sql: "SELECT COUNT(*) FROM sqlite_master")
} catch {
XCTFail("Unexpected error: \(error)")
}
@@ -222,7 +226,7 @@ class DatabaseReaderTests : GRDBTestCase {
semaphore.signal()
waitForExpectations(timeout: 1, handler: nil)
XCTAssertNotNil(count)
XCTAssertNotNil(recorder.count)
}
try test(makeDatabaseQueue())
@@ -15,12 +15,15 @@ class DatabaseRegionObservationTests: GRDBTestCase {
let observation = DatabaseRegionObservation(tracking: .fullDatabase)
var count = 0
class Recorder {
var count = 0
}
let recorder = Recorder()
let cancellable = observation.start(
in: dbQueue,
onError: { XCTFail("Unexpected error: \($0)") },
onChange: { db in
count += 1
recorder.count += 1
notificationExpectation.fulfill()
})
@@ -37,7 +40,7 @@ class DatabaseRegionObservationTests: GRDBTestCase {
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(count, 3)
XCTAssertEqual(recorder.count, 3)
}
}
@@ -84,12 +87,15 @@ class DatabaseRegionObservationTests: GRDBTestCase {
let observation = DatabaseRegionObservation(tracking: request1, request2)
var count = 0
class Recorder {
var count = 0
}
let recorder = Recorder()
let cancellable = observation.start(
in: dbQueue,
onError: { XCTFail("Unexpected error: \($0)") },
onChange: { db in
count += 1
recorder.count += 1
notificationExpectation.fulfill()
})
@@ -106,7 +112,7 @@ class DatabaseRegionObservationTests: GRDBTestCase {
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(count, 3)
XCTAssertEqual(recorder.count, 3)
}
}
@@ -126,12 +132,15 @@ class DatabaseRegionObservationTests: GRDBTestCase {
let observation = DatabaseRegionObservation(tracking: [request1, request2])
var count = 0
class Recorder {
var count = 0
}
let recorder = Recorder()
let cancellable = observation.start(
in: dbQueue,
onError: { XCTFail("Unexpected error: \($0)") },
onChange: { db in
count += 1
recorder.count += 1
notificationExpectation.fulfill()
})
@@ -148,7 +157,7 @@ class DatabaseRegionObservationTests: GRDBTestCase {
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(count, 3)
XCTAssertEqual(recorder.count, 3)
}
}
@@ -162,13 +171,16 @@ class DatabaseRegionObservationTests: GRDBTestCase {
let observation = DatabaseRegionObservation(tracking: SQLRequest<Row>(sql: "SELECT * FROM t ORDER BY id"))
var count = 0
class Recorder {
var count = 0
}
let recorder = Recorder()
do {
let cancellable = observation.start(
in: dbQueue,
onError: { XCTFail("Unexpected error: \($0)") },
onChange: { db in
count += 1
recorder.count += 1
notificationExpectation.fulfill()
})
@@ -187,7 +199,7 @@ class DatabaseRegionObservationTests: GRDBTestCase {
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(count, 2)
XCTAssertEqual(recorder.count, 2)
}
func testDatabaseRegionExtentNextTransaction() throws {
@@ -200,18 +212,21 @@ class DatabaseRegionObservationTests: GRDBTestCase {
let observation = DatabaseRegionObservation(tracking: SQLRequest<Row>(sql: "SELECT * FROM t ORDER BY id"))
var count = 0
var cancellable: AnyDatabaseCancellable?
cancellable = observation.start(
class Recorder {
var count = 0
var cancellable: AnyDatabaseCancellable?
}
let recorder = Recorder()
recorder.cancellable = observation.start(
in: dbQueue,
onError: { XCTFail("Unexpected error: \($0)") },
onChange: { db in
cancellable?.cancel()
count += 1
onChange: { [weak recorder] db in
recorder?.cancellable?.cancel()
recorder?.count += 1
notificationExpectation.fulfill()
})
try withExtendedLifetime(cancellable) {
try withExtendedLifetime(recorder) {
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')")
}
@@ -221,7 +236,7 @@ class DatabaseRegionObservationTests: GRDBTestCase {
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(count, 1)
XCTAssertEqual(recorder.count, 1)
}
}
+8 -6
View File
@@ -114,11 +114,12 @@ class DatabaseTraceTests : GRDBTestCase {
}
func testTraceFromConfigurationWithDefaultOptions() throws {
var events: [String] = []
class Recorder { var events: [String] = [] }
let recorder = Recorder()
var configuration = Configuration()
configuration.prepareDatabase { db in
db.trace { event in
events.append("SQL: \(event)")
recorder.events.append("SQL: \(event)")
}
}
let dbQueue = try makeDatabaseQueue(configuration: configuration)
@@ -127,19 +128,20 @@ class DatabaseTraceTests : GRDBTestCase {
CREATE table t(a);
INSERT INTO t (a) VALUES (?)
""", arguments: [1])
XCTAssertEqual(events.suffix(2), [
XCTAssertEqual(recorder.events.suffix(2), [
"SQL: CREATE table t(a)",
"SQL: INSERT INTO t (a) VALUES (?)"])
}
}
func testTraceFromConfigurationWithPublicStatementArguments() throws {
var events: [String] = []
class Recorder { var events: [String] = [] }
let recorder = Recorder()
var configuration = Configuration()
configuration.publicStatementArguments = true
configuration.prepareDatabase { db in
db.trace { event in
events.append("SQL: \(event)")
recorder.events.append("SQL: \(event)")
}
}
let dbQueue = try makeDatabaseQueue(configuration: configuration)
@@ -148,7 +150,7 @@ class DatabaseTraceTests : GRDBTestCase {
CREATE table t(a);
INSERT INTO t (a) VALUES (?)
""", arguments: [1])
XCTAssertEqual(events.suffix(2), [
XCTAssertEqual(recorder.events.suffix(2), [
"SQL: CREATE table t(a)",
"SQL: INSERT INTO t (a) VALUES (1)"])
}
@@ -1,7 +1,7 @@
import XCTest
import GRDB
private class FetchableParent : DatabaseValueConvertible, CustomStringConvertible {
private class FetchableParent : DatabaseValueConvertible, CustomStringConvertible, @unchecked Sendable {
var databaseValue: DatabaseValue { "Parent".databaseValue }
class func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
+9 -6
View File
@@ -272,16 +272,19 @@ class FTS4TableBuilderTests: GRDBTestCase {
func testFTS4Compression() throws {
// Based on https://github.com/groue/GRDB.swift/issues/369
var compressCalled = false
var uncompressCalled = false
class Recorder {
var compressCalled = false
var uncompressCalled = false
}
let recorder = Recorder()
dbConfiguration.prepareDatabase { db in
db.add(function: DatabaseFunction("zipit", argumentCount: 1, pure: true, function: { dbValues in
compressCalled = true
recorder.compressCalled = true
return dbValues[0]
}))
db.add(function: DatabaseFunction("unzipit", argumentCount: 1, pure: true, function: { dbValues in
uncompressCalled = true
recorder.uncompressCalled = true
return dbValues[0]
}))
}
@@ -296,12 +299,12 @@ class FTS4TableBuilderTests: GRDBTestCase {
assertDidExecute(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts4(content, compress=\"zipit\", uncompress=\"unzipit\")")
try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["abc"])
XCTAssertTrue(compressCalled)
XCTAssertTrue(recorder.compressCalled)
}
try dbPool.read { db in
_ = try Row.fetchOne(db, sql: "SELECT * FROM documents")
XCTAssertTrue(uncompressCalled)
XCTAssertTrue(recorder.uncompressCalled)
}
}
}
+4 -4
View File
@@ -219,12 +219,12 @@ extension FetchRequest {
/// A type-erased ValueReducer.
public struct AnyValueReducer<Fetched, Value>: ValueReducer {
private var __fetch: (Database) throws -> Fetched
private var __value: (Fetched) -> Value?
private var __fetch: @Sendable (Database) throws -> Fetched
private var __value: @Sendable (Fetched) -> Value?
public init(
fetch: @escaping (Database) throws -> Fetched,
value: @escaping (Fetched) -> Value?)
fetch: @escaping @Sendable (Database) throws -> Fetched,
value: @escaping @Sendable (Fetched) -> Value?)
{
self.__fetch = fetch
self.__value = value
@@ -50,6 +50,7 @@ extension Wrapper: SQLExpressible where RawValue: SQLExpressible { }
extension Wrapper: StatementBinding where RawValue: StatementBinding { }
extension Wrapper: DatabaseValueConvertible where RawValue: DatabaseValueConvertible { }
extension FastWrapper: Sendable where RawValue: Sendable { }
extension FastWrapper: SQLSelectable where RawValue: SQLSelectable { }
extension FastWrapper: SQLOrderingTerm where RawValue: SQLOrderingTerm { }
extension FastWrapper: SQLSpecificExpressible where RawValue: SQLSpecificExpressible { }
+1 -1
View File
@@ -15,7 +15,7 @@ private class Person : Record {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: """
CREATE TABLE persons (
id INTEGER PRIMARY KEY,
@@ -13,7 +13,7 @@ private class MinimalNonOptionalPrimaryKeySingle: Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: "CREATE TABLE minimalSingles (id TEXT NOT NULL PRIMARY KEY)")
}
@@ -12,7 +12,7 @@ class MinimalRowID : Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: "CREATE TABLE minimalRowIDs (id INTEGER PRIMARY KEY)")
}
@@ -11,7 +11,7 @@ class MinimalSingle: Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: "CREATE TABLE minimalSingles (UUID TEXT NOT NULL PRIMARY KEY)")
}
@@ -16,7 +16,7 @@ private class Person : Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: """
CREATE TABLE persons (
creationDate TEXT NOT NULL,
@@ -14,7 +14,7 @@ private class Citizenship : Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: """
CREATE TABLE citizenships (
personName TEXT NOT NULL,
@@ -14,7 +14,7 @@ private class Item : Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: """
CREATE TABLE items (
name TEXT,
@@ -16,7 +16,7 @@ private class Person : Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: """
CREATE TABLE persons (
id INTEGER PRIMARY KEY,
@@ -12,7 +12,7 @@ class Pet : Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: """
CREATE TABLE pets (
UUID TEXT NOT NULL PRIMARY KEY,
@@ -11,7 +11,7 @@ class Email : Record, Hashable {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: """
CREATE TABLE emails (
email TEXT NOT NULL PRIMARY KEY ON CONFLICT REPLACE,
+1 -1
View File
@@ -15,7 +15,7 @@ private class Person : Record {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: """
CREATE TABLE persons (
id INTEGER PRIMARY KEY,
@@ -13,7 +13,7 @@ class BadlyMangledStuff : Record {
super.init()
}
static func setup(inDatabase db: Database) throws {
@Sendable static func setup(inDatabase db: Database) throws {
try db.execute(sql: "CREATE TABLE stuffs (id INTEGER PRIMARY KEY, name TEXT)")
}
+106 -66
View File
@@ -23,12 +23,15 @@ class SharedValueObservationTests: GRDBTestCase {
// We want to control when the shared observation is deallocated
withExtendedLifetime(sharedObservation) { sharedObservation in
do {
var value: Int?
class Recorder {
var value: Int?
}
let recorder = Recorder()
let cancellable = sharedObservation!.start(
onError: { XCTFail("Unexpected error \($0)") },
onChange: { value = $0 })
onChange: { recorder.value = $0 })
XCTAssertEqual(value, 0)
XCTAssertEqual(recorder.value, 0)
XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"])
cancellable.cancel()
@@ -36,12 +39,15 @@ class SharedValueObservationTests: GRDBTestCase {
}
do {
var value: Int?
class Recorder {
var value: Int?
}
let recorder = Recorder()
let cancellable = sharedObservation!.start(
onError: { XCTFail("Unexpected error \($0)") },
onChange: { value = $0 })
onChange: { recorder.value = $0 })
XCTAssertEqual(value, 0)
XCTAssertEqual(recorder.value, 0)
XCTAssertEqual(log.flush(), [])
cancellable.cancel()
@@ -75,21 +81,24 @@ class SharedValueObservationTests: GRDBTestCase {
// We want to control when the shared observation is deallocated
withExtendedLifetime(sharedObservation) { sharedObservation in
do {
var value1: Int?
var value2: Int?
class Recorder {
var value1: Int?
var value2: Int?
}
let recorder = Recorder()
let cancellable1 = sharedObservation!.start(
onError: { XCTFail("Unexpected error \($0)") },
onChange: { value in
value1 = value
recorder.value1 = value
_ = sharedObservation!.start(
onError: { XCTFail("Unexpected error \($0)") },
onChange: { value in
value2 = value
recorder.value2 = value
})
})
XCTAssertEqual(value1, 0)
XCTAssertEqual(value2, 0)
XCTAssertEqual(recorder.value1, 0)
XCTAssertEqual(recorder.value2, 0)
XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"])
cancellable1.cancel()
@@ -159,12 +168,15 @@ class SharedValueObservationTests: GRDBTestCase {
// We want to control when the shared observation is deallocated
withExtendedLifetime(sharedObservation) { sharedObservation in
do {
var value: Int?
class Recorder {
var value: Int?
}
let recorder = Recorder()
let cancellable = sharedObservation!.start(
onError: { XCTFail("Unexpected error \($0)") },
onChange: { value = $0 })
onChange: { recorder.value = $0 })
XCTAssertEqual(value, 0)
XCTAssertEqual(recorder.value, 0)
XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"])
cancellable.cancel()
@@ -172,12 +184,15 @@ class SharedValueObservationTests: GRDBTestCase {
}
do {
var value: Int?
class Recorder {
var value: Int?
}
let recorder = Recorder()
let cancellable = sharedObservation!.start(
onError: { XCTFail("Unexpected error \($0)") },
onChange: { value = $0 })
onChange: { recorder.value = $0 })
XCTAssertEqual(value, 0)
XCTAssertEqual(recorder.value, 0)
XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"])
cancellable.cancel()
@@ -210,21 +225,24 @@ class SharedValueObservationTests: GRDBTestCase {
// We want to control when the shared observation is deallocated
withExtendedLifetime(sharedObservation) { sharedObservation in
var value1: Int?
var value2: Int?
class Context {
var value1: Int?
var value2: Int?
}
let context = Context()
let cancellable1 = sharedObservation!.start(
onError: { XCTFail("Unexpected error \($0)") },
onChange: { value in
value1 = value
context.value1 = value
_ = sharedObservation!.start(
onError: { XCTFail("Unexpected error \($0)") },
onChange: { value in
value2 = value
context.value2 = value
})
})
XCTAssertEqual(value1, 0)
XCTAssertEqual(value2, 0)
XCTAssertEqual(context.value1, 0)
XCTAssertEqual(context.value2, 0)
XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"])
cancellable1.cancel()
@@ -256,41 +274,46 @@ class SharedValueObservationTests: GRDBTestCase {
// We want to control when the shared observation is deallocated
try withExtendedLifetime(sharedObservation) { sharedObservation in
class Context {
var values1: [Int] = []
var values2: [Int] = []
var values3: [Int] = []
}
let context = Context()
// --- Start observation 1
var values1: [Int] = []
let exp1 = expectation(description: "")
exp1.expectedFulfillmentCount = 2
exp1.assertForOverFulfill = false
let cancellable1 = sharedObservation!.start(
onError: { XCTFail("Unexpected error \($0)") },
onChange: {
values1.append($0)
context.values1.append($0)
exp1.fulfill()
})
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
wait(for: [exp1], timeout: 1)
XCTAssertEqual(values1, [0, 1])
XCTAssertEqual(context.values1, [0, 1])
XCTAssertEqual(log.flush(), [
"start", "fetch", "tracked region: player(*)", "value: 0",
"database did change", "fetch", "value: 1"])
// --- Start observation 2
var values2: [Int] = []
let exp2 = expectation(description: "")
exp2.expectedFulfillmentCount = 2
exp2.assertForOverFulfill = false
let cancellable2 = sharedObservation!.start(
onError: { XCTFail("Unexpected error \($0)") },
onChange: {
values2.append($0)
context.values2.append($0)
exp2.fulfill()
})
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
wait(for: [exp2], timeout: 1)
XCTAssertEqual(values1, [0, 1, 2])
XCTAssertEqual(values2, [1, 2])
XCTAssertEqual(context.values1, [0, 1, 2])
XCTAssertEqual(context.values2, [1, 2])
XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 2"])
// --- Stop observation 1
@@ -298,22 +321,21 @@ class SharedValueObservationTests: GRDBTestCase {
XCTAssertEqual(log.flush(), [])
// --- Start observation 3
var values3: [Int] = []
let exp3 = expectation(description: "")
exp3.expectedFulfillmentCount = 2
exp3.assertForOverFulfill = false
let cancellable3 = sharedObservation!.start(
onError: { XCTFail("Unexpected error \($0)") },
onChange: {
values3.append($0)
context.values3.append($0)
exp3.fulfill()
})
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
wait(for: [exp3], timeout: 1)
XCTAssertEqual(values1, [0, 1, 2])
XCTAssertEqual(values2, [1, 2, 3])
XCTAssertEqual(values3, [2, 3])
XCTAssertEqual(context.values1, [0, 1, 2])
XCTAssertEqual(context.values2, [1, 2, 3])
XCTAssertEqual(context.values3, [2, 3])
XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 3"])
// --- Stop observation 2
@@ -338,24 +360,30 @@ class SharedValueObservationTests: GRDBTestCase {
}
}
class Context {
var sharedObservation: SharedValueObservation<Int>?
init(dbQueue: DatabaseQueue, log: Log) {
sharedObservation = ValueObservation
.tracking(Table("player").fetchCount)
.print(to: log)
.shared(
in: dbQueue,
scheduling: .async(onQueue: .main),
extent: .observationLifetime)
}
}
let log = Log()
var sharedObservation: SharedValueObservation<Int>? = ValueObservation
.tracking(Table("player").fetchCount)
.print(to: log)
.shared(
in: dbQueue,
scheduling: .async(onQueue: .main),
extent: .observationLifetime)
let context = Context(dbQueue: dbQueue, log: log)
XCTAssertEqual(log.flush(), [])
// ---
let exp = expectation(description: "")
exp.expectedFulfillmentCount = 3
let cancellable = sharedObservation!.start(
let cancellable = context.sharedObservation!.start(
onError: { XCTFail("Unexpected error \($0)") },
onChange: { value in
onChange: { [weak context] value in
// Early release
sharedObservation = nil
context?.sharedObservation = nil
switch value {
case 0:
@@ -435,41 +463,46 @@ class SharedValueObservationTests: GRDBTestCase {
// We want to control when the shared observation is deallocated
try withExtendedLifetime(sharedObservation) { sharedObservation in
class Context {
var values1: [Int] = []
var values2: [Int] = []
var values3: [Int] = []
}
let context = Context()
// --- Start observation 1
var values1: [Int] = []
let exp1 = expectation(description: "")
exp1.expectedFulfillmentCount = 2
exp1.assertForOverFulfill = false
let cancellable1 = sharedObservation!.start(
onError: { XCTFail("Unexpected error \($0)") },
onChange: {
values1.append($0)
context.values1.append($0)
exp1.fulfill()
})
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
wait(for: [exp1], timeout: 1)
XCTAssertEqual(values1, [0, 1])
XCTAssertEqual(context.values1, [0, 1])
XCTAssertEqual(log.flush(), [
"start", "fetch", "tracked region: player(*)", "value: 0",
"database did change", "fetch", "value: 1"])
// --- Start observation 2
var values2: [Int] = []
let exp2 = expectation(description: "")
exp2.expectedFulfillmentCount = 2
exp2.assertForOverFulfill = false
let cancellable2 = sharedObservation!.start(
onError: { XCTFail("Unexpected error \($0)") },
onChange: {
values2.append($0)
context.values2.append($0)
exp2.fulfill()
})
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
wait(for: [exp2], timeout: 1)
XCTAssertEqual(values1, [0, 1, 2])
XCTAssertEqual(values2, [1, 2])
XCTAssertEqual(context.values1, [0, 1, 2])
XCTAssertEqual(context.values2, [1, 2])
XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 2"])
// --- Stop observation 1
@@ -477,22 +510,21 @@ class SharedValueObservationTests: GRDBTestCase {
XCTAssertEqual(log.flush(), [])
// --- Start observation 3
var values3: [Int] = []
let exp3 = expectation(description: "")
exp3.expectedFulfillmentCount = 2
exp3.assertForOverFulfill = false
let cancellable3 = sharedObservation!.start(
onError: { XCTFail("Unexpected error \($0)") },
onChange: {
values3.append($0)
context.values3.append($0)
exp3.fulfill()
})
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
wait(for: [exp3], timeout: 1)
XCTAssertEqual(values1, [0, 1, 2])
XCTAssertEqual(values2, [1, 2, 3])
XCTAssertEqual(values3, [2, 3])
XCTAssertEqual(context.values1, [0, 1, 2])
XCTAssertEqual(context.values2, [1, 2, 3])
XCTAssertEqual(context.values3, [2, 3])
XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 3"])
// --- Stop observation 2
@@ -522,11 +554,15 @@ class SharedValueObservationTests: GRDBTestCase {
}
}
class Context {
var fetchError: (any Error)? = nil
}
let context = Context()
let log = Log()
var fetchError: (any Error)? = nil
let publisher = ValueObservation
.tracking { db -> Int in
if let error = fetchError { throw error }
if let error = context.fetchError { throw error }
return try Table("player").fetchCount(db)
}
.print(to: log)
@@ -540,7 +576,7 @@ class SharedValueObservationTests: GRDBTestCase {
try XCTAssertEqual(wait(for: recorder1.next(), timeout: 1), 0)
try XCTAssertEqual(wait(for: recorder2.next(), timeout: 1), 0)
fetchError = TestError()
context.fetchError = TestError()
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
if case .finished = try wait(for: recorder1.completion, timeout: 1) { XCTFail("Expected error") }
@@ -557,7 +593,7 @@ class SharedValueObservationTests: GRDBTestCase {
}
do {
fetchError = nil
context.fetchError = nil
let recorder = publisher.record()
if case .finished = try wait(for: recorder.completion, timeout: 1) { XCTFail("Expected error") }
XCTAssertEqual(log.flush(), [])
@@ -578,11 +614,15 @@ class SharedValueObservationTests: GRDBTestCase {
}
}
class Context {
var fetchError: (any Error)? = nil
}
let context = Context()
let log = Log()
var fetchError: (any Error)? = nil
let publisher = ValueObservation
.tracking { db -> Int in
if let error = fetchError { throw error }
if let error = context.fetchError { throw error }
return try Table("player").fetchCount(db)
}
.print(to: log)
@@ -596,7 +636,7 @@ class SharedValueObservationTests: GRDBTestCase {
try XCTAssertEqual(wait(for: recorder1.next(), timeout: 1), 0)
try XCTAssertEqual(wait(for: recorder2.next(), timeout: 1), 0)
fetchError = TestError()
context.fetchError = TestError()
try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")}
if case .finished = try wait(for: recorder1.completion, timeout: 1) { XCTFail("Expected error") }
@@ -613,7 +653,7 @@ class SharedValueObservationTests: GRDBTestCase {
}
do {
fetchError = nil
context.fetchError = nil
let recorder = publisher.record()
try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1)
XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 1"])
+109 -52
View File
@@ -3,14 +3,20 @@ import GRDB
class TransactionDateTests: GRDBTestCase {
func testTransactionDateOutsideOfTransaction() throws {
let dates = [
Date.distantPast,
Date(),
Date.distantFuture,
]
var dateIterator = dates.makeIterator()
class Context {
static let dates = [
Date.distantPast,
Date(),
Date.distantFuture,
]
var dateIterator: [Date].Iterator
init() {
dateIterator = Self.dates.makeIterator()
}
}
let context = Context()
dbConfiguration.transactionClock = .custom { _ in
dateIterator.next()!
context.dateIterator.next()!
}
var collectedDates: [Date] = []
@@ -19,18 +25,24 @@ class TransactionDateTests: GRDBTestCase {
try collectedDates.append(db.transactionDate)
try collectedDates.append(db.transactionDate)
}
XCTAssertEqual(collectedDates, dates)
XCTAssertEqual(collectedDates, Context.dates)
}
func testTransactionDateInsideTransaction_commit() throws {
let dates = [
Date.distantPast,
Date(),
Date.distantFuture,
]
var dateIterator = dates.makeIterator()
class Context {
static let dates = [
Date.distantPast,
Date(),
Date.distantFuture,
]
var dateIterator: [Date].Iterator
init() {
dateIterator = Self.dates.makeIterator()
}
}
let context = Context()
dbConfiguration.transactionClock = .custom { _ in
dateIterator.next()!
context.dateIterator.next()!
}
var collectedDates: [Date] = []
@@ -42,18 +54,29 @@ class TransactionDateTests: GRDBTestCase {
try db.execute(sql: "COMMIT")
try collectedDates.append(db.transactionDate)
}
XCTAssertEqual(collectedDates, [dates[0], dates[1], dates[1], dates[2]])
XCTAssertEqual(collectedDates, [
Context.dates[0],
Context.dates[1],
Context.dates[1],
Context.dates[2],
])
}
func testTransactionDateInsideTransaction_rollback() throws {
let dates = [
Date.distantPast,
Date(),
Date.distantFuture,
]
var dateIterator = dates.makeIterator()
class Context {
static let dates = [
Date.distantPast,
Date(),
Date.distantFuture,
]
var dateIterator: [Date].Iterator
init() {
dateIterator = Self.dates.makeIterator()
}
}
let context = Context()
dbConfiguration.transactionClock = .custom { _ in
dateIterator.next()!
context.dateIterator.next()!
}
var collectedDates: [Date] = []
@@ -65,18 +88,29 @@ class TransactionDateTests: GRDBTestCase {
try db.execute(sql: "ROLLBACK")
try collectedDates.append(db.transactionDate)
}
XCTAssertEqual(collectedDates, [dates[0], dates[1], dates[1], dates[2]])
XCTAssertEqual(collectedDates, [
Context.dates[0],
Context.dates[1],
Context.dates[1],
Context.dates[2],
])
}
func testTransactionDateInsideTransaction_rollbackingError() throws {
let dates = [
Date.distantPast,
Date(),
Date.distantFuture,
]
var dateIterator = dates.makeIterator()
class Context {
static let dates = [
Date.distantPast,
Date(),
Date.distantFuture,
]
var dateIterator: [Date].Iterator
init() {
dateIterator = Self.dates.makeIterator()
}
}
let context = Context()
dbConfiguration.transactionClock = .custom { _ in
dateIterator.next()!
context.dateIterator.next()!
}
var collectedDates: [Date] = []
@@ -92,7 +126,12 @@ class TransactionDateTests: GRDBTestCase {
""")
try collectedDates.append(db.transactionDate)
}
XCTAssertEqual(collectedDates, [dates[0], dates[1], dates[1], dates[2]])
XCTAssertEqual(collectedDates, [
Context.dates[0],
Context.dates[1],
Context.dates[1],
Context.dates[2],
])
}
func test_TimestampedRecord_default_willInsert() throws {
@@ -107,8 +146,11 @@ class TransactionDateTests: GRDBTestCase {
}
}
var currentDate = Date.distantPast
dbConfiguration.transactionClock = .custom { _ in currentDate }
class Context {
var currentDate = Date.distantPast
}
let context = Context()
dbConfiguration.transactionClock = .custom { _ in context.currentDate }
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "player") { t in
@@ -119,7 +161,7 @@ class TransactionDateTests: GRDBTestCase {
}
}
currentDate = Date.distantPast
context.currentDate = Date.distantPast
try dbQueue.write { db in
do {
var player = Player(name: "Arthur")
@@ -152,8 +194,11 @@ class TransactionDateTests: GRDBTestCase {
}
}
var currentDate = Date.distantPast
dbConfiguration.transactionClock = .custom { _ in currentDate }
class Context {
var currentDate = Date.distantPast
}
let context = Context()
dbConfiguration.transactionClock = .custom { _ in context.currentDate }
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "player") { t in
@@ -164,14 +209,14 @@ class TransactionDateTests: GRDBTestCase {
}
}
currentDate = Date.distantPast
context.currentDate = Date.distantPast
try dbQueue.write { db in
var player = Player(name: "Arthur")
try player.insert(db)
}
let newTransactionDate = Date()
currentDate = newTransactionDate
context.currentDate = newTransactionDate
try dbQueue.write { db in
var player = try Player.find(db, key: 1)
@@ -198,8 +243,11 @@ class TransactionDateTests: GRDBTestCase {
}
}
var currentDate = Date.distantPast
dbConfiguration.transactionClock = .custom { _ in currentDate }
class Context {
var currentDate = Date.distantPast
}
let context = Context()
dbConfiguration.transactionClock = .custom { _ in context.currentDate }
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "player") { t in
@@ -210,14 +258,14 @@ class TransactionDateTests: GRDBTestCase {
}
}
currentDate = Date.distantPast
context.currentDate = Date.distantPast
try dbQueue.write { db in
var player = Player(name: "Arthur")
try player.insert(db)
}
let newTransactionDate = Date()
currentDate = newTransactionDate
context.currentDate = newTransactionDate
try dbQueue.write { db in
var player = try Player.find(db, key: 1)
@@ -251,8 +299,11 @@ class TransactionDateTests: GRDBTestCase {
}
}
var currentDate = Date.distantPast
dbConfiguration.transactionClock = .custom { _ in currentDate }
class Context {
var currentDate = Date.distantPast
}
let context = Context()
dbConfiguration.transactionClock = .custom { _ in context.currentDate }
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "player") { t in
@@ -267,7 +318,7 @@ class TransactionDateTests: GRDBTestCase {
}
let newTransactionDate = Date()
currentDate = newTransactionDate
context.currentDate = newTransactionDate
try dbQueue.write { db in
var player = try Player.find(db, key: 1)
try player.touch(db)
@@ -303,8 +354,11 @@ class TransactionDateTests: GRDBTestCase {
}
}
var currentDate = Date.distantPast
dbConfiguration.transactionClock = .custom { _ in currentDate }
class Context {
var currentDate = Date.distantPast
}
let context = Context()
dbConfiguration.transactionClock = .custom { _ in context.currentDate }
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "player") { t in
@@ -315,7 +369,7 @@ class TransactionDateTests: GRDBTestCase {
}
}
currentDate = Date.distantPast
context.currentDate = Date.distantPast
try dbQueue.write { db in
var player = Player(name: "Arthur", isInserted: false)
try player.insert(db)
@@ -354,8 +408,11 @@ class TransactionDateTests: GRDBTestCase {
}
}
var currentDate = Date.distantPast
dbConfiguration.transactionClock = .custom { _ in currentDate }
class Context {
var currentDate = Date.distantPast
}
let context = Context()
dbConfiguration.transactionClock = .custom { _ in context.currentDate }
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "player") { t in
@@ -366,7 +423,7 @@ class TransactionDateTests: GRDBTestCase {
}
}
currentDate = Date.distantPast
context.currentDate = Date.distantPast
try dbQueue.write { db in
let player = Player(name: "Arthur")
try player.insert(db)
@@ -410,11 +410,14 @@ class ValueObservationPrintTests: GRDBTestCase {
// Force DatabasePool to perform two initial fetches, because between
// its first read access, and its write access that installs the
// transaction observer, some write did happen.
var needsChange = true
class Context {
var needsChange = true
}
let context = Context()
let observation = ValueObservation
.trackingConstantRegion { db -> Int? in
if needsChange {
needsChange = false
if context.needsChange {
context.needsChange = false
try dbPool.write { db in
try db.execute(sql: """
INSERT INTO player DEFAULT VALUES;
@@ -461,11 +464,14 @@ class ValueObservationPrintTests: GRDBTestCase {
// Force DatabasePool to perform two initial fetches, because between
// its first read access, and its write access that installs the
// transaction observer, some write did happen.
var needsChange = true
class Context {
var needsChange = true
}
let context = Context()
let observation = ValueObservation
.trackingConstantRegion { db -> Int? in
if needsChange {
needsChange = false
if context.needsChange {
context.needsChange = false
try dbPool.write { db in
try db.execute(sql: """
INSERT INTO player DEFAULT VALUES;
@@ -130,24 +130,27 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
""")
}
var results: [Int] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 4
var regions: [DatabaseRegion] = []
class Recorder {
var regions: [DatabaseRegion] = []
var results: [Int] = []
}
let recorder = Recorder()
let observation = ValueObservation
.tracking { db -> Int in
let table = try String.fetchOne(db, sql: "SELECT name FROM source")!
return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")!
}
.handleEvents(willTrackRegion: { regions.append($0) })
.handleEvents(willTrackRegion: { recorder.regions.append($0) })
let observer = observation.start(
in: dbQueue,
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
results.append(count)
recorder.results.append(count)
notificationExpectation.fulfill()
})
@@ -162,9 +165,9 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results, [0, 1, 2, 3])
XCTAssertEqual(recorder.results, [0, 1, 2, 3])
XCTAssertEqual(regions.map(\.description), [
XCTAssertEqual(recorder.regions.map(\.description), [
"a(value),source(name)",
"b(value),source(name)"])
}
@@ -181,25 +184,28 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
""")
}
var results: [Int] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 4
var regions: [DatabaseRegion] = []
class Recorder {
var regions: [DatabaseRegion] = []
var results: [Int] = []
}
let recorder = Recorder()
let observation = ValueObservation
.tracking { db -> Int in
let table = try String.fetchOne(db, sql: "SELECT name FROM source")!
return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")!
}
.handleEvents(willTrackRegion: { regions.append($0) })
.handleEvents(willTrackRegion: { recorder.regions.append($0) })
let observer = observation.start(
in: dbQueue,
scheduling: .async(onQueue: .main),
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
results.append(count)
recorder.results.append(count)
notificationExpectation.fulfill()
})
@@ -214,9 +220,9 @@ class ValueObservationRegionRecordingTests: GRDBTestCase {
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results, [0, 1, 2, 3])
XCTAssertEqual(recorder.results, [0, 1, 2, 3])
XCTAssertEqual(regions.map(\.description), [
XCTAssertEqual(recorder.regions.map(\.description), [
"a(value),source(name)",
"b(value),source(name)"])
}
+119 -86
View File
@@ -5,19 +5,22 @@ import Dispatch
class ValueObservationTests: GRDBTestCase {
func testImmediateError() throws {
struct TestError: Error { }
class Recorder {
var error: TestError?
}
func test(_ dbWriter: some DatabaseWriter) throws {
// Create an observation
let observation = ValueObservation.trackingConstantRegion { _ in throw TestError() }
// Start observation
var error: TestError?
let recorder = Recorder()
_ = observation.start(
in: dbWriter,
scheduling: .immediate,
onError: { error = $0 as? TestError },
onError: { recorder.error = $0 as? TestError },
onChange: { _ in })
XCTAssertNotNil(error)
XCTAssertNotNil(recorder.error)
}
try test(makeDatabaseQueue())
@@ -26,7 +29,11 @@ class ValueObservationTests: GRDBTestCase {
func testErrorCompletesTheObservation() throws {
struct TestError: Error { }
class Context {
var nextError: (any Error)? = nil // If not null, observation throws an error
var errorCaught = false
}
func test(_ dbWriter: some DatabaseWriter) throws {
// We need something to change
try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
@@ -37,25 +44,24 @@ class ValueObservationTests: GRDBTestCase {
notificationExpectation.expectedFulfillmentCount = 4
notificationExpectation.isInverted = true
var nextError: (any Error)? = nil // If not null, observation throws an error
let context = Context()
let observation = ValueObservation.trackingConstantRegion {
_ = try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")
if let error = nextError {
if let error = context.nextError {
throw error
}
}
// Start observation
var errorCaught = false
let cancellable = observation.start(
in: dbWriter,
onError: { _ in
errorCaught = true
context.errorCaught = true
notificationExpectation.fulfill()
},
onChange: {
XCTAssertFalse(errorCaught)
nextError = TestError()
XCTAssertFalse(context.errorCaught)
context.nextError = TestError()
notificationExpectation.fulfill()
// Trigger another change
try! dbWriter.writeWithoutTransaction { db in
@@ -65,7 +71,7 @@ class ValueObservationTests: GRDBTestCase {
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertTrue(errorCaught)
XCTAssertTrue(context.errorCaught)
}
}
@@ -92,12 +98,15 @@ class ValueObservationTests: GRDBTestCase {
// Test that view v is not included in the observed region.
// This optimization helps observation of views that feed from a
// single table.
var region: DatabaseRegion?
class Recorder {
var region: DatabaseRegion?
}
let recorder = Recorder()
let expectation = self.expectation(description: "")
let observation = ValueObservation
.trackingConstantRegion(request.fetchAll)
.handleEvents(willTrackRegion: {
region = $0
recorder.region = $0
expectation.fulfill()
})
let observer = observation.start(
@@ -106,7 +115,7 @@ class ValueObservationTests: GRDBTestCase {
onChange: { _ in })
withExtendedLifetime(observer) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(region!.description, "t(id,name)") // view is NOT tracked
XCTAssertEqual(recorder.region!.description, "t(id,name)") // view is NOT tracked
}
}
@@ -125,12 +134,15 @@ class ValueObservationTests: GRDBTestCase {
// Test that no pragma table is included in the observed region.
// This optimization helps observation that feed from a single table.
var region: DatabaseRegion?
class Recorder {
var region: DatabaseRegion?
}
let recorder = Recorder()
let expectation = self.expectation(description: "")
let observation = ValueObservation
.trackingConstantRegion(request.fetchAll)
.handleEvents(willTrackRegion: {
region = $0
recorder.region = $0
expectation.fulfill()
})
let observer = observation.start(
@@ -139,7 +151,7 @@ class ValueObservationTests: GRDBTestCase {
onChange: { _ in })
withExtendedLifetime(observer) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(region!.description, "t(id,name)[1]") // pragma_table_xinfo is NOT tracked
XCTAssertEqual(recorder.region!.description, "t(id,name)[1]") // pragma_table_xinfo is NOT tracked
}
}
@@ -325,10 +337,14 @@ class ValueObservationTests: GRDBTestCase {
// Force DatabasePool to perform two initial fetches, because between
// its first read access, and its write access that installs the
// transaction observer, some write did happen.
var needsChange = true
class Context {
var needsChange = true
var observedCounts: [Int] = []
}
let context = Context()
let observation = ValueObservation.trackingConstantRegion { db -> Int in
if needsChange {
needsChange = false
if context.needsChange {
context.needsChange = false
try dbPool.write { db in
try db.execute(sql: """
INSERT INTO t DEFAULT VALUES;
@@ -341,18 +357,17 @@ class ValueObservationTests: GRDBTestCase {
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = 2
var observedCounts: [Int] = []
let cancellable = observation.start(
in: dbPool,
scheduling: .async(onQueue: .main),
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCounts.append(count)
context.observedCounts.append(count)
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(observedCounts, [0, 0])
XCTAssertEqual(context.observedCounts, [0, 0])
}
}
@@ -365,10 +380,14 @@ class ValueObservationTests: GRDBTestCase {
// Force DatabasePool to perform two initial fetches, because between
// its first read access, and its write access that installs the
// transaction observer, some write did happen.
var needsChange = true
class Context {
var needsChange = true
var observedCounts: [Int] = []
}
let context = Context()
let observation = ValueObservation.trackingConstantRegion { db -> Int in
if needsChange {
needsChange = false
if context.needsChange {
context.needsChange = false
try dbPool.write { db in
try db.execute(sql: """
INSERT INTO t DEFAULT VALUES;
@@ -381,18 +400,17 @@ class ValueObservationTests: GRDBTestCase {
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = 2
var observedCounts: [Int] = []
let cancellable = observation.start(
in: dbPool,
scheduling: .immediate,
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCounts.append(count)
context.observedCounts.append(count)
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(observedCounts, [0, 0])
XCTAssertEqual(context.observedCounts, [0, 0])
}
}
@@ -405,10 +423,14 @@ class ValueObservationTests: GRDBTestCase {
// Allow pool to perform a single initial fetch, because between
// its first read access, and its write access that installs the
// transaction observer, no write did happen.
var needsChange = true
class Context {
var needsChange = true
var observedCounts: [Int] = []
}
let context = Context()
let observation = ValueObservation.trackingConstantRegion { db -> Int in
if needsChange {
needsChange = false
if context.needsChange {
context.needsChange = false
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
try! dbPool.write { db in
try db.execute(sql: """
@@ -431,18 +453,17 @@ class ValueObservationTests: GRDBTestCase {
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = expectedCounts.count
var observedCounts: [Int] = []
let cancellable = observation.start(
in: dbPool,
scheduling: .async(onQueue: .main),
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCounts.append(count)
context.observedCounts.append(count)
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(observedCounts, expectedCounts)
XCTAssertEqual(context.observedCounts, expectedCounts)
}
}
@@ -455,10 +476,14 @@ class ValueObservationTests: GRDBTestCase {
// Allow pool to perform a single initial fetch, because between
// its first read access, and its write access that installs the
// transaction observer, no write did happen.
var needsChange = true
class Context {
var needsChange = true
var observedCounts: [Int] = []
}
let context = Context()
let observation = ValueObservation.trackingConstantRegion { db -> Int in
if needsChange {
needsChange = false
if context.needsChange {
context.needsChange = false
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
try! dbPool.write { db in
try db.execute(sql: """
@@ -481,18 +506,17 @@ class ValueObservationTests: GRDBTestCase {
let expectation = self.expectation(description: "")
expectation.expectedFulfillmentCount = expectedCounts.count
var observedCounts: [Int] = []
let cancellable = observation.start(
in: dbPool,
scheduling: .immediate,
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { count in
observedCounts.append(count)
context.observedCounts.append(count)
expectation.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(observedCounts, expectedCounts)
XCTAssertEqual(context.observedCounts, expectedCounts)
}
}
@@ -531,7 +555,11 @@ class ValueObservationTests: GRDBTestCase {
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
// Track reducer process
var changesCount = 0
class Context {
var changesCount = 0
var cancellable: (any DatabaseCancellable)?
}
let context = Context()
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 2
@@ -542,14 +570,14 @@ class ValueObservationTests: GRDBTestCase {
}
// Start observation and deallocate cancellable after second change
var cancellable: (any DatabaseCancellable)?
cancellable = observation.start(
context.cancellable = observation.start(
in: dbQueue,
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { _ in
changesCount += 1
if changesCount == 2 {
cancellable = nil
onChange: { [weak context] _ in
guard let context else { return }
context.changesCount += 1
if context.changesCount == 2 {
context.cancellable = nil
}
notificationExpectation.fulfill()
})
@@ -564,11 +592,8 @@ class ValueObservationTests: GRDBTestCase {
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
// Avoid "Variable 'cancellable' was written to, but never read" warning
_ = cancellable
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(changesCount, 2)
XCTAssertEqual(context.changesCount, 2)
}
func testCancellableExplicitCancellation() throws {
@@ -577,7 +602,11 @@ class ValueObservationTests: GRDBTestCase {
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
// Track reducer process
var changesCount = 0
class Context {
var changesCount = 0
var cancellable: (any DatabaseCancellable)?
}
let context = Context()
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 2
@@ -588,35 +617,38 @@ class ValueObservationTests: GRDBTestCase {
}
// Start observation and cancel cancellable after second change
var cancellable: (any DatabaseCancellable)!
cancellable = observation.start(
context.cancellable = observation.start(
in: dbQueue,
onError: { error in XCTFail("Unexpected error: \(error)") },
onChange: { _ in
changesCount += 1
if changesCount == 2 {
cancellable.cancel()
onChange: { [weak context] _ in
guard let context else { return }
context.changesCount += 1
if context.changesCount == 2 {
context.cancellable?.cancel()
}
notificationExpectation.fulfill()
})
try withExtendedLifetime(cancellable) {
// notified
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
// not notified
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(changesCount, 2)
// notified
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
// not notified
try dbQueue.write { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
waitForExpectations(timeout: 2, handler: nil)
XCTAssertEqual(context.changesCount, 2)
}
func testCancellableInvalidation1() throws {
class Context {
var shouldStopObservation = false
var cancellable: (any DatabaseCancellable)? = nil
}
// Test that observation stops when cancellable is deallocated
func test(_ dbWriter: some DatabaseWriter) throws {
try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
@@ -626,22 +658,20 @@ class ValueObservationTests: GRDBTestCase {
notificationExpectation.expectedFulfillmentCount = 2
do {
var cancellable: (any DatabaseCancellable)? = nil
_ = cancellable // Avoid "Variable 'cancellable' was written to, but never read" warning
var shouldStopObservation = false
let context = Context()
let observation = ValueObservation(
trackingMode: .nonConstantRegionRecordedFromSelection,
makeReducer: {
AnyValueReducer<Void, Void>(
fetch: { _ in
if shouldStopObservation {
cancellable = nil /* deallocation */
if context.shouldStopObservation {
context.cancellable = nil /* deallocation */
}
shouldStopObservation = true
context.shouldStopObservation = true
},
value: { _ in () })
})
cancellable = observation.start(
context.cancellable = observation.start(
in: dbWriter,
scheduling: .immediate,
onError: { error in XCTFail("Unexpected error: \(error)") },
@@ -661,6 +691,11 @@ class ValueObservationTests: GRDBTestCase {
}
func testCancellableInvalidation2() throws {
class Context {
var shouldStopObservation = false
var cancellable: (any DatabaseCancellable)? = nil
}
// Test that observation stops when cancellable is deallocated
func test(_ dbWriter: some DatabaseWriter) throws {
try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
@@ -670,23 +705,21 @@ class ValueObservationTests: GRDBTestCase {
notificationExpectation.expectedFulfillmentCount = 2
do {
var cancellable: (any DatabaseCancellable)? = nil
_ = cancellable // Avoid "Variable 'cancellable' was written to, but never read" warning
var shouldStopObservation = false
let context = Context()
let observation = ValueObservation(
trackingMode: .nonConstantRegionRecordedFromSelection,
makeReducer: {
AnyValueReducer<Void, Void>(
fetch: { _ in },
value: { _ in
if shouldStopObservation {
cancellable = nil /* deallocation right before notification */
if context.shouldStopObservation {
context.cancellable = nil /* deallocation right before notification */
}
shouldStopObservation = true
context.shouldStopObservation = true
return ()
})
})
cancellable = observation.start(
context.cancellable = observation.start(
in: dbWriter,
scheduling: .immediate,
onError: { error in XCTFail("Unexpected error: \(error)") },