mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-01 04:38:44 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d66e069822 | ||
|
|
e7eac0d500 | ||
|
|
61e0e97b39 | ||
|
|
fc10db84fe |
No files matched your search
@@ -27,7 +27,7 @@ struct PlayerRequest: Queryable {
|
||||
|
||||
static var defaultValue: [Player] { [] }
|
||||
|
||||
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> {
|
||||
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], any Error> {
|
||||
// Build the publisher from the general-purpose read-only access
|
||||
// granted by `appDatabase.reader`.
|
||||
// Some apps will prefer to call a dedicated method of `appDatabase`.
|
||||
|
||||
@@ -27,7 +27,7 @@ struct PlayerRequest: Queryable {
|
||||
|
||||
static var defaultValue: [Player] { [] }
|
||||
|
||||
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> {
|
||||
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], any Error> {
|
||||
// Build the publisher from the general-purpose read-only access
|
||||
// granted by `appDatabase.reader`.
|
||||
// Some apps will prefer to call a dedicated method of `appDatabase`.
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
+22
-14
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -308,7 +316,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
///
|
||||
/// Invariant: `transactionDateResult` is nil iff connection is not
|
||||
/// inside a transaction.
|
||||
var transactionDateResult: Result<Date, Error>?
|
||||
var transactionDateResult: Result<Date, any Error>?
|
||||
|
||||
/// The date of the current transaction.
|
||||
///
|
||||
@@ -1209,7 +1217,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// Now that transaction has begun, we'll rollback in case of error.
|
||||
// But we'll throw the first caught error, so that user knows
|
||||
// what happened.
|
||||
var firstError: Error? = nil
|
||||
var firstError: (any Error)? = nil
|
||||
let needsRollback: Bool
|
||||
do {
|
||||
let completion = try operations()
|
||||
@@ -1353,7 +1361,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// Now that savepoint has begun, we'll rollback in case of error.
|
||||
// But we'll throw the first caught error, so that user knows
|
||||
// what happened.
|
||||
var firstError: Error? = nil
|
||||
var firstError: (any Error)? = nil
|
||||
let needsRollback: Bool
|
||||
do {
|
||||
let completion = try operations()
|
||||
@@ -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.
|
||||
|
||||
@@ -186,7 +186,7 @@ extension ResultCode {
|
||||
/// // any other database error
|
||||
/// }
|
||||
/// ```
|
||||
public static func ~= (lhs: Self, rhs: Error) -> Bool {
|
||||
public static func ~= (lhs: Self, rhs: any Error) -> Bool {
|
||||
guard let error = rhs as? DatabaseError else { return false }
|
||||
return lhs ~= error.extendedResultCode
|
||||
}
|
||||
|
||||
@@ -403,7 +403,7 @@ public final class DatabaseFunction: Hashable {
|
||||
}
|
||||
}
|
||||
|
||||
private static func report(error: Error, in sqliteContext: OpaquePointer?) {
|
||||
private static func report(error: some Error, in sqliteContext: OpaquePointer?) {
|
||||
if let error = error as? DatabaseError {
|
||||
if let message = error.message {
|
||||
sqlite3_result_error(sqliteContext, message, -1)
|
||||
|
||||
@@ -14,7 +14,7 @@ public final class DatabasePool {
|
||||
@LockedBox var databaseSnapshotCount = 0
|
||||
|
||||
/// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers.
|
||||
private var suspensionObservers: [NSObjectProtocol] = []
|
||||
private var suspensionObservers: [any NSObjectProtocol] = []
|
||||
|
||||
// MARK: - Database Information
|
||||
|
||||
@@ -91,7 +91,9 @@ public final class DatabasePool {
|
||||
// See https://github.com/groue/GRDB.swift/#memory-management
|
||||
#if os(iOS)
|
||||
if configuration.automaticMemoryManagement {
|
||||
setupMemoryManagement()
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.setupMemoryManagement()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -221,6 +223,7 @@ extension DatabasePool {
|
||||
/// Listens to UIApplicationDidEnterBackgroundNotification and
|
||||
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
|
||||
/// as much memory as possible.
|
||||
@MainActor
|
||||
private func setupMemoryManagement() {
|
||||
let center = NotificationCenter.default
|
||||
center.addObserver(
|
||||
@@ -235,7 +238,7 @@ extension DatabasePool {
|
||||
object: nil)
|
||||
}
|
||||
|
||||
@objc
|
||||
@MainActor @objc
|
||||
private func applicationDidEnterBackground(_ notification: NSNotification) {
|
||||
guard let application = notification.object as? UIApplication else {
|
||||
return
|
||||
@@ -257,7 +260,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 +362,7 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func asyncRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
@@ -401,7 +406,7 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
@@ -446,25 +451,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, 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, Error>) -> Void) {
|
||||
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
asyncConcurrentRead(value)
|
||||
}
|
||||
|
||||
@@ -505,7 +503,7 @@ extension DatabasePool: DatabaseReader {
|
||||
/// ```
|
||||
///
|
||||
/// - parameter value: A function that accesses the database.
|
||||
public func asyncConcurrentRead(_ value: @escaping (Result<Database, 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 +663,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, Error>) -> Void) {
|
||||
func asyncWALSnapshotTransaction(_ completion: @escaping @Sendable (Result<WALSnapshotTransaction, any Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
completion(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
@@ -691,7 +689,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 +720,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 +754,7 @@ extension DatabasePool: DatabaseWriter {
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
updates(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
@@ -809,7 +807,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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ public final class DatabaseQueue {
|
||||
private let writer: SerializedDatabase
|
||||
|
||||
/// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers.
|
||||
private var suspensionObservers: [NSObjectProtocol] = []
|
||||
private var suspensionObservers: [any NSObjectProtocol] = []
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
@@ -65,7 +65,9 @@ public final class DatabaseQueue {
|
||||
// See https://github.com/groue/GRDB.swift/#memory-management
|
||||
#if os(iOS)
|
||||
if configuration.automaticMemoryManagement {
|
||||
setupMemoryManagement()
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.setupMemoryManagement()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -141,6 +143,7 @@ extension DatabaseQueue {
|
||||
/// Listens to UIApplicationDidEnterBackgroundNotification and
|
||||
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
|
||||
/// as much memory as possible.
|
||||
@MainActor
|
||||
private func setupMemoryManagement() {
|
||||
let center = NotificationCenter.default
|
||||
center.addObserver(
|
||||
@@ -155,7 +158,7 @@ extension DatabaseQueue {
|
||||
object: nil)
|
||||
}
|
||||
|
||||
@objc
|
||||
@MainActor @objc
|
||||
private func applicationDidEnterBackground(_ notification: NSNotification) {
|
||||
guard let application = notification.object as? UIApplication else {
|
||||
return
|
||||
@@ -169,7 +172,9 @@ extension DatabaseQueue {
|
||||
// Release memory asynchronously
|
||||
writer.async { db in
|
||||
db.releaseMemory()
|
||||
application.endBackgroundTask(task)
|
||||
DispatchQueue.main.async {
|
||||
application.endBackgroundTask(task)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -233,7 +238,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, 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 +263,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
try writer.sync(value)
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
writer.async { value(.success($0)) }
|
||||
}
|
||||
|
||||
@@ -266,7 +271,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 +284,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
})
|
||||
}
|
||||
|
||||
public func spawnConcurrentRead(_ value: @escaping (Result<Database, 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 +314,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 +384,7 @@ extension DatabaseQueue: DatabaseWriter {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
writer.async { updates(.success($0)) }
|
||||
}
|
||||
|
||||
@@ -425,7 +430,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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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, 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, 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)
|
||||
@@ -575,9 +573,9 @@ extension DatabasePublishers {
|
||||
/// You build such a publisher from ``DatabaseReader``.
|
||||
public struct Read<Output>: Publisher {
|
||||
public typealias Output = Output
|
||||
public typealias Failure = Error
|
||||
public typealias Failure = any Error
|
||||
|
||||
fileprivate let upstream: AnyPublisher<Output, Error>
|
||||
fileprivate let upstream: AnyPublisher<Output, any Error>
|
||||
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Self.Failure == S.Failure, Self.Output == S.Input {
|
||||
upstream.receive(subscriber: subscriber)
|
||||
@@ -586,7 +584,7 @@ extension DatabasePublishers {
|
||||
}
|
||||
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
extension Publisher where Failure == Error {
|
||||
extension Publisher where Failure == any Error {
|
||||
fileprivate func eraseToReadPublisher() -> DatabasePublishers.Read<Output> {
|
||||
.init(upstream: eraseToAnyPublisher())
|
||||
}
|
||||
@@ -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, 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, 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, Error>) -> Void) {
|
||||
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
asyncRead(value)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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 (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
|
||||
}
|
||||
@@ -188,7 +188,7 @@ extension DatabasePublishers {
|
||||
/// You build such a publisher from ``DatabaseRegionObservation``.
|
||||
public struct DatabaseRegion: Publisher {
|
||||
public typealias Output = Database
|
||||
public typealias Failure = Error
|
||||
public typealias Failure = any Error
|
||||
|
||||
let writer: any DatabaseWriter
|
||||
let observation: DatabaseRegionObservation
|
||||
@@ -207,8 +207,8 @@ extension DatabasePublishers {
|
||||
}
|
||||
}
|
||||
|
||||
private class DatabaseRegionSubscription<Downstream: Subscriber>: Subscription
|
||||
where Downstream.Failure == Error, Downstream.Input == Database
|
||||
private class DatabaseRegionSubscription<Downstream: Subscriber>: Subscription, @unchecked Sendable
|
||||
where Downstream.Failure == any Error, Downstream.Input == Database
|
||||
{
|
||||
private struct WaitingForDemand {
|
||||
let downstream: Downstream
|
||||
@@ -298,7 +298,7 @@ extension DatabasePublishers {
|
||||
}
|
||||
}
|
||||
|
||||
private func receive(failure error: Error) {
|
||||
private func receive(failure error: any Error) {
|
||||
lock.synchronized {
|
||||
if case let .observing(info) = state {
|
||||
state = .finished
|
||||
|
||||
@@ -154,7 +154,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
|
||||
try reader.sync(block)
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, 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, 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(
|
||||
|
||||
@@ -292,7 +292,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, 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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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, 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, 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, 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!) } })
|
||||
}
|
||||
}
|
||||
@@ -906,9 +906,9 @@ extension DatabasePublishers {
|
||||
/// You build such a publisher from ``DatabaseWriter``.
|
||||
public struct Write<Output>: Publisher {
|
||||
public typealias Output = Output
|
||||
public typealias Failure = Error
|
||||
public typealias Failure = any Error
|
||||
|
||||
fileprivate let upstream: AnyPublisher<Output, Error>
|
||||
fileprivate let upstream: AnyPublisher<Output, any Error>
|
||||
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Self.Failure == S.Failure, Self.Output == S.Input {
|
||||
upstream.receive(subscriber: subscriber)
|
||||
@@ -917,7 +917,7 @@ extension DatabasePublishers {
|
||||
}
|
||||
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
extension Publisher where Failure == Error {
|
||||
extension Publisher where Failure == any Error {
|
||||
fileprivate func eraseToWritePublisher() -> DatabasePublishers.Write<Output> {
|
||||
.init(upstream: self.eraseToAnyPublisher())
|
||||
}
|
||||
@@ -941,7 +941,7 @@ extension Publisher where Failure == 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
|
||||
|
||||
@@ -949,7 +949,7 @@ public class DatabaseFuture<Value> {
|
||||
_wait = wait
|
||||
}
|
||||
|
||||
init(_ result: Result<Value, Error>) {
|
||||
init(_ result: Result<Value, any Error>) {
|
||||
_wait = result.get
|
||||
}
|
||||
|
||||
@@ -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, 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, 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, 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, Error>) -> Void) {
|
||||
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
base.spawnConcurrentRead(value)
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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)!
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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"
|
||||
@@ -152,7 +152,7 @@ extension DatabaseDateComponents: DatabaseValueConvertible {
|
||||
}
|
||||
|
||||
extension DatabaseDateComponents: Decodable {
|
||||
public init(from decoder: Decoder) throws {
|
||||
public init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
let stringValue = try container.decode(String.self)
|
||||
guard let decodedValue = DatabaseDateComponents.fromDatabaseValue(stringValue.databaseValue) else {
|
||||
@@ -164,7 +164,7 @@ extension DatabaseDateComponents: Decodable {
|
||||
}
|
||||
|
||||
extension DatabaseDateComponents: Encodable {
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
public func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(String.fromDatabaseValue(databaseValue)!)
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
|
||||
@@ -161,12 +161,12 @@ private struct DatabaseValueDecoder: Decoder {
|
||||
throw JSONRequiredError()
|
||||
}
|
||||
|
||||
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
|
||||
func unkeyedContainer() throws -> any UnkeyedDecodingContainer {
|
||||
// We need to switch to JSON decoding
|
||||
throw JSONRequiredError()
|
||||
}
|
||||
|
||||
func singleValueContainer() throws -> SingleValueDecodingContainer {
|
||||
func singleValueContainer() throws -> any SingleValueDecodingContainer {
|
||||
DatabaseValueDecodingContainer(dbValue: dbValue, codingPath: codingPath)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ private class DatabaseValueEncoder: Encoder {
|
||||
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
|
||||
/// - precondition: May not be called after a value has been encoded through
|
||||
/// a previous `self.singleValueContainer()` call.
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer {
|
||||
func unkeyedContainer() -> any UnkeyedEncodingContainer {
|
||||
// We need to perform JSON encoding. Unfortunately we can't access the
|
||||
// inner container of Foundation's JSONEncoder. At this point we must
|
||||
// throw an error so that the caller can retry encoding from scratch.
|
||||
@@ -109,7 +109,7 @@ private class DatabaseValueEncoder: Encoder {
|
||||
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
|
||||
/// - precondition: May not be called after a value has been encoded through
|
||||
/// a previous `self.singleValueContainer()` call.
|
||||
func singleValueContainer() -> SingleValueEncodingContainer {
|
||||
func singleValueContainer() -> any SingleValueEncodingContainer {
|
||||
DatabaseValueEncodingContainer(encode: encode, jsonEncoder: jsonEncoder)
|
||||
}
|
||||
|
||||
|
||||
@@ -10,9 +10,9 @@ struct JSONRequiredEncoder: Encoder {
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer { self }
|
||||
func unkeyedContainer() -> any UnkeyedEncodingContainer { self }
|
||||
|
||||
func singleValueContainer() -> SingleValueEncodingContainer { self }
|
||||
func singleValueContainer() -> any SingleValueEncodingContainer { self }
|
||||
|
||||
struct KeyedContainer<KeyType: CodingKey>: KeyedEncodingContainerProtocol {
|
||||
var codingPath: [any CodingKey]
|
||||
@@ -47,15 +47,15 @@ struct JSONRequiredEncoder: Encoder {
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
func nestedUnkeyedContainer(forKey key: KeyType) -> UnkeyedEncodingContainer {
|
||||
func nestedUnkeyedContainer(forKey key: KeyType) -> any UnkeyedEncodingContainer {
|
||||
JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
|
||||
func superEncoder() -> Encoder {
|
||||
func superEncoder() -> any Encoder {
|
||||
JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
|
||||
func superEncoder(forKey key: KeyType) -> Encoder {
|
||||
func superEncoder(forKey key: KeyType) -> any Encoder {
|
||||
JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
}
|
||||
@@ -91,7 +91,7 @@ extension JSONRequiredEncoder: UnkeyedEncodingContainer {
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { self }
|
||||
mutating func nestedUnkeyedContainer() -> any UnkeyedEncodingContainer { self }
|
||||
|
||||
mutating func superEncoder() -> Encoder { self }
|
||||
mutating func superEncoder() -> any Encoder { self }
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -751,7 +754,7 @@ class DatabaseObservationBroker {
|
||||
|
||||
/// Transaction turns rollbacked because a transaction observer has
|
||||
/// cancelled a commit by throwing an error.
|
||||
case cancelledCommit(Error)
|
||||
case cancelledCommit(any Error)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
+1
-1
@@ -58,7 +58,7 @@ extension DatabaseMigrator {
|
||||
@available(*, unavailable, message: "The completion function now accepts one Result<Database, Error> argument")
|
||||
public func asyncMigrate(
|
||||
_ writer: any DatabaseWriter,
|
||||
completion: @escaping (Database, Error?) -> Void)
|
||||
completion: @escaping (Database, (any Error)?) -> Void)
|
||||
{ preconditionFailure() }
|
||||
}
|
||||
|
||||
|
||||
@@ -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, Error>) -> Void)
|
||||
completion: @escaping @Sendable (Result<Database, any Error>) -> Void)
|
||||
{
|
||||
writer.asyncBarrierWriteWithoutTransaction { dbResult in
|
||||
do {
|
||||
@@ -523,9 +523,9 @@ extension DatabasePublishers {
|
||||
/// You build such a publisher from ``DatabaseMigrator``.
|
||||
public struct Migrate: Publisher {
|
||||
public typealias Output = Void
|
||||
public typealias Failure = Error
|
||||
public typealias Failure = any Error
|
||||
|
||||
fileprivate let upstream: AnyPublisher<Void, Error>
|
||||
fileprivate let upstream: AnyPublisher<Void, any Error>
|
||||
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Self.Failure == S.Failure, Self.Output == S.Input {
|
||||
upstream.receive(subscriber: subscriber)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
@@ -138,7 +138,7 @@ extension SQLOrdering {
|
||||
/// ### Supporting Type
|
||||
///
|
||||
/// - ``SQLOrdering``
|
||||
public protocol SQLOrderingTerm {
|
||||
public protocol SQLOrderingTerm: Sendable {
|
||||
/// Returns an SQL ordering.
|
||||
var sqlOrdering: SQLOrdering { get }
|
||||
}
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -365,7 +365,7 @@ extension Database {
|
||||
view name: String,
|
||||
options: ViewOptions = [],
|
||||
columns: [String]? = nil,
|
||||
as request: SQLSubqueryable)
|
||||
as request: some SQLSubqueryable)
|
||||
throws {
|
||||
var literal: SQL = "CREATE "
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -29,11 +29,11 @@ private class RecordEncoder<Record: EncodableRecord>: Encoder {
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer {
|
||||
func unkeyedContainer() -> any UnkeyedEncodingContainer {
|
||||
fatalError("unkeyed encoding is not supported")
|
||||
}
|
||||
|
||||
func singleValueContainer() -> SingleValueEncodingContainer {
|
||||
func singleValueContainer() -> any SingleValueEncodingContainer {
|
||||
// @itaiferber on https://forums.swift.org/t/how-to-encode-objects-of-unknown-type/12253/11
|
||||
//
|
||||
// > Encoding a value into a single-value container is equivalent to
|
||||
@@ -109,15 +109,15 @@ private class RecordEncoder<Record: EncodableRecord>: Encoder {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
|
||||
func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
|
||||
func nestedUnkeyedContainer(forKey key: Key) -> any UnkeyedEncodingContainer {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
|
||||
func superEncoder() -> Encoder {
|
||||
func superEncoder() -> any Encoder {
|
||||
recordEncoder
|
||||
}
|
||||
|
||||
func superEncoder(forKey key: Key) -> Encoder {
|
||||
func superEncoder(forKey key: Key) -> any Encoder {
|
||||
recordEncoder
|
||||
}
|
||||
}
|
||||
@@ -195,7 +195,7 @@ private class ColumnEncoder<Record: EncodableRecord>: Encoder {
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer {
|
||||
func unkeyedContainer() -> any UnkeyedEncodingContainer {
|
||||
// We need to perform JSON encoding. Unfortunately we can't access the
|
||||
// inner container of Foundation's JSONEncoder. At this point we must
|
||||
// throw an error so that the caller can retry encoding from scratch.
|
||||
@@ -205,7 +205,7 @@ private class ColumnEncoder<Record: EncodableRecord>: Encoder {
|
||||
return JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
|
||||
func singleValueContainer() -> SingleValueEncodingContainer { self }
|
||||
func singleValueContainer() -> any SingleValueEncodingContainer { self }
|
||||
}
|
||||
|
||||
extension ColumnEncoder: SingleValueEncodingContainer {
|
||||
|
||||
@@ -79,7 +79,7 @@ public class FetchableRecordDecoder {
|
||||
/// The decoder that decodes a record from a database row
|
||||
private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
var row: Row
|
||||
var codingPath: [CodingKey]
|
||||
var codingPath: [any CodingKey]
|
||||
var columnDecodingStrategy: DatabaseColumnDecodingStrategy
|
||||
var userInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo }
|
||||
|
||||
@@ -87,7 +87,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
KeyedDecodingContainer(KeyedContainer<Key>(decoder: self))
|
||||
}
|
||||
|
||||
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
|
||||
func unkeyedContainer() throws -> any UnkeyedDecodingContainer {
|
||||
guard let codingKey = codingPath.last else {
|
||||
fatalError("unkeyed decoding from database row is not supported")
|
||||
}
|
||||
@@ -105,7 +105,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
debugDescription: debugDescription))
|
||||
}
|
||||
|
||||
func singleValueContainer() throws -> SingleValueDecodingContainer {
|
||||
func singleValueContainer() throws -> any SingleValueDecodingContainer {
|
||||
guard let key = codingPath.last else {
|
||||
// Decoding an array of scalars from rows: pick the first column
|
||||
return ColumnDecoder<R>(row: row, columnIndex: 0, codingPath: codingPath)
|
||||
@@ -123,8 +123,8 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
|
||||
class KeyedContainer<Key: CodingKey>: KeyedDecodingContainerProtocol {
|
||||
private let decoder: _RowDecoder
|
||||
var codingPath: [CodingKey] { decoder.codingPath }
|
||||
private var decodedRootKey: CodingKey?
|
||||
var codingPath: [any CodingKey] { decoder.codingPath }
|
||||
private var decodedRootKey: (any CodingKey)?
|
||||
// Not nil iff decoder has a columnDecodingStrategy
|
||||
private let _columnForKey: [String: String]?
|
||||
|
||||
@@ -378,17 +378,17 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
fatalError("not implemented")
|
||||
}
|
||||
|
||||
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
|
||||
func nestedUnkeyedContainer(forKey key: Key) throws -> any UnkeyedDecodingContainer {
|
||||
throw DecodingError.typeMismatch(
|
||||
UnkeyedDecodingContainer.self,
|
||||
(any UnkeyedDecodingContainer).self,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
|
||||
}
|
||||
|
||||
func superDecoder() throws -> Decoder {
|
||||
func superDecoder() throws -> any Decoder {
|
||||
decoder
|
||||
}
|
||||
|
||||
func superDecoder(forKey key: Key) throws -> Decoder {
|
||||
func superDecoder(forKey key: Key) throws -> any Decoder {
|
||||
decoder
|
||||
}
|
||||
|
||||
@@ -397,7 +397,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
private func decode<T>(
|
||||
_ type: T.Type,
|
||||
fromRow row: Row,
|
||||
codingPath: [CodingKey])
|
||||
codingPath: [any CodingKey])
|
||||
throws -> T
|
||||
where T: Decodable
|
||||
{
|
||||
@@ -449,11 +449,11 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
|
||||
private struct PrefetchedRowsDecoder<R: FetchableRecord>: Decoder {
|
||||
var rows: [Row]
|
||||
var codingPath: [CodingKey]
|
||||
var codingPath: [any CodingKey]
|
||||
var currentIndex: Int
|
||||
var userInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo }
|
||||
|
||||
init(rows: [Row], codingPath: [CodingKey]) {
|
||||
init(rows: [Row], codingPath: [any CodingKey]) {
|
||||
self.rows = rows
|
||||
self.codingPath = codingPath
|
||||
self.currentIndex = 0
|
||||
@@ -463,9 +463,9 @@ private struct PrefetchedRowsDecoder<R: FetchableRecord>: Decoder {
|
||||
fatalError("keyed decoding from prefetched rows is not supported")
|
||||
}
|
||||
|
||||
func unkeyedContainer() throws -> UnkeyedDecodingContainer { self }
|
||||
func unkeyedContainer() throws -> any UnkeyedDecodingContainer { self }
|
||||
|
||||
func singleValueContainer() throws -> SingleValueDecodingContainer {
|
||||
func singleValueContainer() throws -> any SingleValueDecodingContainer {
|
||||
fatalError("single value decoding from prefetched rows is not supported")
|
||||
}
|
||||
}
|
||||
@@ -501,11 +501,11 @@ extension PrefetchedRowsDecoder: UnkeyedDecodingContainer {
|
||||
fatalError("not implemented")
|
||||
}
|
||||
|
||||
mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
|
||||
mutating func nestedUnkeyedContainer() throws -> any UnkeyedDecodingContainer {
|
||||
fatalError("not implemented")
|
||||
}
|
||||
|
||||
mutating func superDecoder() throws -> Decoder {
|
||||
mutating func superDecoder() throws -> any Decoder {
|
||||
fatalError("not implemented")
|
||||
}
|
||||
}
|
||||
@@ -516,7 +516,7 @@ extension PrefetchedRowsDecoder: UnkeyedDecodingContainer {
|
||||
private struct ColumnDecoder<R: FetchableRecord>: Decoder {
|
||||
var row: Row
|
||||
var columnIndex: Int
|
||||
var codingPath: [CodingKey]
|
||||
var codingPath: [any CodingKey]
|
||||
var userInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo }
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
|
||||
@@ -524,12 +524,12 @@ private struct ColumnDecoder<R: FetchableRecord>: Decoder {
|
||||
throw JSONRequiredError()
|
||||
}
|
||||
|
||||
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
|
||||
func unkeyedContainer() throws -> any UnkeyedDecodingContainer {
|
||||
// We need to switch to JSON decoding
|
||||
throw JSONRequiredError()
|
||||
}
|
||||
|
||||
func singleValueContainer() throws -> SingleValueDecodingContainer { self }
|
||||
func singleValueContainer() throws -> any SingleValueDecodingContainer { self }
|
||||
}
|
||||
|
||||
extension ColumnDecoder: SingleValueDecodingContainer {
|
||||
|
||||
@@ -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 []
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -967,7 +967,7 @@ public enum DatabaseColumnDecodingStrategy {
|
||||
case convertFromSnakeCase
|
||||
|
||||
/// A key decoding strategy defined by the closure you supply.
|
||||
case custom((String) -> CodingKey)
|
||||
case custom((String) -> any CodingKey)
|
||||
|
||||
func key<K: CodingKey>(forColumn column: String) -> K? {
|
||||
switch self {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}()
|
||||
}
|
||||
}
|
||||
@@ -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] = [:]
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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), 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()
|
||||
|
||||
@@ -48,7 +48,7 @@ where
|
||||
private enum State {
|
||||
case waitingForRequest(Upstream, Target)
|
||||
case waitingForSubscription(Target, Subscribers.Demand)
|
||||
case subscribed(Target, Subscription)
|
||||
case subscribed(Target, any Subscription)
|
||||
case finished
|
||||
}
|
||||
|
||||
@@ -110,7 +110,7 @@ where
|
||||
|
||||
// MARK: Subscriber
|
||||
|
||||
func receive(subscription: Subscription) {
|
||||
func receive(subscription: any Subscription) {
|
||||
lock.synchronized { sideEffect in
|
||||
switch state {
|
||||
case let .waitingForSubscription(target, currentDemand):
|
||||
|
||||
+17
-4
@@ -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
|
||||
@@ -99,7 +99,7 @@ extension Sequence {
|
||||
/// finally: cleanup)
|
||||
func throwingFirstError<T>(execute: () throws -> T, finally: () throws -> Void) throws -> T {
|
||||
var result: T?
|
||||
var firstError: Error?
|
||||
var firstError: (any Error)?
|
||||
do {
|
||||
result = try execute()
|
||||
} catch {
|
||||
@@ -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
|
||||
|
||||
@@ -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 */ }
|
||||
|
||||
@@ -817,7 +817,7 @@ extension ValueConcurrentObserver: TransactionObserver {
|
||||
}
|
||||
}
|
||||
|
||||
private func reduce(_ fetchResult: Result<Reducer.Fetched, Error>) {
|
||||
private func reduce(_ fetchResult: Result<Reducer.Fetched, any Error>) {
|
||||
reduceQueue.async {
|
||||
do {
|
||||
let fetchedValue = try fetchResult.get()
|
||||
@@ -874,7 +874,7 @@ extension ValueConcurrentObserver: DatabaseCancellable {
|
||||
}
|
||||
}
|
||||
|
||||
func notifyError(_ error: Error) {
|
||||
func notifyError(_ error: any Error) {
|
||||
scheduler.schedule {
|
||||
let events = self.lock.synchronized {
|
||||
let events = self.notificationCallbacks?.events
|
||||
|
||||
@@ -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
|
||||
@@ -457,7 +457,7 @@ extension ValueWriteOnlyObserver: DatabaseCancellable {
|
||||
}
|
||||
}
|
||||
|
||||
func notifyError(_ error: Error) {
|
||||
func notifyError(_ error: any Error) {
|
||||
scheduler.schedule {
|
||||
let events = self.lock.synchronized {
|
||||
let events = self.notificationCallbacks?.events
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
@@ -177,13 +177,16 @@ public final class SharedValueObservation<Element> {
|
||||
private var clients: [Client]
|
||||
private var isObserving = false
|
||||
private var cancellable: AnyDatabaseCancellable?
|
||||
private var lastResult: Result<Element, Error>?
|
||||
private var lastResult: Result<Element, any Error>?
|
||||
|
||||
private final class Client {
|
||||
var onError: (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 (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 (Error) -> Void,
|
||||
onChange: @escaping (Element) -> Void)
|
||||
onError: @escaping @Sendable (any Error) -> Void,
|
||||
onChange: @escaping @Sendable (Element) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
synchronized {
|
||||
@@ -299,7 +302,7 @@ public final class SharedValueObservation<Element> {
|
||||
}
|
||||
#endif
|
||||
|
||||
private func handleError(_ error: Error) {
|
||||
private func handleError(_ error: any Error) {
|
||||
synchronized {
|
||||
let notifiedClients = clients
|
||||
|
||||
|
||||
@@ -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: ((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 (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 (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: ((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: 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") })
|
||||
}
|
||||
|
||||
@@ -333,7 +325,7 @@ extension ValueObservation {
|
||||
/// ``SharedValueObservation``.
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public struct AsyncValueObservation<Element>: AsyncSequence {
|
||||
public typealias BufferingPolicy = AsyncThrowingStream<Element, Error>.Continuation.BufferingPolicy
|
||||
public typealias BufferingPolicy = AsyncThrowingStream<Element, any Error>.Continuation.BufferingPolicy
|
||||
public typealias AsyncIterator = Iterator
|
||||
|
||||
var bufferingPolicy: BufferingPolicy
|
||||
@@ -377,7 +369,7 @@ public struct AsyncValueObservation<Element>: AsyncSequence {
|
||||
}
|
||||
|
||||
public struct Iterator: AsyncIteratorProtocol {
|
||||
var iterator: AsyncThrowingStream<Element, Error>.AsyncIterator
|
||||
var iterator: AsyncThrowingStream<Element, any Error>.AsyncIterator
|
||||
let cancellable: AnyDatabaseCancellable
|
||||
|
||||
public mutating func next() async throws -> Element? {
|
||||
@@ -457,7 +449,7 @@ extension DatabasePublishers {
|
||||
/// You build such a publisher from ``ValueObservation``
|
||||
/// or ``SharedValueObservation``.
|
||||
public struct Value<Output>: Publisher {
|
||||
public typealias Failure = Error
|
||||
public typealias Failure = any Error
|
||||
private let start: ValueObservationStart<Output>
|
||||
|
||||
init(start: @escaping ValueObservationStart<Output>) {
|
||||
@@ -472,8 +464,8 @@ extension DatabasePublishers {
|
||||
}
|
||||
}
|
||||
|
||||
private class ValueSubscription<Downstream: Subscriber>: Subscription
|
||||
where Downstream.Failure == Error
|
||||
private class ValueSubscription<Downstream: Subscriber>: Subscription, @unchecked Sendable
|
||||
where Downstream.Failure == any Error
|
||||
{
|
||||
private struct WaitingForDemand {
|
||||
let downstream: Downstream
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
+1
-5
@@ -10,9 +10,6 @@ var swiftSettings: [SwiftSetting] = [
|
||||
var cSettings: [CSetting] = []
|
||||
var dependencies: [PackageDescription.Package.Dependency] = []
|
||||
|
||||
// For Swift 5.8+
|
||||
//swiftSettings.append(.enableUpcomingFeature("ExistentialAny"))
|
||||
|
||||
// Don't rely on those environment variables. They are ONLY testing conveniences:
|
||||
// $ SQLITE_ENABLE_PREUPDATE_HOOK=1 make test_SPM
|
||||
if ProcessInfo.processInfo.environment["SQLITE_ENABLE_PREUPDATE_HOOK"] == "1" {
|
||||
@@ -77,6 +74,5 @@ let package = Package(
|
||||
],
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings)
|
||||
],
|
||||
swiftLanguageVersions: [.v5]
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,83 @@
|
||||
// swift-tools-version:5.9
|
||||
// The swift-tools-version declares the minimum version of Swift required to build this package.
|
||||
|
||||
import Foundation
|
||||
import PackageDescription
|
||||
|
||||
var swiftSettings: [SwiftSetting] = [
|
||||
.define("SQLITE_ENABLE_FTS5"),
|
||||
// <https://github.com/apple/swift-evolution/blob/main/proposals/0335-existential-any.md>
|
||||
.enableUpcomingFeature("ExistentialAny"),
|
||||
]
|
||||
var cSettings: [CSetting] = []
|
||||
var dependencies: [PackageDescription.Package.Dependency] = []
|
||||
|
||||
// Don't rely on those environment variables. They are ONLY testing conveniences:
|
||||
// $ SQLITE_ENABLE_PREUPDATE_HOOK=1 make test_SPM
|
||||
if ProcessInfo.processInfo.environment["SQLITE_ENABLE_PREUPDATE_HOOK"] == "1" {
|
||||
swiftSettings.append(.define("SQLITE_ENABLE_PREUPDATE_HOOK"))
|
||||
cSettings.append(.define("GRDB_SQLITE_ENABLE_PREUPDATE_HOOK"))
|
||||
}
|
||||
|
||||
// The SPI_BUILDER environment variable enables documentation building
|
||||
// on <https://swiftpackageindex.com/groue/GRDB.swift>. See
|
||||
// <https://github.com/SwiftPackageIndex/SwiftPackageIndex-Server/issues/2122>
|
||||
// for more information.
|
||||
//
|
||||
// SPI_BUILDER also enables the `make docs-localhost` command.
|
||||
if ProcessInfo.processInfo.environment["SPI_BUILDER"] == "1" {
|
||||
dependencies.append(.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"))
|
||||
}
|
||||
|
||||
let package = Package(
|
||||
name: "GRDB",
|
||||
defaultLocalization: "en", // for tests
|
||||
platforms: [
|
||||
.iOS(.v11),
|
||||
.macOS(.v10_13),
|
||||
.tvOS(.v11),
|
||||
.watchOS(.v4),
|
||||
],
|
||||
products: [
|
||||
.library(name: "CSQLite", targets: ["CSQLite"]),
|
||||
.library(name: "GRDB", targets: ["GRDB"]),
|
||||
.library(name: "GRDB-dynamic", type: .dynamic, targets: ["GRDB"]),
|
||||
],
|
||||
dependencies: dependencies,
|
||||
targets: [
|
||||
.systemLibrary(
|
||||
name: "CSQLite",
|
||||
providers: [.apt(["libsqlite3-dev"])]),
|
||||
.target(
|
||||
name: "GRDB",
|
||||
dependencies: ["CSQLite"],
|
||||
path: "GRDB",
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings + [
|
||||
// <https://github.com/apple/swift-evolution/blob/main/proposals/0337-support-incremental-migration-to-concurrency-checking.md>
|
||||
.enableExperimentalFeature("StrictConcurrency"),
|
||||
]),
|
||||
.testTarget(
|
||||
name: "GRDBTests",
|
||||
dependencies: ["GRDB"],
|
||||
path: "Tests",
|
||||
exclude: [
|
||||
"CocoaPods",
|
||||
"Crash",
|
||||
"CustomSQLite",
|
||||
"GRDBTests/getThreadsCount.c",
|
||||
"Info.plist",
|
||||
"Performance",
|
||||
"SPM",
|
||||
"generatePerformanceReport.rb",
|
||||
"parsePerformanceTests.rb",
|
||||
],
|
||||
resources: [
|
||||
.copy("GRDBTests/Betty.jpeg"),
|
||||
.copy("GRDBTests/InflectionsTests.json"),
|
||||
.copy("GRDBTests/Issue1383.sqlite"),
|
||||
],
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings)
|
||||
]
|
||||
)
|
||||
@@ -40,7 +40,7 @@ public class Recorder<Input, Failure: Error>: Subscriber {
|
||||
|
||||
/// Publisher is subscribed. The recorder may have an expectation to
|
||||
/// fulfill. It keeps track of all published elements.
|
||||
case subscribed(Subscription, RecorderExpectation?, [Input])
|
||||
case subscribed(any Subscription, RecorderExpectation?, [Input])
|
||||
|
||||
/// Publisher is completed. The recorder keeps track of all published
|
||||
/// elements and completion.
|
||||
@@ -204,7 +204,7 @@ public class Recorder<Input, Failure: Error>: Subscriber {
|
||||
|
||||
// MARK: - Subscriber
|
||||
|
||||
public func receive(subscription: Subscription) {
|
||||
public func receive(subscription: any Subscription) {
|
||||
synchronized {
|
||||
switch state {
|
||||
case let .waitingForSubscription(exp):
|
||||
|
||||
@@ -72,7 +72,7 @@ class DatabaseRegionObservationPublisherTests : XCTestCase {
|
||||
|
||||
func test(writer: some DatabaseWriter) throws {
|
||||
let expectation = self.expectation(description: "")
|
||||
let testSubject = PassthroughSubject<Database, Error>()
|
||||
let testSubject = PassthroughSubject<Database, any Error>()
|
||||
let testCancellable = testSubject
|
||||
.tryMap(Player.fetchCount)
|
||||
.collect(3)
|
||||
|
||||
@@ -397,7 +397,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase {
|
||||
|
||||
func test(writer: some DatabaseWriter, iteration: Int) throws {
|
||||
// print(iteration)
|
||||
let scoreSubject = PassthroughSubject<Int, Error>()
|
||||
let scoreSubject = PassthroughSubject<Int, any Error>()
|
||||
let publisher = scoreSubject
|
||||
.map { score in
|
||||
writer.writePublisher { db -> Int in
|
||||
|
||||
@@ -176,7 +176,7 @@ class ValueObservationPublisherTests : XCTestCase {
|
||||
|
||||
func test(writer: some DatabaseWriter) throws {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
let testSubject = PassthroughSubject<Int, Error>()
|
||||
let testSubject = PassthroughSubject<Int, any Error>()
|
||||
let testCancellable = testSubject
|
||||
.sink(
|
||||
receiveCompletion: { _ in },
|
||||
@@ -228,7 +228,7 @@ class ValueObservationPublisherTests : XCTestCase {
|
||||
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
private class DemandSubscriber<Input, Failure: Error>: Subscriber {
|
||||
private var subscription: Subscription?
|
||||
private var subscription: (any Subscription)?
|
||||
let subject = PassthroughSubject<Input, Failure>()
|
||||
deinit {
|
||||
subscription?.cancel()
|
||||
@@ -242,7 +242,7 @@ class ValueObservationPublisherTests : XCTestCase {
|
||||
subscription!.request(demand)
|
||||
}
|
||||
|
||||
func receive(subscription: Subscription) {
|
||||
func receive(subscription: any Subscription) {
|
||||
self.subscription = subscription
|
||||
}
|
||||
|
||||
@@ -267,7 +267,7 @@ class ValueObservationPublisherTests : XCTestCase {
|
||||
}
|
||||
|
||||
func test(writer: some DatabaseWriter) throws {
|
||||
let subscriber = DemandSubscriber<Int, Error>()
|
||||
let subscriber = DemandSubscriber<Int, any Error>()
|
||||
|
||||
let expectation = self.expectation(description: "")
|
||||
expectation.isInverted = true
|
||||
@@ -302,7 +302,7 @@ class ValueObservationPublisherTests : XCTestCase {
|
||||
}
|
||||
|
||||
func test(writer: some DatabaseWriter) throws {
|
||||
let subscriber = DemandSubscriber<Int, Error>()
|
||||
let subscriber = DemandSubscriber<Int, any Error>()
|
||||
let expectation = self.expectation(description: "")
|
||||
|
||||
let testCancellable = subscriber.subject.sink(
|
||||
@@ -340,7 +340,7 @@ class ValueObservationPublisherTests : XCTestCase {
|
||||
}
|
||||
|
||||
func test(writer: some DatabaseWriter) throws {
|
||||
let subscriber = DemandSubscriber<Int, Error>()
|
||||
let subscriber = DemandSubscriber<Int, any Error>()
|
||||
let expectation = self.expectation(description: "")
|
||||
expectation.isInverted = true
|
||||
|
||||
@@ -382,7 +382,7 @@ class ValueObservationPublisherTests : XCTestCase {
|
||||
}
|
||||
|
||||
func test(writer: some DatabaseWriter) throws {
|
||||
let subscriber = DemandSubscriber<Int, Error>()
|
||||
let subscriber = DemandSubscriber<Int, any Error>()
|
||||
let expectation = self.expectation(description: "")
|
||||
|
||||
let testCancellable = subscriber.subject
|
||||
|
||||
@@ -127,7 +127,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
enum CodingKeys: CodingKey { case a, bs }
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
a = try container.decode(A.self, forKey: .a)
|
||||
if try container.decodeNil(forKey: .bs) {
|
||||
@@ -307,7 +307,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
enum CodingKeys: CodingKey { case a, bs }
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
a = try container.decode(A.self, forKey: .a)
|
||||
if try container.decodeNil(forKey: .bs) {
|
||||
|
||||
@@ -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 { }
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1334,7 +1343,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
// of NSFileCoordinator. What a weird API.
|
||||
let coordinator = NSFileCoordinator(filePresenter: nil)
|
||||
var coordinatorError: NSError?
|
||||
var poolError: Error?
|
||||
var poolError: (any Error)?
|
||||
coordinator.coordinate(writingItemAt: dbURL, options: .forMerging, error: &coordinatorError) { url in
|
||||
do {
|
||||
_ = try DatabasePool(path: url.path)
|
||||
@@ -1355,7 +1364,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
let coordinator = NSFileCoordinator(filePresenter: nil)
|
||||
var coordinatorError: NSError?
|
||||
var dbPool: DatabasePool?
|
||||
var dbError: Error?
|
||||
var dbError: (any Error)?
|
||||
coordinator.coordinate(writingItemAt: databaseURL, options: .forMerging, error: &coordinatorError) { url in
|
||||
do {
|
||||
dbPool = try openDatabase(at: url)
|
||||
@@ -1384,7 +1393,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
let coordinator = NSFileCoordinator(filePresenter: nil)
|
||||
var coordinatorError: NSError?
|
||||
var dbPool: DatabasePool?
|
||||
var dbError: Error?
|
||||
var dbError: (any Error)?
|
||||
coordinator.coordinate(readingItemAt: databaseURL, options: .withoutChanges, error: &coordinatorError) { url in
|
||||
do {
|
||||
dbPool = try openReadOnlyDatabase(at: url)
|
||||
|
||||
@@ -57,10 +57,12 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
|
||||
// Precondition: there is one reader.
|
||||
try dbPool.read { _ in }
|
||||
|
||||
// Simulate memory warning.
|
||||
NotificationCenter.default.post(
|
||||
name: UIApplication.didReceiveMemoryWarningNotification,
|
||||
object: nil)
|
||||
// Eventually simulate memory warning (after dbPool could register).
|
||||
DispatchQueue.main.async {
|
||||
NotificationCenter.default.post(
|
||||
name: UIApplication.didReceiveMemoryWarningNotification,
|
||||
object: nil)
|
||||
}
|
||||
|
||||
// Postcondition: reader connection was closed
|
||||
withExtendedLifetime(dbPool) { _ in
|
||||
@@ -85,10 +87,12 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
|
||||
// Precondition: there is one reader.
|
||||
try dbPool.read { _ in }
|
||||
|
||||
// Simulate memory warning.
|
||||
NotificationCenter.default.post(
|
||||
name: UIApplication.didReceiveMemoryWarningNotification,
|
||||
object: nil)
|
||||
// Eventually simulate memory warning (after dbPool could register).
|
||||
DispatchQueue.main.async {
|
||||
NotificationCenter.default.post(
|
||||
name: UIApplication.didReceiveMemoryWarningNotification,
|
||||
object: nil)
|
||||
}
|
||||
|
||||
// Postcondition: no reader connection was closed
|
||||
withExtendedLifetime(dbPool) { _ in
|
||||
@@ -106,10 +110,12 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
|
||||
semaphore.wait()
|
||||
}
|
||||
|
||||
// Simulate memory warning.
|
||||
NotificationCenter.default.post(
|
||||
name: UIApplication.didReceiveMemoryWarningNotification,
|
||||
object: nil)
|
||||
// Eventually simulate memory warning (after dbPool could register).
|
||||
DispatchQueue.main.async {
|
||||
NotificationCenter.default.post(
|
||||
name: UIApplication.didReceiveMemoryWarningNotification,
|
||||
object: nil)
|
||||
}
|
||||
|
||||
// Make sure we can read
|
||||
try dbPool.read { _ in }
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)"])
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ class DatabaseValueConvertibleDecodableTests: GRDBTestCase {
|
||||
struct Value : Decodable, DatabaseValueConvertible {
|
||||
let string: String
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
string = try decoder.singleValueContainer().decode(String.self)
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ class DatabaseValueConvertibleDecodableTests: GRDBTestCase {
|
||||
struct Value : Decodable, DatabaseValueConvertible {
|
||||
let string: String
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
string = try decoder.singleValueContainer().decode(String.self)
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ class DatabaseValueConvertibleDecodableTests: GRDBTestCase {
|
||||
struct ValueWrapper : Decodable, DatabaseValueConvertible {
|
||||
let value: Value
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
value = try decoder.singleValueContainer().decode(Value.self)
|
||||
}
|
||||
|
||||
@@ -91,13 +91,13 @@ class DatabaseValueConvertibleDecodableTests: GRDBTestCase {
|
||||
struct Nested : Decodable {
|
||||
let string: String
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
string = try decoder.singleValueContainer().decode(String.self)
|
||||
}
|
||||
}
|
||||
let nested: Nested
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
nested = try decoder.singleValueContainer().decode(Nested.self)
|
||||
}
|
||||
|
||||
@@ -162,7 +162,7 @@ class DatabaseValueConvertibleDecodableTests: GRDBTestCase {
|
||||
struct Value: Decodable, DatabaseValueConvertible {
|
||||
let dictionary: [String: Int]
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
dictionary = try .init(from: decoder)
|
||||
}
|
||||
|
||||
@@ -195,7 +195,7 @@ class DatabaseValueConvertibleDecodableTests: GRDBTestCase {
|
||||
struct Value: Decodable, DatabaseValueConvertible {
|
||||
let strings: [String]
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
strings = try .init(from: decoder)
|
||||
}
|
||||
|
||||
@@ -228,7 +228,7 @@ class DatabaseValueConvertibleDecodableTests: GRDBTestCase {
|
||||
struct Value: Decodable, DatabaseValueConvertible {
|
||||
let dictionary: [String: Int]
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
dictionary = try container.decode([String: Int].self)
|
||||
}
|
||||
@@ -262,7 +262,7 @@ class DatabaseValueConvertibleDecodableTests: GRDBTestCase {
|
||||
struct Value: Decodable, DatabaseValueConvertible {
|
||||
let strings: [String]
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
strings = try container.decode([String].self)
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ class DatabaseValueConvertibleEncodableTests: GRDBTestCase {
|
||||
struct Value : Encodable, DatabaseValueConvertible {
|
||||
let string: String
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(string)
|
||||
}
|
||||
@@ -28,7 +28,7 @@ class DatabaseValueConvertibleEncodableTests: GRDBTestCase {
|
||||
struct Value : Encodable, DatabaseValueConvertible {
|
||||
let string: String
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(string)
|
||||
}
|
||||
@@ -41,7 +41,7 @@ class DatabaseValueConvertibleEncodableTests: GRDBTestCase {
|
||||
struct Wrapper : Encodable, DatabaseValueConvertible {
|
||||
let value: Value
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(value)
|
||||
}
|
||||
@@ -63,14 +63,14 @@ class DatabaseValueConvertibleEncodableTests: GRDBTestCase {
|
||||
struct Nested : Encodable {
|
||||
let string: String
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(string)
|
||||
}
|
||||
}
|
||||
let nested: Nested
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(nested)
|
||||
}
|
||||
@@ -111,7 +111,7 @@ class DatabaseValueConvertibleEncodableTests: GRDBTestCase {
|
||||
struct Value: Encodable, DatabaseValueConvertible {
|
||||
let dictionary: [String: Int]
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
try dictionary.encode(to: encoder)
|
||||
}
|
||||
|
||||
@@ -135,7 +135,7 @@ class DatabaseValueConvertibleEncodableTests: GRDBTestCase {
|
||||
struct Value: Encodable, DatabaseValueConvertible {
|
||||
let strings: [String]
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
try strings.encode(to: encoder)
|
||||
}
|
||||
|
||||
@@ -159,7 +159,7 @@ class DatabaseValueConvertibleEncodableTests: GRDBTestCase {
|
||||
struct Value: Encodable, DatabaseValueConvertible {
|
||||
let dictionary: [String: Int]
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(dictionary)
|
||||
}
|
||||
@@ -184,7 +184,7 @@ class DatabaseValueConvertibleEncodableTests: GRDBTestCase {
|
||||
struct Value: Encodable, DatabaseValueConvertible {
|
||||
let strings: [String]
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(strings)
|
||||
}
|
||||
@@ -232,7 +232,7 @@ extension DatabaseValueConvertibleEncodableTests {
|
||||
struct Value : Encodable, DatabaseValueConvertible {
|
||||
let date: Date
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(date)
|
||||
}
|
||||
@@ -261,7 +261,7 @@ extension DatabaseValueConvertibleEncodableTests {
|
||||
struct Value : Encodable, DatabaseValueConvertible {
|
||||
let url: URL
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(url)
|
||||
}
|
||||
@@ -285,7 +285,7 @@ extension DatabaseValueConvertibleEncodableTests {
|
||||
struct Value : Encodable, DatabaseValueConvertible {
|
||||
let uuid: UUID
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(uuid)
|
||||
}
|
||||
|
||||
@@ -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? {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ extension FetchableRecordDecodableTests {
|
||||
case value = "someColumn"
|
||||
}
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
value = try container.decode(String.self, forKey: .value)
|
||||
}
|
||||
@@ -89,7 +89,7 @@ extension FetchableRecordDecodableTests {
|
||||
struct Value : Decodable {
|
||||
let string: String
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
string = try decoder.singleValueContainer().decode(String.self)
|
||||
}
|
||||
}
|
||||
@@ -125,7 +125,7 @@ extension FetchableRecordDecodableTests {
|
||||
struct NestedValue : Decodable {
|
||||
let string: String
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
string = try decoder.singleValueContainer().decode(String.self)
|
||||
}
|
||||
}
|
||||
@@ -133,7 +133,7 @@ extension FetchableRecordDecodableTests {
|
||||
struct Value : Decodable {
|
||||
let nestedValue: NestedValue
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
nestedValue = try decoder.singleValueContainer().decode(NestedValue.self)
|
||||
}
|
||||
}
|
||||
@@ -214,7 +214,7 @@ extension FetchableRecordDecodableTests {
|
||||
self.string = string
|
||||
}
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
string = try decoder.singleValueContainer().decode(String.self) + " (Decodable)"
|
||||
}
|
||||
|
||||
@@ -1084,7 +1084,7 @@ extension FetchableRecordDecodableTests {
|
||||
|
||||
enum CodingKeys: String, CodingKey { case name }
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
name = try container.decode(String.self, forKey: .name)
|
||||
key = decoder.codingPath.last?.stringValue
|
||||
@@ -1097,7 +1097,7 @@ extension FetchableRecordDecodableTests {
|
||||
var key: String?
|
||||
var context: String?
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
name = try container.decode(String.self)
|
||||
key = decoder.codingPath.last?.stringValue
|
||||
@@ -1110,7 +1110,7 @@ extension FetchableRecordDecodableTests {
|
||||
var key: String?
|
||||
var context: String?
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
var container = try decoder.unkeyedContainer()
|
||||
name = try container.decode(String.self)
|
||||
key = decoder.codingPath.last?.stringValue
|
||||
@@ -1129,7 +1129,7 @@ extension FetchableRecordDecodableTests {
|
||||
case nestedKeyed, nestedSingle, nestedUnkeyed
|
||||
}
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
nestedKeyed = try container.decode(NestedKeyed.self, forKey: .nestedKeyed)
|
||||
nestedSingle = try container.decode(NestedSingle.self, forKey: .nestedSingle)
|
||||
@@ -1150,7 +1150,7 @@ extension FetchableRecordDecodableTests {
|
||||
case nestedKeyed, nestedSingle, nestedUnkeyed
|
||||
}
|
||||
|
||||
required init(from decoder: Decoder) throws {
|
||||
required init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
nestedKeyed = try container.decode(NestedKeyed.self, forKey: .nestedKeyed)
|
||||
nestedSingle = try container.decode(NestedSingle.self, forKey: .nestedSingle)
|
||||
@@ -1448,7 +1448,7 @@ extension FetchableRecordDecodableTests {
|
||||
self.lastName = lastName
|
||||
}
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
let userInfoValue = decoder.userInfo[.testKey] as? String
|
||||
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -252,7 +252,7 @@ struct InflectionTestCases: Decodable {
|
||||
}
|
||||
}
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
init(from decoder: any Decoder) throws {
|
||||
var testCases: [String: [(String, String)]] = [:]
|
||||
let container = try decoder.container(keyedBy: AnyCodingKey.self)
|
||||
for key in container.allKeys {
|
||||
|
||||
@@ -38,7 +38,7 @@ extension MutablePersistableRecordEncodableTests {
|
||||
case value = "someColumn"
|
||||
}
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
try container.encode(value + " (Encodable)", forKey: .value)
|
||||
}
|
||||
@@ -129,7 +129,7 @@ extension MutablePersistableRecordEncodableTests {
|
||||
struct Value : Encodable {
|
||||
let string: String
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(string)
|
||||
}
|
||||
@@ -174,7 +174,7 @@ extension MutablePersistableRecordEncodableTests {
|
||||
struct NestedValue : Encodable {
|
||||
let string: String
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(string)
|
||||
}
|
||||
@@ -183,7 +183,7 @@ extension MutablePersistableRecordEncodableTests {
|
||||
struct Value : Encodable {
|
||||
let nestedValue: NestedValue
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(nestedValue)
|
||||
}
|
||||
@@ -281,7 +281,7 @@ extension MutablePersistableRecordEncodableTests {
|
||||
self.string = string
|
||||
}
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(string + " (Encodable)")
|
||||
}
|
||||
@@ -576,7 +576,7 @@ extension MutablePersistableRecordEncodableTests {
|
||||
|
||||
enum CodingKeys: String, CodingKey { case name, key, context }
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
try container.encode(name, forKey: .name)
|
||||
try container.encodeIfPresent(encoder.codingPath.last?.stringValue, forKey: .key)
|
||||
@@ -587,7 +587,7 @@ extension MutablePersistableRecordEncodableTests {
|
||||
struct NestedSingle: Encodable {
|
||||
var name: String
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
var value = name
|
||||
value += ",key:\(encoder.codingPath.last?.stringValue ?? "nil")"
|
||||
@@ -599,7 +599,7 @@ extension MutablePersistableRecordEncodableTests {
|
||||
struct NestedUnkeyed: Encodable {
|
||||
var name: String
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.unkeyedContainer()
|
||||
try container.encode(name)
|
||||
if let key = encoder.codingPath.last?.stringValue {
|
||||
@@ -630,7 +630,7 @@ extension MutablePersistableRecordEncodableTests {
|
||||
case nestedKeyed, nestedSingle, nestedUnkeyed, key, context
|
||||
}
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
try container.encode(nestedKeyed, forKey: .nestedKeyed)
|
||||
try container.encode(nestedSingle, forKey: .nestedSingle)
|
||||
@@ -668,7 +668,7 @@ extension MutablePersistableRecordEncodableTests {
|
||||
return encoder
|
||||
}
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
try container.encode(nestedKeyed, forKey: .nestedKeyed)
|
||||
try container.encode(nestedSingle, forKey: .nestedSingle)
|
||||
@@ -798,7 +798,7 @@ extension MutablePersistableRecordEncodableTests {
|
||||
self.lastName = lastName
|
||||
}
|
||||
|
||||
func encode(to encoder: Encoder) throws {
|
||||
func encode(to encoder: any Encoder) throws {
|
||||
let userInfoValue = encoder.userInfo[.testKey] as? String
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
|
||||
|
||||
@@ -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 { }
|
||||
|
||||
@@ -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)")
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 115 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user