diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift index 9caff8c4c..69cd51d96 100644 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift @@ -7,7 +7,7 @@ import GRDB /// struct AppDatabase { /// Creates an `AppDatabase`, and make sure the database schema is ready. - init(_ dbWriter: DatabaseWriter) throws { + init(_ dbWriter: any DatabaseWriter) throws { self.dbWriter = dbWriter try migrator.migrate(dbWriter) } @@ -18,7 +18,7 @@ struct AppDatabase { /// can use a fast in-memory `DatabaseQueue`. /// /// See - private let dbWriter: DatabaseWriter + private let dbWriter: any DatabaseWriter /// The DatabaseMigrator that defines the database schema. /// diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift index e536c8def..955febbcb 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift @@ -8,7 +8,7 @@ import GRDB /// struct AppDatabase { /// Creates an `AppDatabase`, and make sure the database schema is ready. - init(_ dbWriter: DatabaseWriter) throws { + init(_ dbWriter: any DatabaseWriter) throws { self.dbWriter = dbWriter try migrator.migrate(dbWriter) } @@ -19,7 +19,7 @@ struct AppDatabase { /// can use a fast in-memory `DatabaseQueue`. /// /// See - private let dbWriter: DatabaseWriter + private let dbWriter: any DatabaseWriter /// The DatabaseMigrator that defines the database schema. /// diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift index 3abba5a5a..db00ee36f 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift @@ -6,7 +6,7 @@ import GRDB /// final class AppDatabase { /// Creates an `AppDatabase`, and make sure the database schema is ready. - init(_ dbWriter: DatabaseWriter) throws { + init(_ dbWriter: any DatabaseWriter) throws { self.dbWriter = dbWriter try migrator.migrate(dbWriter) } @@ -17,7 +17,7 @@ final class AppDatabase { /// in-memory `DatabaseQueue`. /// /// See - private let dbWriter: DatabaseWriter + private let dbWriter: any DatabaseWriter /// The DatabaseMigrator that defines the database schema. /// diff --git a/Documentation/FTS5Tokenizers.md b/Documentation/FTS5Tokenizers.md index 1e321a2cc..29c9d7572 100644 --- a/Documentation/FTS5Tokenizers.md +++ b/Documentation/FTS5Tokenizers.md @@ -186,7 +186,7 @@ A FTS5WrapperTokenizer lets the hard tokenization job to another tokenizer, the ```swift protocol FTS5WrapperTokenizer : FTS5CustomTokenizer { - var wrappedTokenizer: FTS5Tokenizer { get } + var wrappedTokenizer: any FTS5Tokenizer { get } func accept( token: String, flags: FTS5TokenFlags, @@ -207,7 +207,7 @@ The `wrappedTokenizer` property is the mandatory wrapped tokenizer. You instanti ```swift final class MyTokenizer : FTS5WrapperTokenizer { - let wrappedTokenizer: FTS5Tokenizer + let wrappedTokenizer: any FTS5Tokenizer init(db: Database, arguments: [String]) throws { // Wrap the unicode61 tokenizer @@ -255,7 +255,7 @@ For example, your custom tokenizer can wrap [unicode61](https://www.sqlite.org/f ```swift final class MyTokenizer : FTS5WrapperTokenizer { static let name = "custom" - let wrappedTokenizer: FTS5Tokenizer + let wrappedTokenizer: any FTS5Tokenizer init(db: Database, arguments: [String]) throws { if arguments.isEmpty { @@ -309,7 +309,7 @@ We'll also take care of the SQLite advice: ```swift final class SynonymsTokenizer : FTS5WrapperTokenizer { static let name = "synonyms" - let wrappedTokenizer: FTS5Tokenizer + let wrappedTokenizer: any FTS5Tokenizer let synonyms: [Set] = [["first", "1st"]] init(db: Database, arguments: [String]) throws { @@ -361,7 +361,7 @@ The tokenizer wrapping is provided by the [FTS5WrapperTokenizer](#fts5wrappertok ```swift final class LatinAsciiTokenizer : FTS5WrapperTokenizer { static let name = "latinascii" - let wrappedTokenizer: FTS5Tokenizer + let wrappedTokenizer: any FTS5Tokenizer init(db: Database, arguments: [String]) throws { wrappedTokenizer = try db.makeTokenizer(.unicode61()) diff --git a/Documentation/SQLInterpolation.md b/Documentation/SQLInterpolation.md index ea7e1d6da..884c19788 100644 --- a/Documentation/SQLInterpolation.md +++ b/Documentation/SQLInterpolation.md @@ -389,7 +389,7 @@ This chapter lists all kinds of supported interpolations. struct AltPlayer: TableRecord { static let databaseTableName = "player" - static let databaseSelection: [SQLSelectable] = [Column("id"), Column("name")] + static let databaseSelection: [any SQLSelectable] = [Column("id"), Column("name")] } // SELECT player.id, player.name FROM player diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index 5aafa7af2..6b65a64ab 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -19,7 +19,7 @@ extension RangeReplaceableCollection { /// let strings = try Array(cursor) /// /// - parameter cursor: The cursor whose elements feed the collection. - public init(_ cursor: C) throws where C.Element == Element { + public init(_ cursor: some Cursor) throws { self.init() // Prefer `forEach` over `next()` looping, as a slight performance // improvement due to the single `sqlite3_stmt_busy` check for @@ -36,7 +36,7 @@ extension RangeReplaceableCollection { /// - parameter cursor: The cursor whose elements feed the collection. /// - parameter minimumCapacity: Prepares the returned collection to store /// the specified number of elements. - public init(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element { + public init(_ cursor: some Cursor, minimumCapacity: Int) throws { self.init() reserveCapacity(minimumCapacity) // Prefer `forEach` over `next()` looping, as a slight performance @@ -112,9 +112,7 @@ extension Dictionary { /// - parameter keysAndValues: A cursor of key-value pairs to use for the /// new dictionary. Every key in `keysAndValues` must be unique. /// - precondition: The cursor must not have duplicate keys. - public init(uniqueKeysWithValues keysAndValues: C) - throws where C.Element == (Key, Value) - { + public init(uniqueKeysWithValues keysAndValues: some Cursor<(Key, Value)>) throws { self.init() // Prefer `forEach` over `next()` looping, as a slight performance // improvement due to the single `sqlite3_stmt_busy` check for @@ -144,9 +142,7 @@ extension Dictionary { /// - parameter keysAndValues: A cursor of key-value pairs to use for the /// new dictionary. Every key in `keysAndValues` must be unique. /// - precondition: The cursor must not have duplicate keys. - public init(minimumCapacity: Int, uniqueKeysWithValues keysAndValues: C) - throws where C.Element == (Key, Value) - { + public init(minimumCapacity: Int, uniqueKeysWithValues keysAndValues: some Cursor<(Key, Value)>) throws { self.init(minimumCapacity: minimumCapacity) // Prefer `forEach` over `next()` looping, as a slight performance // improvement due to the single `sqlite3_stmt_busy` check for @@ -167,7 +163,7 @@ extension Set { /// let strings = try Set(cursor) /// /// - parameter cursor: A cursor of values to gather into a set. - public init(_ cursor: C) throws where C.Element == Element { + public init(_ cursor: some Cursor) throws { self.init() // Prefer `forEach` over `next()` looping, as a slight performance // improvement due to the single `sqlite3_stmt_busy` check for @@ -185,7 +181,7 @@ extension Set { /// - parameter minimumCapacity: The minimum number of elements that the /// newly created set should be able to store without reallocating its /// storage buffer. - public init(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element { + public init(_ cursor: some Cursor, minimumCapacity: Int) throws { self.init(minimumCapacity: minimumCapacity) // Prefer `forEach` over `next()` looping, as a slight performance // improvement due to the single `sqlite3_stmt_busy` check for @@ -685,14 +681,14 @@ public final class AnyCursor: Cursor { /// Creates a cursor that wraps a base iterator but whose type depends only /// on the base iterator’s element type - public convenience init(iterator: I) where I.Element == Element { + public convenience init(iterator: some IteratorProtocol) { var iterator = iterator self.init { iterator.next() } } /// Creates a cursor that wraps a base sequence but whose type depends only /// on the base sequence’s element type - public convenience init(_ s: S) where S.Element == Element { + public convenience init(_ s: some Sequence) { self.init(iterator: s.makeIterator()) } diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 2bcfb0a7e..9d7931178 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -363,11 +363,10 @@ extension Database { /// True if a sequence of columns uniquely identifies a row, that is to say /// if the columns are the primary key, or if there is a unique index on them. - public func table( + public func table( _ tableName: String, - hasUniqueKey columns: T) + hasUniqueKey columns: some Sequence) throws -> Bool - where T.Iterator.Element == String { try columnsForUniqueKey(Array(columns), in: tableName) != nil } @@ -611,11 +610,10 @@ extension Database { /// If there exists a unique key on columns, return the columns /// ordered as the matching index (or primary key). Case of returned columns /// is not guaranteed. - func columnsForUniqueKey( - _ columns: T, + func columnsForUniqueKey( + _ columns: some Sequence, in tableName: String) throws -> [String]? - where T.Iterator.Element == String { let lowercasedColumns = Set(columns.map { $0.lowercased() }) if lowercasedColumns.isEmpty { diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index d5b44d60a..4c0dd8fb8 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -43,7 +43,7 @@ public final class DatabaseFunction: Hashable { _ name: String, argumentCount: Int32? = nil, pure: Bool = false, - function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?) + function: @escaping ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?) { self.identity = Identity(name: name, nArg: argumentCount ?? -1) self.pure = pure @@ -68,7 +68,7 @@ public final class DatabaseFunction: Hashable { /// } /// } /// - /// func finalize() -> DatabaseValueConvertible? { + /// func finalize() -> (any DatabaseValueConvertible)? { /// return sum /// } /// } @@ -110,7 +110,7 @@ public final class DatabaseFunction: Hashable { /// Returns an SQL expression that applies the function. /// /// See - public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression { + public func callAsFunction(_ arguments: any SQLExpressible...) -> SQLExpression { switch kind { case .aggregate: return .function(name, arguments.map(\.sqlExpression)) @@ -166,8 +166,10 @@ public final class DatabaseFunction: Hashable { /// Feeds the `pApp` parameter of sqlite3_create_function_v2 /// private class FunctionDefinition { - let compute: (Int32, UnsafeMutablePointer?) throws -> DatabaseValueConvertible? - init(compute: @escaping (Int32, UnsafeMutablePointer?) throws -> DatabaseValueConvertible?) { + let compute: (Int32, UnsafeMutablePointer?) throws -> (any DatabaseValueConvertible)? + init(compute: @escaping (Int32, UnsafeMutablePointer?) + throws -> (any DatabaseValueConvertible)?) + { self.compute = compute } } @@ -176,17 +178,17 @@ public final class DatabaseFunction: Hashable { /// Feeds the `pApp` parameter of sqlite3_create_function_v2 /// private class AggregateDefinition { - let makeAggregate: () -> DatabaseAggregate - init(makeAggregate: @escaping () -> DatabaseAggregate) { + let makeAggregate: () -> any DatabaseAggregate + init(makeAggregate: @escaping () -> any DatabaseAggregate) { self.makeAggregate = makeAggregate } } /// The current state of an aggregate, storable in SQLite private class AggregateContext { - var aggregate: DatabaseAggregate + var aggregate: any DatabaseAggregate var hasErrored = false - init(aggregate: DatabaseAggregate) { + init(aggregate: some DatabaseAggregate) { self.aggregate = aggregate } } @@ -195,10 +197,10 @@ public final class DatabaseFunction: Hashable { /// See private enum Kind { /// A regular function: SELECT f(1) - case function((Int32, UnsafeMutablePointer?) throws -> DatabaseValueConvertible?) + case function((Int32, UnsafeMutablePointer?) throws -> (any DatabaseValueConvertible)?) /// An aggregate: SELECT f(foo) FROM bar GROUP BY baz - case aggregate(() -> DatabaseAggregate) + case aggregate(() -> any DatabaseAggregate) /// Feeds the `pApp` parameter of sqlite3_create_function_v2 /// @@ -314,7 +316,7 @@ public final class DatabaseFunction: Hashable { } } - private static func report(result: DatabaseValueConvertible?, in sqliteContext: OpaquePointer?) { + private static func report(result: (any DatabaseValueConvertible)?, in sqliteContext: OpaquePointer?) { switch result?.databaseValue.storage ?? .null { case .null: sqlite3_result_null(sqliteContext) @@ -369,7 +371,7 @@ extension DatabaseFunction { /// } /// } /// -/// func finalize() -> DatabaseValueConvertible? { +/// func finalize() -> (any DatabaseValueConvertible)? { /// return sum /// } /// } @@ -402,5 +404,5 @@ public protocol DatabaseAggregate { mutating func step(_ dbValues: [DatabaseValue]) throws /// Returns the final result - func finalize() throws -> DatabaseValueConvertible? + func finalize() throws -> (any DatabaseValueConvertible)? } diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 51fa71730..4b98d3fcb 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -730,7 +730,7 @@ extension DatabasePool: DatabaseReader { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> AnyDatabaseCancellable { if configuration.readonly { // The easy case: the database does not change @@ -761,7 +761,7 @@ extension DatabasePool: DatabaseReader { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> AnyDatabaseCancellable { assert(!configuration.readonly, "Use _addReadOnly(observation:) instead") assert(!observation.requiresWriteAccess, "Use _addWriteOnly(observation:) instead") diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index d9f1eaa7a..9e3156263 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -348,7 +348,7 @@ extension DatabaseQueue { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> AnyDatabaseCancellable { if configuration.readonly { // The easy case: the database does not change diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index b7abe63a1..719412ede 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -281,14 +281,14 @@ public protocol DatabaseReader: AnyObject, Sendable { /// method instead. /// /// - parameter observation: the stared observation - /// - returns: a TransactionObserver + /// - returns: a cancellable /// /// :nodoc: func _add( observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> AnyDatabaseCancellable } extension DatabaseReader { @@ -341,7 +341,7 @@ extension DatabaseReader { /// - throws: The error thrown by `progress` if the backup is abandoned, or /// any `DatabaseError` that would happen while performing the backup. public func backup( - to writer: DatabaseWriter, + to writer: some DatabaseWriter, pagesPerStep: Int32 = -1, progress: ((DatabaseBackupProgress) throws -> Void)? = nil) throws @@ -555,7 +555,7 @@ extension DatabaseReader { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> AnyDatabaseCancellable { if scheduler.immediateInitialValue() { do { @@ -599,10 +599,10 @@ extension DatabaseReader { /// Instances of AnyDatabaseReader forward their methods to an arbitrary /// underlying database reader. public final class AnyDatabaseReader: DatabaseReader { - private let base: DatabaseReader + private let base: any DatabaseReader /// Creates a database reader that wraps a base database reader. - public init(_ base: DatabaseReader) { + public init(_ base: some DatabaseReader) { self.base = base } @@ -651,7 +651,7 @@ public final class AnyDatabaseReader: DatabaseReader { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> AnyDatabaseCancellable { base._add( observation: observation, diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index bf1a51a7d..02027d078 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -369,8 +369,8 @@ public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible { _region = region } - public init(_ region: DatabaseRegionConvertible) { - _region = { try region.databaseRegion($0) } + public init(_ region: some DatabaseRegionConvertible) { + _region = region.databaseRegion } /// :nodoc: @@ -388,7 +388,7 @@ extension DatabaseRegion { } } - static func union(_ regions: [DatabaseRegionConvertible]) -> (Database) throws -> DatabaseRegion { + static func union(_ regions: [any DatabaseRegionConvertible]) -> (Database) throws -> DatabaseRegion { return { db in try regions.reduce(into: DatabaseRegion()) { union, region in try union.formUnion(region.databaseRegion(db)) diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index 2abf47706..2c30a578f 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -45,7 +45,7 @@ extension DatabaseRegionObservation { /// deallocated. See the `extent` property for more information. /// /// - parameter regions: A list of observed regions. - public init(tracking regions: DatabaseRegionConvertible...) { + public init(tracking regions: any DatabaseRegionConvertible...) { self.init(tracking: regions) } @@ -68,7 +68,7 @@ extension DatabaseRegionObservation { /// deallocated. See the `extent` property for more information. /// /// - parameter regions: A list of observed regions. - public init(tracking regions: [DatabaseRegionConvertible]) { + public init(tracking regions: [any DatabaseRegionConvertible]) { self.init( extent: .observerLifetime, observedRegion: DatabaseRegion.union(regions)) @@ -79,18 +79,18 @@ extension DatabaseRegionObservation { /// Starts the observation in the provided database writer (such as /// a database queue or database pool), and returns a transaction observer. /// - /// - parameter reader: A DatabaseWriter. + /// - parameter writer: A DatabaseWriter. /// - parameter onChange: A closure that is provided a database connection /// with write access each time the observed region has been modified. /// - returns: a TransactionObserver public func start( - in dbWriter: DatabaseWriter, + in writer: some DatabaseWriter, onChange: @escaping (Database) -> Void) - throws -> TransactionObserver + throws -> any TransactionObserver { // Use unsafeReentrantWrite so that observation can start from any // dispatch queue. - return try dbWriter.unsafeReentrantWrite { db -> TransactionObserver in + try writer.unsafeReentrantWrite { db in let region = try observedRegion(db).observableRegion(db) let observer = DatabaseRegionObserver(region: region, onChange: onChange) db.add(transactionObserver: observer, extent: extent) @@ -111,7 +111,7 @@ extension DatabaseRegionObservation { /// Error completion, if any, is only emitted, synchronously, /// on subscription. @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) - public func publisher(in writer: DatabaseWriter) -> DatabasePublishers.DatabaseRegion { + public func publisher(in writer: some DatabaseWriter) -> DatabasePublishers.DatabaseRegion { DatabasePublishers.DatabaseRegion(self, in: writer) } } @@ -160,10 +160,10 @@ extension DatabasePublishers { public typealias Output = Database public typealias Failure = Error - let writer: DatabaseWriter + let writer: any DatabaseWriter let observation: DatabaseRegionObservation - init(_ observation: DatabaseRegionObservation, in writer: DatabaseWriter) { + init(_ observation: DatabaseRegionObservation, in writer: some DatabaseWriter) { self.writer = writer self.observation = observation } @@ -183,13 +183,13 @@ extension DatabasePublishers { { private struct WaitingForDemand { let downstream: Downstream - let writer: DatabaseWriter + let writer: any DatabaseWriter let observation: DatabaseRegionObservation } private struct Observing { let downstream: Downstream - let writer: DatabaseWriter // Retain writer until subscription is finished + let writer: any DatabaseWriter // Retain writer until subscription is finished var remainingDemand: Subscribers.Demand } @@ -211,7 +211,7 @@ extension DatabasePublishers { private var lock = NSRecursiveLock() // Allow re-entrancy init( - writer: DatabaseWriter, + writer: some DatabaseWriter, observation: DatabaseRegionObservation, downstream: Downstream) { diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index e9d7a6ae4..c3ff65c43 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -89,7 +89,7 @@ extension DatabaseSnapshot { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> AnyDatabaseCancellable { _addReadOnly( observation: observation, diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index 022a9106d..e85f3013a 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -31,7 +31,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon case blob(Data) /// Returns Int64, Double, String, Data or nil. - public var value: DatabaseValueConvertible? { + public var value: (any DatabaseValueConvertible)? { switch self { case .null: return nil @@ -67,7 +67,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon /// /// The result is nil unless object adopts DatabaseValueConvertible. public init?(value: Any) { - guard let convertible = value as? DatabaseValueConvertible else { + guard let convertible = value as? any DatabaseValueConvertible else { return nil } self = convertible.databaseValue diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index ef1b454e6..ae15394cf 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -110,7 +110,7 @@ public final class DatabaseValueCursor: Databas public var _isDone = false private let columnIndex: Int32 - init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { + init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws { self.statement = statement if let adapter = adapter { // adapter may redefine the index of the leftmost column @@ -178,7 +178,7 @@ extension DatabaseValueConvertible { public static func fetchCursor( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> DatabaseValueCursor { try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) @@ -198,7 +198,7 @@ extension DatabaseValueConvertible { public static func fetchAll( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> [Self] { try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) @@ -221,7 +221,7 @@ extension DatabaseValueConvertible { public static func fetchOne( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Self? { // fetchOne returns nil if there is no row, or if there is a row with a null value @@ -245,7 +245,7 @@ extension DatabaseValueConvertible where Self: Hashable { public static func fetchSet( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Set { try Set(fetchCursor(statement, arguments: arguments, adapter: adapter)) @@ -279,7 +279,7 @@ extension DatabaseValueConvertible { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> DatabaseValueCursor { try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -300,7 +300,7 @@ extension DatabaseValueConvertible { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> [Self] { try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -324,7 +324,7 @@ extension DatabaseValueConvertible { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Self? { try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -347,7 +347,7 @@ extension DatabaseValueConvertible where Self: Hashable { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Set { try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -438,7 +438,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// A cursor over fetched values. /// - /// let request: ... // Some FetchRequest that fetches String + /// let request: some FetchRequest = ... /// let strings = try request.fetchCursor(db) // Cursor of String /// while let string = try strings.next() { // String /// ... @@ -458,7 +458,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// An array of fetched values. /// - /// let request: ... // Some FetchRequest that fetches String + /// let request: some FetchRequest = ... /// let strings = try request.fetchAll(db) // [String] /// /// - parameter db: A database connection. @@ -473,7 +473,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// The result is nil if the request returns no row, or if no value can be /// extracted from the first row. /// - /// let request: ... // Some FetchRequest that fetches String + /// let request: some FetchRequest = ... /// let string = try request.fetchOne(db) // String? /// /// - parameter db: A database connection. @@ -487,7 +487,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable { /// A set of fetched values. /// - /// let request: ... // Some FetchRequest that fetches String + /// let request: some FetchRequest = ... /// let strings = try request.fetchSet(db) // Set /// /// - parameter db: A database connection. diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index d471eb461..05661e450 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -288,13 +288,13 @@ extension DatabaseWriter { /// the observer lifetime (observation lasts until observer /// is deallocated). public func add( - transactionObserver: TransactionObserver, + transactionObserver: some TransactionObserver, extent: Database.TransactionObservationExtent = .observerLifetime) { writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) } } - public func remove(transactionObserver: TransactionObserver) { + public func remove(transactionObserver: some TransactionObserver) { writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) } } @@ -367,7 +367,7 @@ extension DatabaseWriter { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> AnyDatabaseCancellable { assert(!configuration.readonly, "Use _addReadOnly(observation:) instead") let observer = ValueWriteOnlyObserver( @@ -685,10 +685,10 @@ public class DatabaseFuture { /// Instances of AnyDatabaseWriter forward their methods to an arbitrary /// underlying database writer. public final class AnyDatabaseWriter: DatabaseWriter { - private let base: DatabaseWriter + private let base: any DatabaseWriter /// Creates a database writer that wraps a base database writer. - public init(_ base: DatabaseWriter) { + public init(_ base: some DatabaseWriter) { self.base = base } @@ -782,7 +782,7 @@ public final class AnyDatabaseWriter: DatabaseWriter { observation: ValueObservation, scheduling scheduler: ValueObservationScheduler, onChange: @escaping (Reducer.Value) -> Void) - -> DatabaseCancellable + -> AnyDatabaseCancellable { base._add( observation: observation, diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index c66ed2373..56804c8e8 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -4,7 +4,8 @@ /// rows should be interpreted. /// /// struct Player: FetchableRecord { ... } -/// let request: ... // Some FetchRequest that fetches Player +/// let request: some FetchRequest = ... +/// /// try request.fetchCursor(db) // Cursor of Player /// try request.fetchAll(db) // [Player] /// try request.fetchSet(db) // Set @@ -52,14 +53,14 @@ public struct PreparedRequest { public var statement: Statement /// An eventual adapter for rows fetched by the select statement - public var adapter: RowAdapter? + public var adapter: (any RowAdapter)? /// Support for eager loading of hasMany associations. var supplementaryFetch: ((Database, [Row]) throws -> Void)? init( statement: Statement, - adapter: RowAdapter?, + adapter: (any RowAdapter)?, supplementaryFetch: ((Database, [Row]) throws -> Void)? = nil) { self.statement = statement @@ -74,7 +75,7 @@ extension PreparedRequest: Refinable { } extension FetchRequest { /// Returns an adapted request. - public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest { + public func adapted(_ adapter: @escaping (Database) throws -> any RowAdapter) -> AdaptedFetchRequest { AdaptedFetchRequest(self, adapter) } } @@ -84,11 +85,11 @@ public struct AdaptedFetchRequest: FetchRequest { public typealias RowDecoder = Base.RowDecoder let base: Base - let adapter: (Database) throws -> RowAdapter + let adapter: (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 -> RowAdapter) { + init(_ base: Base, _ adapter: @escaping (Database) throws -> any RowAdapter) { self.base = base self.adapter = adapter } @@ -154,9 +155,7 @@ public struct AnyFetchRequest: FetchRequest { extension AnyFetchRequest { /// Creates a request that wraps and forwards operations to `request`. - public init(_ request: Request) - where Request.RowDecoder == RowDecoder - { + public init(_ request: some FetchRequest) { self.init(request: ConcreteFetchRequestEraser(request: request)) } } diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index c503cc39c..dfb738a66 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -7,7 +7,7 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, { // It is not a violation of the Demeter law when another type uses this // property, which is exposed for optimizations. - let impl: RowImpl + let impl: any RowImpl /// Unless we are producing a row array, we use a single row when iterating /// a statement: @@ -44,7 +44,7 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, } /// Creates a row from a dictionary of values. - public convenience init(_ dictionary: [String: DatabaseValueConvertible?]) { + public convenience init(_ dictionary: [String: (any DatabaseValueConvertible)?]) { self.init(impl: ArrayRowImpl(columns: dictionary.map { ($0, $1?.databaseValue ?? .null) })) } @@ -53,7 +53,7 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, /// The result is nil unless all dictionary keys are strings, and values /// adopt DatabaseValueConvertible. public convenience init?(_ dictionary: [AnyHashable: Any]) { - var initDictionary = [String: DatabaseValueConvertible?]() + var initDictionary = [String: (any DatabaseValueConvertible)?]() for (key, value) in dictionary { guard let columnName = key as? String else { return nil @@ -73,7 +73,7 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, /// let row: Row = ["foo": 1, "foo": "bar", "baz": nil] /// print(row) /// // Prints [foo:1 foo:"bar" baz:NULL] - public convenience init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...) { + public convenience init(dictionaryLiteral elements: (String, (any DatabaseValueConvertible)?)...) { self.init(impl: ArrayRowImpl(columns: elements.map { ($0, $1?.databaseValue ?? .null) })) } @@ -128,7 +128,7 @@ public final class Row: Equatable, Hashable, RandomAccessCollection, columnNames: statement.columnNames)) } - init(impl: RowImpl) { + init(impl: any RowImpl) { self.statement = nil self.sqliteStatement = nil self.impl = impl @@ -213,7 +213,7 @@ extension Row { /// /// Indexes span from 0 for the leftmost column to (row.count - 1) for the /// righmost column. - public subscript(_ index: Int) -> DatabaseValueConvertible? { + public subscript(_ index: Int) -> (any DatabaseValueConvertible)? { _checkIndex(index) return impl.databaseValue(atUncheckedIndex: index).storage.value } @@ -274,7 +274,7 @@ extension Row { /// the same name, the leftmost column is considered. /// /// The result is nil if the row does not contain the column. - public subscript(_ columnName: String) -> DatabaseValueConvertible? { + public subscript(_ columnName: String) -> (any DatabaseValueConvertible)? { // IMPLEMENTATION NOTE // This method has a single known use case: checking if the value is nil, // as in: @@ -353,7 +353,7 @@ extension Row { /// the same name, the leftmost column is considered. /// /// The result is nil if the row does not contain the column. - public subscript(_ column: Column) -> DatabaseValueConvertible? { + public subscript(_ column: some ColumnExpression) -> (any DatabaseValueConvertible)? { self[column.name] } @@ -380,7 +380,7 @@ extension Row { /// let row = try Row.fetchOne(db, sql: "SELECT ...")! /// let name: String? = row[Column("missing")] // nil @inlinable - public subscript(_ column: Column) -> Value { + public subscript(_ column: some ColumnExpression) -> Value { try! decode(Value.self, forKey: column.name) } @@ -411,11 +411,9 @@ extension Row { /// let row = try Row.fetchOne(db, sql: "SELECT ...")! /// let name: String? = row[Column("missing")] // nil @inlinable - public subscript(_ column: Column) + public subscript(_ column: some ColumnExpression) -> Value - where - Value: DatabaseValueConvertible & StatementColumnConvertible, - Column: ColumnExpression + where Value: DatabaseValueConvertible & StatementColumnConvertible { try! decode(Value.self, forKey: column.name) } @@ -460,7 +458,7 @@ extension Row { /// /// The returned data does not owns its bytes: it must not be used longer /// than the row's lifetime. - public func dataNoCopy(_ column: Column) -> Data? { + public func dataNoCopy(_ column: some ColumnExpression) -> Data? { try! decodeDataNoCopyIfPresent(forKey: column.name) } } @@ -1094,7 +1092,7 @@ public final class RowCursor: DatabaseCursor { public var _isDone = false @usableFromInline let _row: Row // Reused for performance - init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { + init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws { self.statement = statement self._row = try Row(statement: statement).adapted(with: adapter, layout: statement) @@ -1149,7 +1147,7 @@ extension Row { public static func fetchCursor( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> RowCursor { try RowCursor(statement: statement, arguments: arguments, adapter: adapter) @@ -1169,7 +1167,7 @@ extension Row { public static func fetchAll( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> [Row] { // The cursor reuses a single mutable row. Return immutable copies. @@ -1190,7 +1188,7 @@ extension Row { public static func fetchSet( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Set { // The cursor reuses a single mutable row. Return immutable copies. @@ -1211,7 +1209,7 @@ extension Row { public static func fetchOne( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Row? { let cursor = try fetchCursor(statement, arguments: arguments, adapter: adapter) @@ -1258,7 +1256,7 @@ extension Row { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> RowCursor { try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -1283,7 +1281,7 @@ extension Row { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> [Row] { try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -1308,7 +1306,7 @@ extension Row { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Set { try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -1333,7 +1331,7 @@ extension Row { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Row? { try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -1441,7 +1439,7 @@ extension FetchRequest where RowDecoder == Row { /// A cursor over fetched rows. /// - /// let request: ... // Some FetchRequest that fetches Row + /// let request: some FetchRequest = ... /// let rows = try request.fetchCursor(db) // RowCursor /// while let row = try rows.next() { // Row /// let id: Int64 = row[0] @@ -1470,7 +1468,7 @@ extension FetchRequest where RowDecoder == Row { /// An array of fetched rows. /// - /// let request: ... // Some FetchRequest that fetches Row + /// let request: some FetchRequest = ... /// let rows = try request.fetchAll(db) /// /// - parameter db: A database connection. @@ -1482,7 +1480,7 @@ extension FetchRequest where RowDecoder == Row { /// A set of fetched rows. /// - /// let request: ... // Some FetchRequest that fetches Row + /// let request: some FetchRequest = ... /// let rows = try request.fetchSet(db) /// /// - parameter db: A database connection. @@ -1494,7 +1492,7 @@ extension FetchRequest where RowDecoder == Row { /// The first fetched row. /// - /// let request: ... // Some FetchRequest that fetches Row + /// let request: some FetchRequest = ... /// let row = try request.fetchOne(db) /// /// - parameter db: A database connection. @@ -1698,13 +1696,13 @@ extension Row { /// row.scopes["bar"] // [bar:2] /// row.scopes["baz"] // nil public struct ScopesView: Collection { - public typealias Index = Dictionary.Index + public typealias Index = Dictionary.Index private let row: Row - private let scopes: [String: _LayoutedRowAdapter] + private let scopes: [String: any _LayoutedRowAdapter] private let prefetchedRows: Row.PrefetchedRowsView /// The scopes defined on this row. - public var names: Dictionary.Keys { + public var names: Dictionary.Keys { scopes.keys } @@ -1712,7 +1710,7 @@ extension Row { self.init(row: Row(), scopes: [:], prefetchedRows: Row.PrefetchedRowsView()) } - init(row: Row, scopes: [String: _LayoutedRowAdapter], prefetchedRows: Row.PrefetchedRowsView) { + init(row: Row, scopes: [String: any _LayoutedRowAdapter], prefetchedRows: Row.PrefetchedRowsView) { self.row = row self.scopes = scopes self.prefetchedRows = prefetchedRows @@ -2026,9 +2024,7 @@ extension RowImpl { struct ArrayRowImpl: RowImpl { let columns: [(String, DatabaseValue)] - init(columns: C) - where C: Collection, C.Element == (String, DatabaseValue) - { + init(columns: some Collection<(String, DatabaseValue)>) { self.columns = Array(columns) } diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index 46274d132..978e44ede 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -18,7 +18,7 @@ import Foundation /// row.scopes["b"] // [2, 3, 4] /// row.scopes["c"] // [5, 6] /// row.scopes["d"] // [7, 8] -public func splittingRowAdapters(columnCounts: [Int]) -> [RowAdapter] { +public func splittingRowAdapters(columnCounts: [Int]) -> [any RowAdapter] { guard !columnCounts.isEmpty else { // Identity adapter return [SuffixRowAdapter(fromIndex: 0)] @@ -66,14 +66,14 @@ public struct _LayoutedColumnMapping { /// Use it in your custom RowAdapter type: /// /// struct FooBarAdapter : RowAdapter { - /// func layoutAdapter(layout: _RowLayout) throws -> _LayoutedRowAdapter { + /// func layoutAdapter(layout: _RowLayout) throws -> any _LayoutedRowAdapter { /// return _LayoutedColumnMapping(layoutColumns: [(1, "foo"), (2, "bar")]) /// } /// } /// /// // [foo:"foo" bar: "bar"] /// try Row.fetchOne(db, sql: "SELECT NULL, 'foo', 'bar'", adapter: FooBarAdapter()) - init(layoutColumns: S) where S.Iterator.Element == (Int, String) { + init(layoutColumns: some Sequence<(Int, String)>) { self._layoutColumns = Array(layoutColumns) self.lowercaseColumnIndexes = Dictionary( layoutColumns @@ -97,7 +97,7 @@ extension _LayoutedColumnMapping: _LayoutedRowAdapter { public var _mapping: _LayoutedColumnMapping { self } /// Returns the empty dictionary. - public var _scopes: [String: _LayoutedRowAdapter] { [:] } + public var _scopes: [String: any _LayoutedRowAdapter] { [:] } } /// :nodoc: @@ -124,7 +124,7 @@ public protocol _LayoutedRowAdapter { var _mapping: _LayoutedColumnMapping { get } /// The layouted row adapters for each scope. - var _scopes: [String: _LayoutedRowAdapter] { get } + var _scopes: [String: any _LayoutedRowAdapter] { get } } /// `_RowLayout` is a protocol that supports the `RowAdapter` protocol. It @@ -169,14 +169,14 @@ public protocol _RowAdapter { /// // column named "foo" whose value is the leftmost value of the /// // base row. /// struct FirstColumnAdapter : RowAdapter { - /// func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter { + /// func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { /// return _LayoutedColumnMapping(layoutColumns: [(0, "foo")]) /// } /// } /// /// // [foo:1] /// try Row.fetchOne(db, sql: "SELECT 1, 2, 3", adapter: FirstColumnAdapter()) - func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter + func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter } /// `RowAdapter` is a protocol that helps two incompatible row interfaces @@ -208,7 +208,7 @@ extension RowAdapter { /// /// - parameter scopes: A dictionary that maps scope names to /// row adapters. - public func addingScopes(_ scopes: [String: RowAdapter]) -> RowAdapter { + public func addingScopes(_ scopes: [String: any RowAdapter]) -> any RowAdapter { if scopes.isEmpty { return self } else { @@ -218,7 +218,7 @@ extension RowAdapter { } extension RowAdapter { - func baseColumnIndex(atIndex index: Int, layout: _RowLayout) throws -> Int { + func baseColumnIndex(atIndex index: Int, layout: some _RowLayout) throws -> Int { try _layoutedAdapter(from: layout)._mapping.baseColumnIndex(atMappingIndex: index) } } @@ -229,7 +229,7 @@ public struct EmptyRowAdapter: RowAdapter { public init() { } /// :nodoc: - public func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter { + public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { _LayoutedColumnMapping(layoutColumns: []) } } @@ -252,7 +252,7 @@ public struct ColumnMapping: RowAdapter { } /// :nodoc: - public func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter { + public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { let layoutColumns = try mapping .map { (mappedColumn, baseColumn) -> (Int, String) in guard let index = layout._layoutIndex(ofColumn: baseColumn) else { @@ -293,7 +293,7 @@ public struct SuffixRowAdapter: RowAdapter { } /// :nodoc: - public func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter { + public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { _LayoutedColumnMapping(layoutColumns: layout._layoutColumns.suffix(from: index)) } } @@ -322,7 +322,7 @@ public struct RangeRowAdapter: RowAdapter { } /// :nodoc: - public func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter { + public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { _LayoutedColumnMapping(layoutColumns: layout._layoutColumns[range]) } } @@ -352,10 +352,10 @@ public struct RangeRowAdapter: RowAdapter { public struct ScopeAdapter: RowAdapter { /// The base adapter - let base: RowAdapter + let base: any RowAdapter /// The scope adapters - let scopes: [String: RowAdapter] + let scopes: [String: any RowAdapter] /// Creates an adapter that preserves row contents and add scoped rows. /// @@ -392,13 +392,13 @@ public struct ScopeAdapter: RowAdapter { /// row adapters. /// - parameter scopes: A dictionary that maps scope names to /// row adapters. - public init(base: RowAdapter, scopes: [String: RowAdapter]) { + public init(base: some RowAdapter, scopes: [String: any RowAdapter]) { self.base = base self.scopes = scopes } /// :nodoc: - public func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter { + public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { let layoutedAdapter = try base._layoutedAdapter(from: layout) var layoutedScopes = layoutedAdapter._scopes for (name, adapter) in scopes { @@ -413,14 +413,14 @@ public struct ScopeAdapter: RowAdapter { /// The `_LayoutedRowAdapter` for `ScopeAdapter` struct LayoutedScopeAdapter: _LayoutedRowAdapter { let _mapping: _LayoutedColumnMapping - let _scopes: [String: _LayoutedRowAdapter] + let _scopes: [String: any _LayoutedRowAdapter] } struct ChainedAdapter: RowAdapter { - let first: RowAdapter - let second: RowAdapter + let first: any RowAdapter + let second: any RowAdapter - func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter { + func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { try second._layoutedAdapter(from: first._layoutedAdapter(from: layout)._mapping) } } @@ -444,7 +444,7 @@ public struct RenameColumnAdapter: RowAdapter { } /// :nodoc: - public func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter { + public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter { let layoutColumns = layout._layoutColumns.map { (index, column) in (index, transform(column)) } return _LayoutedColumnMapping(layoutColumns: layoutColumns) } @@ -452,12 +452,12 @@ public struct RenameColumnAdapter: RowAdapter { extension Row { /// Creates a row from a base row and a statement adapter - convenience init(base: Row, adapter: _LayoutedRowAdapter) { + convenience init(base: Row, adapter: some _LayoutedRowAdapter) { self.init(impl: AdaptedRowImpl(base: base, adapter: adapter)) } /// Returns self if adapter is nil - func adapted(with adapter: RowAdapter?, layout: _RowLayout) throws -> Row { + func adapted(with adapter: (any RowAdapter)?, layout: some _RowLayout) throws -> Row { guard let adapter else { return self } @@ -467,10 +467,10 @@ extension Row { struct AdaptedRowImpl: RowImpl { let base: Row - let adapter: _LayoutedRowAdapter + let adapter: any _LayoutedRowAdapter let mapping: _LayoutedColumnMapping - init(base: Row, adapter: _LayoutedRowAdapter) { + init(base: Row, adapter: some _LayoutedRowAdapter) { self.base = base self.adapter = adapter self.mapping = adapter._mapping diff --git a/GRDB/Core/SQL.swift b/GRDB/Core/SQL.swift index 19891d08b..3f9ae00d9 100644 --- a/GRDB/Core/SQL.swift +++ b/GRDB/Core/SQL.swift @@ -96,7 +96,7 @@ public struct SQL { /// let emailLiteral = [columnLiteral, suffixLiteral].joined(separator: " || ") /// let request = User.select(emailLiteral.sqlExpression) /// let emails = try String.fetchAll(db, request) - public init(_ expression: SQLSpecificExpressible) { + public init(_ expression: some SQLSpecificExpressible) { self.init(elements: [.expression(expression.sqlExpression)]) } @@ -172,7 +172,7 @@ extension SQL: SQLSpecificExpressible { /// Use this property when you need an explicit `SQLExpression`. /// For example: /// - /// func date(_ value: SQLExpressible) -> SQLExpression { + /// func date(_ value: some SQLExpressible) -> SQLExpression { /// SQL("DATE(\(value))").sqlExpression /// } /// diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index 04bca77e7..ae6bf582a 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -13,14 +13,14 @@ public struct SQLRequest { } /// The request adapter - public var adapter: RowAdapter? + public var adapter: (any RowAdapter)? private(set) var sqlLiteral: SQL let cache: Cache? private init( literal sqlLiteral: SQL, - adapter: RowAdapter?, + adapter: (any RowAdapter)?, fromCache cache: Cache?, type: RowDecoder.Type) { @@ -51,7 +51,7 @@ extension SQLRequest { public init( sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil, + adapter: (any RowAdapter)? = nil, cached: Bool = false) { self.init( @@ -77,7 +77,7 @@ extension SQLRequest { /// - cached: Defaults to false. If true, the request reuses a cached /// prepared statement. /// - returns: A SQLRequest - public init(literal sqlLiteral: SQL, adapter: RowAdapter? = nil, cached: Bool = false) { + public init(literal sqlLiteral: SQL, adapter: (any RowAdapter)? = nil, cached: Bool = false) { self.init( literal: sqlLiteral, adapter: adapter, @@ -104,7 +104,7 @@ extension SQLRequest where RowDecoder == Row { public init( sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil, + adapter: (any RowAdapter)? = nil, cached: Bool = false) { self.init( @@ -130,7 +130,7 @@ extension SQLRequest where RowDecoder == Row { /// - cached: Defaults to false. If true, the request reuses a cached /// prepared statement. /// - returns: A SQLRequest - public init(literal sqlLiteral: SQL, adapter: RowAdapter? = nil, cached: Bool = false) { + public init(literal sqlLiteral: SQL, adapter: (any RowAdapter)? = nil, cached: Bool = false) { self.init( literal: sqlLiteral, adapter: adapter, diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 49984acb7..d37880152 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -250,7 +250,7 @@ public final class Statement { } // 1-based index - func bind(_ value: T, at index: CInt) { + func bind(_ value: some StatementBinding, at index: CInt) { let code = value.bind(to: sqliteStatement, at: index) // It looks like sqlite3_bind_xxx() functions do not access the file system. @@ -601,12 +601,12 @@ public struct StatementArguments: CustomStringConvertible, Equatable, /// Creates statement arguments from a sequence of optional values. /// - /// let values: [DatabaseValueConvertible?] = ["foo", 1, nil] + /// let values: [(any DatabaseValueConvertible)?] = ["foo", 1, nil] /// db.execute(sql: "INSERT ... (?,?,?)", arguments: StatementArguments(values)) /// /// - parameter sequence: A sequence of DatabaseValueConvertible values. /// - returns: A StatementArguments. - public init(_ sequence: Sequence) where Sequence.Element == DatabaseValueConvertible? { + public init(_ sequence: some Sequence<(any DatabaseValueConvertible)?>) { values = sequence.map { $0?.databaseValue ?? .null } namedValues = .init() } @@ -618,7 +618,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, /// /// - parameter sequence: A sequence of DatabaseValueConvertible values. /// - returns: A StatementArguments. - public init(_ sequence: Sequence) where Sequence.Element: DatabaseValueConvertible { + public init(_ sequence: some Sequence) { values = sequence.map(\.databaseValue) namedValues = .init() } @@ -649,12 +649,12 @@ public struct StatementArguments: CustomStringConvertible, Equatable, /// Creates statement arguments from a sequence of (key, value) dictionary, /// such as a dictionary. /// - /// let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"] + /// let values: [String: (any DatabaseValueConvertible)?] = ["firstName": nil, "lastName": "Miller"] /// db.execute(sql: "INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values)) /// /// - parameter sequence: A sequence of (key, value) pairs /// - returns: A StatementArguments. - public init(_ dictionary: [String: DatabaseValueConvertible?]) { + public init(_ dictionary: [String: (any DatabaseValueConvertible)?]) { namedValues = dictionary.mapValues { $0?.databaseValue ?? .null } values = .init() } @@ -662,14 +662,12 @@ public struct StatementArguments: CustomStringConvertible, Equatable, /// Creates statement arguments from a sequence of (key, value) pairs, such /// as a dictionary. /// - /// let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"] + /// let values: [String: (any DatabaseValueConvertible)?] = ["firstName": nil, "lastName": "Miller"] /// db.execute(sql: "INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values)) /// /// - parameter sequence: A sequence of (key, value) pairs /// - returns: A StatementArguments. - public init(_ sequence: Sequence) - where Sequence: Swift.Sequence, Sequence.Element == (String, DatabaseValueConvertible?) - { + public init(_ sequence: some Sequence<(String, (any DatabaseValueConvertible)?)>) { namedValues = .init(minimumCapacity: sequence.underestimatedCount) for (key, value) in sequence { namedValues[key] = value?.databaseValue ?? .null @@ -685,7 +683,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, /// - parameter dictionary: A dictionary. /// - returns: A StatementArguments. public init?(_ dictionary: [AnyHashable: Any]) { - var initDictionary = [String: DatabaseValueConvertible?]() + var initDictionary = [String: (any DatabaseValueConvertible)?]() for (key, value) in dictionary { guard let columnName = key as? String else { return nil @@ -904,7 +902,7 @@ extension StatementArguments { /// try db.execute( /// sql: "INSERT INTO player (name, score) VALUES (?, ?)" /// arguments: arguments) - public init(arrayLiteral elements: DatabaseValueConvertible?...) { + public init(arrayLiteral elements: (any DatabaseValueConvertible)?...) { self.init(elements) } } @@ -917,7 +915,7 @@ extension StatementArguments { /// try db.execute( /// sql: "INSERT INTO player (name, score) VALUES (:name, :score)" /// arguments: arguments) - public init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...) { + public init(dictionaryLiteral elements: (String, (any DatabaseValueConvertible)?)...) { self.init(elements) } } diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 17be96725..7a2d458b7 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -149,7 +149,7 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible public var _isDone = false @usableFromInline let columnIndex: Int32 - init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { + init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws { self.statement = statement if let adapter = adapter { // adapter may redefine the index of the leftmost column @@ -210,7 +210,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { public static func fetchCursor( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> FastDatabaseValueCursor { try FastDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter) @@ -230,7 +230,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { public static func fetchAll( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> [Self] { try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) @@ -250,7 +250,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { public static func fetchOne( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Self? { // fetchOne handles both a missing row, and one row with a NULL value. @@ -277,7 +277,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash public static func fetchSet( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Set { try Set(fetchCursor(statement, arguments: arguments, adapter: adapter)) @@ -311,7 +311,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> FastDatabaseValueCursor { try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -332,7 +332,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> [Self] { try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -353,7 +353,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Self? { try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -376,7 +376,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Set { try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -466,7 +466,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// A cursor over fetched values. /// - /// let request: ... // Some FetchRequest that fetches String + /// let request: some FetchRequest = ... /// let strings = try request.fetchCursor(db) // Cursor of String /// while let string = try strings.next() { // String /// ... @@ -486,7 +486,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// An array of fetched values. /// - /// let request: ... // Some FetchRequest that fetches String + /// let request: some FetchRequest = ... /// let strings = try request.fetchAll(db) // [String] /// /// - parameter db: A database connection. @@ -501,7 +501,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// The result is nil if the request returns no row, or if no value can be /// extracted from the first row. /// - /// let request: ... // Some FetchRequest that fetches String + /// let request: some FetchRequest = ... /// let string = try request.fetchOne(db) // String? /// /// - parameter db: A database connection. @@ -515,7 +515,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible & Hashable { /// A set of fetched values. /// - /// let request: ... // Some FetchRequest that fetches String + /// let request: some FetchRequest = ... /// let strings = try request.fetchSet(db) // Set /// /// - parameter db: A database connection. diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift index b65e64a34..0ac8736c6 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Decodable.swift @@ -2,7 +2,7 @@ import Foundation private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer { let dbValue: DatabaseValue - let codingPath: [CodingKey] + let codingPath: [any CodingKey] /// Decodes a null value. /// @@ -153,7 +153,7 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer { private struct DatabaseValueDecoder: Decoder { let dbValue: DatabaseValue - let codingPath: [CodingKey] + let codingPath: [any CodingKey] var userInfo: [CodingUserInfoKey: Any] { [:] } func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer { diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift index e87d799bf..f9f7127d8 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift @@ -3,7 +3,7 @@ import Foundation private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer { let encode: (DatabaseValue) -> Void - var codingPath: [CodingKey] { [] } + var codingPath: [any CodingKey] { [] } /// Encodes a null value. /// @@ -37,7 +37,7 @@ private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer { /// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format. /// - precondition: May not be called after a previous `self.encode(_:)` call. mutating func encode(_ value: T) throws where T: Encodable { - if let dbValueConvertible = value as? DatabaseValueConvertible { + if let dbValueConvertible = value as? any DatabaseValueConvertible { // Prefer DatabaseValueConvertible encoding over Decodable. // This allows us to encode Date as String, for example. encode(dbValueConvertible.databaseValue) @@ -57,7 +57,7 @@ private class DatabaseValueEncoder: Encoder { /// The path of coding keys taken to get to this point in encoding. /// A `nil` value indicates an unkeyed container. - var codingPath: [CodingKey] { [] } + var codingPath: [any CodingKey] { [] } /// Any contextual information set by the user for encoding. var userInfo: [CodingUserInfoKey: Any] = [:] diff --git a/GRDB/Core/Support/StandardLibrary/JSONRequiredEncoder.swift b/GRDB/Core/Support/StandardLibrary/JSONRequiredEncoder.swift index 8ab622a19..96e9d041f 100644 --- a/GRDB/Core/Support/StandardLibrary/JSONRequiredEncoder.swift +++ b/GRDB/Core/Support/StandardLibrary/JSONRequiredEncoder.swift @@ -2,7 +2,7 @@ struct JSONRequiredError: Error { } /// The encoder that always ends up with a JSONRequiredError struct JSONRequiredEncoder: Encoder { - var codingPath: [CodingKey] + var codingPath: [any CodingKey] var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { @@ -15,7 +15,7 @@ struct JSONRequiredEncoder: Encoder { func singleValueContainer() -> SingleValueEncodingContainer { self } struct KeyedContainer: KeyedEncodingContainerProtocol { - var codingPath: [CodingKey] + var codingPath: [any CodingKey] var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } // swiftlint:disable comma diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index be77b89db..4e61b3ede 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -10,7 +10,7 @@ extension Database { /// the observer lifetime (observation lasts until observer /// is deallocated). public func add( - transactionObserver: TransactionObserver, + transactionObserver: some TransactionObserver, extent: TransactionObservationExtent = .observerLifetime) { SchedulingWatchdog.preconditionValidQueue(self) @@ -24,7 +24,7 @@ extension Database { } /// Remove a transaction observer. - public func remove(transactionObserver: TransactionObserver) { + public func remove(transactionObserver: some TransactionObserver) { SchedulingWatchdog.preconditionValidQueue(self) // Drop cached statements that delete, because the removal of an @@ -193,15 +193,15 @@ class DatabaseObservationBroker { // MARK: - Transaction observers - func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent) { + func add(transactionObserver: some TransactionObserver, extent: Database.TransactionObservationExtent) { transactionObservations.append(TransactionObservation(observer: transactionObserver, extent: extent)) } - func remove(transactionObserver: TransactionObserver) { + func remove(transactionObserver: some TransactionObserver) { transactionObservations.removeFirst { $0.isWrapping(transactionObserver) } } - func disableUntilNextTransaction(transactionObserver: TransactionObserver) { + func disableUntilNextTransaction(transactionObserver: some TransactionObserver) { if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver) }) { observation.isDisabled = true statementObservations.removeFirst { $0.0 === observation } @@ -804,15 +804,15 @@ final class TransactionObservation { // It is still interested in transactions commits & rollbacks. var isDisabled = false - private weak var weakObserver: TransactionObserver? - private var strongObserver: TransactionObserver? - private var observer: TransactionObserver? { strongObserver ?? weakObserver } + private weak var weakObserver: (any TransactionObserver)? + private var strongObserver: (any TransactionObserver)? + private var observer: (any TransactionObserver)? { strongObserver ?? weakObserver } fileprivate var isObserving: Bool { observer != nil } - init(observer: TransactionObserver, extent: Database.TransactionObservationExtent) { + init(observer: some TransactionObserver, extent: Database.TransactionObservationExtent) { self.extent = extent switch extent { case .observerLifetime: @@ -825,7 +825,7 @@ final class TransactionObservation { } } - func isWrapping(_ observer: TransactionObserver) -> Bool { + func isWrapping(_ observer: some TransactionObserver) -> Bool { self.observer === observer } @@ -950,7 +950,7 @@ public struct DatabaseEvent { case update = 23 } - private let impl: DatabaseEventImpl + private let impl: any DatabaseEventImpl /// The event kind public let kind: Kind @@ -976,7 +976,7 @@ public struct DatabaseEvent { impl.copy(self) } - fileprivate init(kind: Kind, rowID: Int64, impl: DatabaseEventImpl) { + fileprivate init(kind: Kind, rowID: Int64, impl: any DatabaseEventImpl) { self.kind = kind self.rowID = rowID self.impl = impl @@ -1142,7 +1142,7 @@ public struct DatabasePreUpdateEvent { impl.copy(self) } - fileprivate init(kind: Kind, initialRowID: Int64?, finalRowID: Int64?, impl: DatabasePreUpdateEventImpl) { + fileprivate init(kind: Kind, initialRowID: Int64?, finalRowID: Int64?, impl: any DatabasePreUpdateEventImpl) { self.kind = kind self.initialRowID = (kind == .update || kind == .delete ) ? initialRowID : nil self.finalRowID = (kind == .update || kind == .insert ) ? finalRowID : nil @@ -1168,7 +1168,7 @@ public struct DatabasePreUpdateEvent { tableNameCString: tableNameCString)) } - private let impl: DatabasePreUpdateEventImpl + private let impl: any DatabasePreUpdateEventImpl } extension DatabasePreUpdateEvent: DatabaseEventProtocol { @@ -1336,7 +1336,7 @@ enum DatabaseEventPredicate { // Only events that match observedKinds case matching(observedKinds: [DatabaseEventKind], advertisedKinds: [DatabaseEventKind]) - func evaluate(_ event: DatabaseEventProtocol) -> Bool { + func evaluate(_ event: some DatabaseEventProtocol) -> Bool { switch self { case .true: return true @@ -1372,7 +1372,7 @@ enum DatabaseEventPredicate { /// rollbacked. class SavepointStack { /// The buffered events (see DatabaseObservationBroker.databaseDidChange(with:)) - var eventsBuffer: [(event: DatabaseEventProtocol, statementObservations: [StatementObservation])] = [] + var eventsBuffer: [(event: any DatabaseEventProtocol, statementObservations: [StatementObservation])] = [] /// The savepoint stack, as an array of tuples (savepointName, index in the eventsBuffer array). /// Indexes let us drop rollbacked events from the event buffer. diff --git a/GRDB/FTS/FTS5CustomTokenizer.swift b/GRDB/FTS/FTS5CustomTokenizer.swift index b52c541c6..9d3bb4500 100644 --- a/GRDB/FTS/FTS5CustomTokenizer.swift +++ b/GRDB/FTS/FTS5CustomTokenizer.swift @@ -139,7 +139,7 @@ extension Database { let object = Unmanaged .fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)) .takeUnretainedValue() - guard let tokenizer = object as? FTS5Tokenizer else { + guard let tokenizer = object as? any FTS5Tokenizer else { return SQLITE_ERROR } return tokenizer.tokenize( diff --git a/GRDB/FTS/FTS5Tokenizer.swift b/GRDB/FTS/FTS5Tokenizer.swift index ac93e776d..54ca29223 100644 --- a/GRDB/FTS/FTS5Tokenizer.swift +++ b/GRDB/FTS/FTS5Tokenizer.swift @@ -254,7 +254,7 @@ extension Database { /// wrappedTokenizer = try db.makeTokenizer(.unicode61()) /// } /// } - public func makeTokenizer(_ descriptor: FTS5TokenizerDescriptor) throws -> FTS5Tokenizer { + public func makeTokenizer(_ descriptor: FTS5TokenizerDescriptor) throws -> any FTS5Tokenizer { let api = FTS5.api(self) let xTokenizerPointer: UnsafeMutablePointer = .allocate(capacity: 1) diff --git a/GRDB/FTS/FTS5WrapperTokenizer.swift b/GRDB/FTS/FTS5WrapperTokenizer.swift index dfee9e0bd..ac2a46e39 100644 --- a/GRDB/FTS/FTS5WrapperTokenizer.swift +++ b/GRDB/FTS/FTS5WrapperTokenizer.swift @@ -50,7 +50,7 @@ public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5Token /// } public protocol FTS5WrapperTokenizer: FTS5CustomTokenizer { /// The wrapped tokenizer - var wrappedTokenizer: FTS5Tokenizer { get } + var wrappedTokenizer: any FTS5Tokenizer { get } /// Given a token produced by the wrapped tokenizer, notifies customized /// tokens to the `tokenCallback` function. @@ -92,7 +92,7 @@ public protocol FTS5WrapperTokenizer: FTS5CustomTokenizer { } private struct FTS5WrapperContext { - let tokenizer: FTS5WrapperTokenizer + let tokenizer: any FTS5WrapperTokenizer let context: UnsafeMutableRawPointer? let tokenization: FTS5Tokenization let tokenCallback: FTS5TokenCallback diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index b7546125f..a4c3be606 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -197,7 +197,7 @@ public struct DatabaseMigrator { /// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool) /// where migrations should apply. /// - throws: An eventual error thrown by the registered migration blocks. - public func migrate(_ writer: DatabaseWriter) throws { + public func migrate(_ writer: some DatabaseWriter) throws { guard let lastMigration = _migrations.last else { return } @@ -212,7 +212,7 @@ public struct DatabaseMigrator { /// where migrations should apply. /// - parameter targetIdentifier: The identifier of a registered migration. /// - throws: An eventual error thrown by the registered migration blocks. - public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws { + public func migrate(_ writer: some DatabaseWriter, upTo targetIdentifier: String) throws { try writer.barrierWriteWithoutTransaction { db in try migrate(db, upTo: targetIdentifier) } @@ -228,7 +228,7 @@ public struct DatabaseMigrator { /// argument is a `Result` that provides a connection to the migrated /// database, or the failure that would prevent the migration to complete. public func asyncMigrate( - _ writer: DatabaseWriter, + _ writer: some DatabaseWriter, completion: @escaping (Result) -> Void) { writer.asyncBarrierWriteWithoutTransaction { dbResult in @@ -456,7 +456,7 @@ extension DatabaseMigrator { /// - parameter writer: A DatabaseWriter (DatabaseQueue or DatabasePool) /// where migrations should apply. @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) - public func migratePublisher(_ writer: DatabaseWriter) -> DatabasePublishers.Migrate { + public func migratePublisher(_ writer: some DatabaseWriter) -> DatabasePublishers.Migrate { migratePublisher(writer, receiveOn: DispatchQueue.main) } @@ -472,9 +472,8 @@ extension DatabaseMigrator { /// where migrations should apply. /// - parameter scheduler: A Combine Scheduler. @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) - public func migratePublisher(_ writer: DatabaseWriter, receiveOn scheduler: S) + public func migratePublisher(_ writer: some DatabaseWriter, receiveOn scheduler: some Scheduler) -> DatabasePublishers.Migrate - where S: Scheduler { DatabasePublishers.Migrate( upstream: OnDemandFuture { promise in diff --git a/GRDB/QueryInterface/ForeignKey.swift b/GRDB/QueryInterface/ForeignKey.swift index a27a55d36..9a4e407a7 100644 --- a/GRDB/QueryInterface/ForeignKey.swift +++ b/GRDB/QueryInterface/ForeignKey.swift @@ -102,7 +102,7 @@ public struct ForeignKey: Equatable { /// - parameter destinationColumns: The columns at the destination of the /// foreign key. When nil (the default), GRDB automatically uses the /// primary key. - public init(_ originColumns: [ColumnExpression], to destinationColumns: [ColumnExpression]? = nil) { + public init(_ originColumns: [any ColumnExpression], to destinationColumns: [any ColumnExpression]? = nil) { self.init(originColumns.map(\.name), to: destinationColumns?.map(\.name)) } } diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index 7ec25bfa7..a78763445 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -145,7 +145,7 @@ extension Association { /// /// let playerInfos = PlayerInfo.all().fetchAll(db) /// print(playerInfos.first?.team) - public func forKey(_ codingKey: CodingKey) -> Self { + public func forKey(_ codingKey: some CodingKey) -> Self { forKey(codingKey.stringValue) } @@ -208,7 +208,7 @@ extension Association { /// .select { db in [Column("id")] } /// .select { db in [Column("color") } /// var request = Player.including(required: association) - public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { + public func select(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self { withDestinationRelation { relation in relation = relation.select { db in try selection(db).map(\.sqlSelection) @@ -229,7 +229,7 @@ extension Association { /// .select([Column("color")]) /// .annotated(with: { db in [Column("name")] }) /// var request = Player.including(required: association) - public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { + public func annotated(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self { withDestinationRelation { relation in relation = relation.annotated { db in try selection(db).map(\.sqlSelection) @@ -252,7 +252,7 @@ extension Association { /// // JOIN team ON team.id = player.teamId AND 1 /// let association = Player.team.filter { db in true } /// var request = Player.including(required: association) - public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { + public func filter(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self { withDestinationRelation { relation in relation = relation.filter { db in try predicate(db).sqlExpression @@ -287,7 +287,7 @@ extension Association { /// .reversed() /// .order{ _ in [Column("name")] } /// var request = Player.including(required: association) - public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self { + public func order(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self { withDestinationRelation { relation in relation = relation.order { db in try orderings(db).map(\.sqlOrdering) @@ -349,7 +349,7 @@ extension Association { // AggregatingRequest conformance extension Association { /// Creates an association grouped according to *expressions promise*. - public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self { + public func group(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self { withDestinationRelation { relation in relation = relation.group { db in try expressions(db).map(\.sqlExpression) @@ -359,7 +359,7 @@ extension Association { /// Creates an association with the provided *predicate promise* added to /// the eventual set of already applied predicates. - public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { + public func having(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self { withDestinationRelation { relation in relation = relation.having { db in try predicate(db).sqlExpression diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 135c0bc8f..966308a71 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -62,9 +62,9 @@ extension AssociationToMany { /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) /// /// let teams: [Team] = try Team.having(Team.players.average(Column("score")) > 100).fetchAll(db) - public func average(_ expression: SQLSpecificExpressible) -> AssociationAggregate { + public func average(_ expression: some SQLSpecificExpressible) -> AssociationAggregate { let aggregate = makeAggregate(.aggregate("AVG", [expression.sqlExpression])) - if let column = expression as? ColumnExpression { + if let column = expression as? any ColumnExpression { let name = key.singularizedName return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") } else { @@ -89,9 +89,9 @@ extension AssociationToMany { /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) /// /// let teams: [Team] = try Team.having(Team.players.max(Column("score")) < 100).fetchAll(db) - public func max(_ expression: SQLSpecificExpressible) -> AssociationAggregate { + public func max(_ expression: some SQLSpecificExpressible) -> AssociationAggregate { let aggregate = makeAggregate(.aggregate("MAX", [expression.sqlExpression])) - if let column = expression as? ColumnExpression { + if let column = expression as? any ColumnExpression { let name = key.singularizedName return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") } else { @@ -116,9 +116,9 @@ extension AssociationToMany { /// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request) /// /// let teams: [Team] = try Team.having(Team.players.min(Column("score")) > 100).fetchAll(db) - public func min(_ expression: SQLSpecificExpressible) -> AssociationAggregate { + public func min(_ expression: some SQLSpecificExpressible) -> AssociationAggregate { let aggregate = makeAggregate(.aggregate("MIN", [expression.sqlExpression])) - if let column = expression as? ColumnExpression { + if let column = expression as? any ColumnExpression { let name = key.singularizedName return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)") } else { @@ -146,9 +146,9 @@ extension AssociationToMany { /// /// This aggregate invokes the `SUM` SQL function. See also `total(_:)`, and /// . - public func sum(_ expression: SQLSpecificExpressible) -> AssociationAggregate { + public func sum(_ expression: some SQLSpecificExpressible) -> AssociationAggregate { let aggregate = makeAggregate(.aggregate("SUM", [expression.sqlExpression])) - if let column = expression as? ColumnExpression { + if let column = expression as? any ColumnExpression { let name = key.singularizedName return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum") } else { @@ -176,9 +176,9 @@ extension AssociationToMany { /// /// This aggregate invokes the `TOTAL` SQL function. See also `sum(_:)`, and /// . - public func total(_ expression: SQLSpecificExpressible) -> AssociationAggregate { + public func total(_ expression: some SQLSpecificExpressible) -> AssociationAggregate { let aggregate = makeAggregate(.aggregate("TOTAL", [expression.sqlExpression])) - if let column = expression as? ColumnExpression { + if let column = expression as? any ColumnExpression { let name = key.singularizedName // Yes we use the `Sum` suffix instead of `Total`. Both `total(_:)` // and `sum(_:)` compute sums. @@ -249,9 +249,7 @@ public struct AssociationAggregate { /// - We don't know yet if the aggregated expression will be used in the /// SQL selection, or in the HAVING clause. /// - It helps implementing aggregate operators such as `&&`, `+`, etc. - func prepare(_ request: inout Request) -> SQLExpression - where Request: DerivableRequest, Request.RowDecoder == RowDecoder - { + func prepare(_ request: inout some DerivableRequest) -> SQLExpression { preparation.prepare(&request) } } @@ -287,7 +285,7 @@ extension AssociationAggregate: Refinable { /// return try AuthorInfo.fetchAll(db, request) /// } /// } - public func forKey(_ key: CodingKey) -> Self { + public func forKey(_ key: some CodingKey) -> Self { forKey(key.stringValue) } } @@ -305,9 +303,7 @@ extension AssociationAggregate: Refinable { /// We could have used a generic closure instead of this class... if only Swift /// would support generic closures. private class AssociationAggregatePreparation { - func prepare(_ request: inout Request) -> SQLExpression - where Request: DerivableRequest, Request.RowDecoder == RowDecoder - { + func prepare(_ request: inout some DerivableRequest) -> SQLExpression { fatalError("subclass must override") } } @@ -324,9 +320,7 @@ private class BasePreparation: self.expression = expression } - override func prepare(_ request: inout Request) -> SQLExpression - where Request: DerivableRequest, Request.RowDecoder == Association.OriginRowDecoder - { + override func prepare(_ request: inout some DerivableRequest) -> SQLExpression { // The fundamental request that supports association aggregate: // // SELECT parent.* @@ -357,9 +351,7 @@ private class MapPreparation: AssociationAggregatePreparation(_ request: inout Request) -> SQLExpression - where Request: DerivableRequest, Request.RowDecoder == RowDecoder - { + override func prepare(_ request: inout some DerivableRequest) -> SQLExpression { transform(base.prepare(&request)) } } @@ -387,9 +379,7 @@ private class CombinePreparation: AssociationAggregatePreparation(_ request: inout Request) -> SQLExpression - where Request: DerivableRequest, Request.RowDecoder == RowDecoder - { + override func prepare(_ request: inout some DerivableRequest) -> SQLExpression { let lhsExpression = lhs.prepare(&request) let rhsExpression = rhs.prepare(&request) return combine(lhsExpression, rhsExpression) @@ -434,7 +424,7 @@ public func && ( /// :nodoc: public func && ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 && rhs } @@ -443,7 +433,7 @@ public func && ( // TODO: test /// :nodoc: public func && ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -468,7 +458,7 @@ public func || ( /// :nodoc: public func || ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 || rhs } @@ -477,7 +467,7 @@ public func || ( // TODO: test /// :nodoc: public func || ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -506,7 +496,7 @@ public func == ( /// Author.having(Author.books.count == 3) public func == ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 == rhs } @@ -518,7 +508,7 @@ public func == ( /// /// Author.having(3 == Author.books.count) public func == ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -563,7 +553,7 @@ public func != ( /// Author.having(Author.books.count != 3) public func != ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 != rhs } @@ -575,7 +565,7 @@ public func != ( /// /// Author.having(3 != Author.books.count) public func != ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -620,7 +610,7 @@ public func === ( /// Author.having(Author.books.count === 3) public func === ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 === rhs } @@ -632,7 +622,7 @@ public func === ( /// /// Author.having(3 === Author.books.count) public func === ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -659,7 +649,7 @@ public func !== ( /// Author.having(Author.books.count !== 3) public func !== ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 !== rhs } @@ -671,7 +661,7 @@ public func !== ( /// /// Author.having(3 !== Author.books.count) public func !== ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -700,7 +690,7 @@ public func <= ( /// Author.having(Author.books.count <= 3) public func <= ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 <= rhs } @@ -712,7 +702,7 @@ public func <= ( /// /// Author.having(3 <= Author.books.count) public func <= ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -739,7 +729,7 @@ public func < ( /// Author.having(Author.books.count < 3) public func < ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 < rhs } @@ -751,7 +741,7 @@ public func < ( /// /// Author.having(3 < Author.books.count) public func < ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -778,7 +768,7 @@ public func > ( /// Author.having(Author.books.count > 3) public func > ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 > rhs } @@ -790,7 +780,7 @@ public func > ( /// /// Author.having(3 > Author.books.count) public func > ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -817,7 +807,7 @@ public func >= ( /// Author.having(Author.books.count >= 3) public func >= ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 >= rhs } @@ -829,7 +819,7 @@ public func >= ( /// /// Author.having(3 >= Author.books.count) public func >= ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -867,7 +857,7 @@ public func + ( /// Author.annotated(with: Author.books.count + 1) public func + ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 + rhs } @@ -879,7 +869,7 @@ public func + ( /// /// Author.annotated(with: 1 + Author.books.count) public func + ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -906,7 +896,7 @@ public func - ( /// Author.annotated(with: Author.books.count - 1) public func - ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 - rhs } @@ -918,7 +908,7 @@ public func - ( /// /// Author.annotated(with: 1 - Author.books.count) public func - ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -945,7 +935,7 @@ public func * ( /// Author.annotated(with: Author.books.count * 2) public func * ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 * rhs } @@ -957,7 +947,7 @@ public func * ( /// /// Author.annotated(with: 2 * Author.books.count) public func * ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -984,7 +974,7 @@ public func / ( /// Author.annotated(with: Author.books.count / 2) public func / ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs.map { $0 / rhs } @@ -996,7 +986,7 @@ public func / ( /// /// Author.annotated(with: 2 / Author.books.count) public func / ( - lhs: SQLExpressible, + lhs: some SQLExpressible, rhs: AssociationAggregate) -> AssociationAggregate { @@ -1010,7 +1000,7 @@ public func / ( /// Team.annotated(with: Team.players.min(Column("score")) ?? 0) public func ?? ( lhs: AssociationAggregate, - rhs: SQLExpressible) + rhs: some SQLExpressible) -> AssociationAggregate { lhs diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index 293a7b9a0..b5e07e947 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -36,11 +36,11 @@ public struct CommonTableExpression { /// - parameter columns: The columns of the common table expression. If nil, /// the columns are the columns of the request. /// - parameter request: A request. - private init( + private init( recursive: Bool = false, named tableName: String, columns: [String]? = nil, - request: Request, + request: some SQLSubqueryable, type: RowDecoder.Type) { self.tableName = tableName @@ -72,11 +72,11 @@ extension CommonTableExpression { /// - parameter columns: The columns of the common table expression. If nil, /// the columns are the columns of the request. /// - parameter request: A request. - public init( + public init( recursive: Bool = false, named tableName: String, columns: [String]? = nil, - request: Request) + request: some SQLSubqueryable) { self.init( recursive: recursive, @@ -172,11 +172,11 @@ extension CommonTableExpression where RowDecoder == Row { /// - parameter columns: The columns of the common table expression. If nil, /// the columns are the columns of the request. /// - parameter request: A request. - public init( + public init( recursive: Bool = false, named tableName: String, columns: [String]? = nil, - request: Request) + request: some SQLSubqueryable) { self.init( recursive: recursive, @@ -296,7 +296,7 @@ extension CommonTableExpression { /// /// // name IN playerName /// playerNameCTE.contains(Column("name")) - public func contains(_ element: SQLExpressible) -> SQLExpression { + public func contains(_ element: some SQLExpressible) -> SQLExpression { SQLCollection.table(tableName).contains(element.sqlExpression) } } @@ -352,7 +352,7 @@ extension CommonTableExpression { /// - returns: An association to the common table expression. public func association( to cte: CommonTableExpression, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible) + on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( @@ -388,7 +388,7 @@ extension CommonTableExpression { /// - returns: An association to the common table expression. public func association( to destination: Destination.Type, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible) + on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) -> JoinAssociation where Destination: TableRecord { @@ -425,7 +425,7 @@ extension CommonTableExpression { /// - returns: An association to the common table expression. public func association( to destination: Table, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible) + on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index ca4f82b67..84a7b5caf 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -76,7 +76,7 @@ extension QueryInterfaceRequest: SelectionRequest { /// request /// .select { db in [Column("id")] } /// .select { db in [Column("email")] } - public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest { + public func select(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> QueryInterfaceRequest { with { $0.relation = $0.relation.select { db in try selection(db).map(\.sqlSelection) @@ -92,7 +92,7 @@ extension QueryInterfaceRequest: SelectionRequest { /// let request = Player.all().select([max(Column("score"))], as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public func select(_ selection: [SQLSelectable], as type: RowDecoder.Type = RowDecoder.self) + public func select(_ selection: [any SQLSelectable], as type: RowDecoder.Type = RowDecoder.self) -> QueryInterfaceRequest { select(selection).asRequest(of: RowDecoder.self) @@ -106,7 +106,7 @@ extension QueryInterfaceRequest: SelectionRequest { /// let request = Player.all().select(max(Column("score")), as: Int.self) /// let maxScore: Int? = try request.fetchOne(db) /// } - public func select(_ selection: SQLSelectable..., as type: RowDecoder.Type = RowDecoder.self) + public func select(_ selection: any SQLSelectable..., as type: RowDecoder.Type = RowDecoder.self) -> QueryInterfaceRequest { select(selection, as: type) @@ -156,7 +156,7 @@ extension QueryInterfaceRequest: SelectionRequest { /// request = request /// .select([Column("id"), Column("email")]) /// .annotated(with: { db in [Column("name")] }) - public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest { + public func annotated(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> QueryInterfaceRequest { with { $0.relation = $0.relation.annotated { db in try selection(db).map(\.sqlSelection) @@ -192,7 +192,7 @@ extension QueryInterfaceRequest: FilteredRequest { /// // SELECT * FROM player WHERE 1 /// var request = Player.all() /// request = request.filter { db in true } - public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { + public func filter(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> QueryInterfaceRequest { with { $0.relation = $0.relation.filter { db in try predicate(db).sqlExpression @@ -215,7 +215,7 @@ extension QueryInterfaceRequest: OrderedRequest { /// .order{ _ in [Column("email")] } /// .reversed() /// .order{ _ in [Column("name")] } - public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest { + public func order(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> QueryInterfaceRequest { with { $0.relation = $0.relation.order { db in try orderings(db).map(\.sqlOrdering) @@ -254,7 +254,7 @@ extension QueryInterfaceRequest: OrderedRequest { extension QueryInterfaceRequest: AggregatingRequest { /// Creates a request grouped according to *expressions promise*. - public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceRequest { + public func group(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> QueryInterfaceRequest { with { $0.relation = $0.relation.group { db in try expressions(db).map(\.sqlExpression) @@ -264,7 +264,7 @@ extension QueryInterfaceRequest: AggregatingRequest { /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. - public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { + public func having(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> QueryInterfaceRequest { with { $0.relation = $0.relation.having { db in try predicate(db).sqlExpression @@ -427,7 +427,7 @@ extension QueryInterfaceRequest { // runtime check for MutablePersistableRecord, and look for a // user-defined default. Such dynamic dispatch is unusual in GRDB, but // static dispatch is likely to create bad surprises in generic contexts. - if let recordType = RowDecoder.self as? MutablePersistableRecord.Type { + if let recordType = RowDecoder.self as? any MutablePersistableRecord.Type { return recordType.persistenceConflictPolicy.conflictResolutionForUpdate } else { return .abort @@ -507,11 +507,11 @@ extension QueryInterfaceRequest { /// try Player.updateAll(db, assignment) /// } public struct ColumnAssignment { - var column: ColumnExpression + var columnName: String var value: SQLExpression func sql(_ context: SQLGenerationContext) throws -> String { - try column.sqlExpression.sql(context) + " = " + value.sql(context) + try Column(columnName).sqlExpression.sql(context) + " = " + value.sql(context) } } @@ -527,8 +527,8 @@ extension ColumnExpression { /// // UPDATE player SET score = 0 /// try Player.updateAll(db, Column("score").set(to: 0)) /// } - public func set(to value: SQLExpressible?) -> ColumnAssignment { - ColumnAssignment(column: self, value: value?.sqlExpression ?? .null) + public func set(to value: (any SQLExpressible)?) -> ColumnAssignment { + ColumnAssignment(columnName: name, value: value?.sqlExpression ?? .null) } } @@ -541,7 +541,7 @@ extension ColumnExpression { /// // UPDATE player SET score = score + 1 /// try Player.updateAll(db, Column("score") += 1) /// } -public func += (column: ColumnExpression, value: SQLExpressible) -> ColumnAssignment { +public func += (column: some ColumnExpression, value: some SQLExpressible) -> ColumnAssignment { column.set(to: column + value) } @@ -554,7 +554,7 @@ public func += (column: ColumnExpression, value: SQLExpressible) -> ColumnAssign /// // UPDATE player SET score = score - 1 /// try Player.updateAll(db, Column("score") -= 1) /// } -public func -= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssignment { +public func -= (column: some ColumnExpression, value: some SQLExpressible) -> ColumnAssignment { column.set(to: column - value) } @@ -567,7 +567,7 @@ public func -= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssign /// // UPDATE player SET score = score * 2 /// try Player.updateAll(db, Column("score") *= 2) /// } -public func *= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssignment { +public func *= (column: some ColumnExpression, value: some SQLExpressible) -> ColumnAssignment { column.set(to: column * value) } @@ -580,7 +580,7 @@ public func *= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssign /// // UPDATE player SET score = score / 2 /// try Player.updateAll(db, Column("score") /= 2) /// } -public func /= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssignment { +public func /= (column: some ColumnExpression, value: some SQLExpressible) -> ColumnAssignment { column.set(to: column / value) } diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 524c198c2..0c4d8f61a 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -29,7 +29,7 @@ public protocol SelectionRequest { /// request /// .select { db in [Column("id")] } /// .select { db in [Column("email")] } - func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self + func select(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self /// Creates a request which appends *selection promise*. /// @@ -38,7 +38,7 @@ public protocol SelectionRequest { /// request = request /// .select([Column("id"), Column("email")]) /// .annotated(with: { db in [Column("name")] }) - func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self + func annotated(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self } extension SelectionRequest { @@ -54,7 +54,7 @@ extension SelectionRequest { /// request /// .select([Column("id")]) /// .select([Column("email")]) - public func select(_ selection: [SQLSelectable]) -> Self { + public func select(_ selection: [any SQLSelectable]) -> Self { select { _ in selection } } @@ -70,7 +70,7 @@ extension SelectionRequest { /// request /// .select(Column("id")) /// .select(Column("email")) - public func select(_ selection: SQLSelectable...) -> Self { + public func select(_ selection: any SQLSelectable...) -> Self { select(selection) } @@ -120,7 +120,7 @@ extension SelectionRequest { /// request = request /// .select([Column("id"), Column("email")]) /// .annotated(with: [Column("name")]) - public func annotated(with selection: [SQLSelectable]) -> Self { + public func annotated(with selection: [any SQLSelectable]) -> Self { annotated(with: { _ in selection }) } @@ -131,7 +131,7 @@ extension SelectionRequest { /// request = request /// .select([Column("id"), Column("email")]) /// .annotated(with: Column("name")) - public func annotated(with selection: SQLSelectable...) -> Self { + public func annotated(with selection: any SQLSelectable...) -> Self { annotated(with: selection) } } @@ -146,7 +146,7 @@ public protocol FilteredRequest { /// // SELECT * FROM player WHERE 1 /// var request = Player.all() /// request = request.filter { db in true } - func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self + func filter(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self } extension FilteredRequest { @@ -159,7 +159,7 @@ extension FilteredRequest { /// // SELECT * FROM player WHERE email = 'arthur@example.com' /// var request = Player.all() /// request = request.filter(Column("email") == "arthur@example.com") - public func filter(_ predicate: SQLSpecificExpressible) -> Self { + public func filter(_ predicate: some SQLSpecificExpressible) -> Self { filter { _ in predicate } } @@ -233,7 +233,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { /// let request = try Player...filter(key: 1) /// /// - parameter key: A primary key - public func filter(key: PrimaryKeyType) -> Self { + public func filter(key: some DatabaseValueConvertible) -> Self { if key.databaseValue.isNull { return none() } @@ -256,7 +256,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { // (customizing TableRequest where RowDecoder: EncodableRecord) would // make it impractical to define `filter(id:)`, `fetchOne(_:key:)`, // `deleteAll(_:ids:)` etc. - if let recordType = RowDecoder.self as? EncodableRecord.Type { + if let recordType = RowDecoder.self as? any EncodableRecord.Type { if Sequence.Element.self == Date.self || Sequence.Element.self == Optional.self { let strategy = recordType.databaseDateEncodingStrategy let keys = keys.compactMap { ($0 as! Date?).flatMap(strategy.encode)?.databaseValue } @@ -277,10 +277,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { /// let request = try Player...filter(encodedKeys: [1, 2, 3]) /// /// - parameter keys: A collection of primary keys - func filter(rawKeys: Sequence) - -> Self - where Sequence.Element: DatabaseValueConvertible - { + func filter(rawKeys: some Sequence) -> Self { let keys = Array(rawKeys) if keys.isEmpty { return none() @@ -305,7 +302,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { /// index on the key columns. /// /// - parameter key: A unique key - public func filter(key: [String: DatabaseValueConvertible?]?) -> Self { + public func filter(key: [String: (any DatabaseValueConvertible)?]?) -> Self { guard let key else { return none() } @@ -321,7 +318,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { /// index on the key columns. /// /// - parameter keys: A collection of unique keys - public func filter(keys: [[String: DatabaseValueConvertible?]]) -> Self { + public func filter(keys: [[String: (any DatabaseValueConvertible)?]]) -> Self { if keys.isEmpty { return none() } @@ -387,10 +384,7 @@ where Self: FilteredRequest, /// let request = try Player...filter(ids: [1, 2, 3]) /// /// - parameter ids: A collection of primary keys - public func filter(ids: Collection) - -> Self - where Collection.Element == RowDecoder.ID - { + public func filter(ids: some Collection) -> Self { filter(keys: ids) } } @@ -430,21 +424,21 @@ extension TableRequest where Self: AggregatingRequest { /// The protocol for all requests that can aggregate. public protocol AggregatingRequest { /// Creates a request grouped according to *expressions promise*. - func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self + func group(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. - func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self + func having(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self } extension AggregatingRequest { /// Creates a request grouped according to *expressions*. - public func group(_ expressions: [SQLExpressible]) -> Self { + public func group(_ expressions: [any SQLExpressible]) -> Self { group { _ in expressions } } /// Creates a request grouped according to *expressions*. - public func group(_ expressions: SQLExpressible...) -> Self { + public func group(_ expressions: any SQLExpressible...) -> Self { group(expressions) } @@ -461,7 +455,7 @@ extension AggregatingRequest { /// Creates a request with the provided *predicate* added to the /// eventual set of already applied predicates. - public func having(_ predicate: SQLExpressible) -> Self { + public func having(_ predicate: some SQLExpressible) -> Self { having { _ in predicate } } @@ -496,7 +490,7 @@ public protocol OrderedRequest { /// .order{ _ in [Column("email")] } /// .reversed() /// .order{ _ in [Column("name")] } - func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self + func order(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self /// Creates a request that reverses applied orderings. /// @@ -533,7 +527,7 @@ extension OrderedRequest { /// .order(Column("email")) /// .reversed() /// .order(Column("name")) - public func order(_ orderings: SQLOrderingTerm...) -> Self { + public func order(_ orderings: any SQLOrderingTerm...) -> Self { order { _ in orderings } } @@ -550,7 +544,7 @@ extension OrderedRequest { /// .order(Column("email")) /// .reversed() /// .order(Column("name")) - public func order(_ orderings: [SQLOrderingTerm]) -> Self { + public func order(_ orderings: [any SQLOrderingTerm]) -> Self { order { _ in orderings } } diff --git a/GRDB/QueryInterface/SQL/Column.swift b/GRDB/QueryInterface/SQL/Column.swift index 903cf7f7d..1bc67c9cf 100644 --- a/GRDB/QueryInterface/SQL/Column.swift +++ b/GRDB/QueryInterface/SQL/Column.swift @@ -76,7 +76,7 @@ public struct Column: ColumnExpression, Equatable { } /// Creates a column given a CodingKey. - public init(_ codingKey: CodingKey) { + public init(_ codingKey: some CodingKey) { self.name = codingKey.stringValue } diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 72696c126..249f2e4f9 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -1694,9 +1694,9 @@ public protocol SQLSpecificExpressible: SQLExpressible, SQLSelectable, SQLOrderi // spill out. The three declarations below have no chance overloading a // Swift-defined operator, or a user-defined operator: // - // - ==(SQLExpressible, SQLSpecificExpressible) - // - ==(SQLSpecificExpressible, SQLExpressible) - // - ==(SQLSpecificExpressible, SQLSpecificExpressible) + // - ==(some SQLExpressible, some SQLSpecificExpressible) + // - ==(some SQLSpecificExpressible, some SQLExpressible) + // - ==(some SQLSpecificExpressible, some SQLSpecificExpressible) } extension SQLSpecificExpressible { @@ -1739,7 +1739,7 @@ extension Sequence where Element: SQLSpecificExpressible { } } -extension Sequence where Element == SQLSpecificExpressible { +extension Sequence where Element == any SQLSpecificExpressible { /// Returns an expression by joining all elements with an associative SQL /// binary operator. /// @@ -1853,7 +1853,7 @@ extension SQLSpecificExpressible { /// let height: Int /// let area: Int /// - /// static let databaseSelection: [SQLSelectable] = [ + /// static let databaseSelection: [any SQLSelectable] = [ /// Column(CodingKeys.width), /// Column(CodingKeys.height), /// (Column(CodingKeys.width) * Column(CodingKeys.height)).forKey(CodingKeys.area), @@ -1864,7 +1864,7 @@ extension SQLSpecificExpressible { /// let shapes: [Shape] = try Shape.fetchAll(db) /// /// See `forKey(_ key: String)` for more information. - public func forKey(_ key: CodingKey) -> SQLSelection { + public func forKey(_ key: some CodingKey) -> SQLSelection { forKey(key.stringValue) } } diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index d2acfc445..d5c94b195 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -4,7 +4,7 @@ /// /// // ABS(amount) /// abs(Column("amount")) -public func abs(_ value: SQLSpecificExpressible) -> SQLExpression { +public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression { .function("ABS", [value.sqlExpression]) } @@ -15,7 +15,7 @@ public func abs(_ value: SQLSpecificExpressible) -> SQLExpression { /// /// // AVG(length) /// average(Column("length")) -public func average(_ value: SQLSpecificExpressible) -> SQLExpression { +public func average(_ value: some SQLSpecificExpressible) -> SQLExpression { .aggregate("AVG", [value.sqlExpression]) } @@ -26,7 +26,7 @@ public func average(_ value: SQLSpecificExpressible) -> SQLExpression { /// /// // COUNT(email) /// count(Column("email")) -public func count(_ counted: SQLSpecificExpressible) -> SQLExpression { +public func count(_ counted: some SQLSpecificExpressible) -> SQLExpression { .count(counted.sqlExpression) } @@ -37,7 +37,7 @@ public func count(_ counted: SQLSpecificExpressible) -> SQLExpression { /// /// // COUNT(DISTINCT email) /// count(distinct: Column("email")) -public func count(distinct value: SQLSpecificExpressible) -> SQLExpression { +public func count(distinct value: some SQLSpecificExpressible) -> SQLExpression { .countDistinct(value.sqlExpression) } @@ -48,7 +48,7 @@ public func count(distinct value: SQLSpecificExpressible) -> SQLExpression { /// /// // IFNULL(name, 'Anonymous') /// Column("name") ?? "Anonymous" -public func ?? (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func ?? (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .function("IFNULL", [lhs.sqlExpression, rhs.sqlExpression]) } @@ -59,7 +59,7 @@ public func ?? (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// /// // LENGTH(name) /// length(Column("name")) -public func length(_ value: SQLSpecificExpressible) -> SQLExpression { +public func length(_ value: some SQLSpecificExpressible) -> SQLExpression { .function("LENGTH", [value.sqlExpression]) } @@ -70,7 +70,7 @@ public func length(_ value: SQLSpecificExpressible) -> SQLExpression { /// /// // MAX(score) /// max(Column("score")) -public func max(_ value: SQLSpecificExpressible) -> SQLExpression { +public func max(_ value: some SQLSpecificExpressible) -> SQLExpression { .aggregate("MAX", [value.sqlExpression]) } @@ -81,7 +81,7 @@ public func max(_ value: SQLSpecificExpressible) -> SQLExpression { /// /// // MIN(score) /// min(Column("score")) -public func min(_ value: SQLSpecificExpressible) -> SQLExpression { +public func min(_ value: some SQLSpecificExpressible) -> SQLExpression { .aggregate("MIN", [value.sqlExpression]) } @@ -96,7 +96,7 @@ public func min(_ value: SQLSpecificExpressible) -> SQLExpression { /// /// // SUM(amount) /// sum(Column("amount")) -public func sum(_ value: SQLSpecificExpressible) -> SQLExpression { +public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression { .aggregate("SUM", [value.sqlExpression]) } @@ -111,7 +111,7 @@ public func sum(_ value: SQLSpecificExpressible) -> SQLExpression { /// /// // TOTAL(amount) /// total(Column("amount")) -public func total(_ value: SQLSpecificExpressible) -> SQLExpression { +public func total(_ value: some SQLSpecificExpressible) -> SQLExpression { .aggregate("TOTAL", [value.sqlExpression]) } @@ -277,7 +277,7 @@ public enum SQLDateModifier: SQLSpecificExpressible { /// julianDay(Column("date"), .day(1)) /// /// For more information, see -public func julianDay(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression { +public func julianDay(_ value: some SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression { .function("JULIANDAY", [value.sqlExpression] + modifiers.map(\.sqlExpression)) } @@ -292,6 +292,6 @@ public func julianDay(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModif /// dateTime(Column("date"), .day(1)) /// /// For more information, see -public func dateTime(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression { +public func dateTime(_ value: some SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression { .function("DATETIME", [value.sqlExpression] + modifiers.map(\.sqlExpression)) } diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index 257cfc83e..e8ec42407 100644 --- a/GRDB/QueryInterface/SQL/SQLOperators.swift +++ b/GRDB/QueryInterface/SQL/SQLOperators.swift @@ -9,7 +9,7 @@ /// /// // name IS NULL /// Column("name") == nil -public func == (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { +public func == (lhs: some SQLSpecificExpressible, rhs: (any SQLExpressible)?) -> SQLExpression { .equal(lhs.sqlExpression, rhs?.sqlExpression ?? .null) } @@ -22,7 +22,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpress /// /// // NOT validated /// Column("validated") == false -public func == (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { +public func == (lhs: some SQLSpecificExpressible, rhs: Bool) -> SQLExpression { if rhs { return lhs.sqlExpression.is(.true) } else { @@ -39,7 +39,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { /// /// // name IS NULL /// nil == Column("name") -public func == (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { +public func == (lhs: (any SQLExpressible)?, rhs: some SQLSpecificExpressible) -> SQLExpression { .equal(lhs?.sqlExpression ?? .null, rhs.sqlExpression) } @@ -52,7 +52,7 @@ public func == (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpress /// /// // NOT validated /// false == Column("validated") -public func == (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { +public func == (lhs: Bool, rhs: some SQLSpecificExpressible) -> SQLExpression { if lhs { return rhs.sqlExpression.is(.true) } else { @@ -64,7 +64,7 @@ public func == (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { /// /// // email = login /// Column("email") == Column("login") -public func == (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func == (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .equal(lhs.sqlExpression, rhs.sqlExpression) } @@ -77,7 +77,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// /// // name IS NOT NULL /// Column("name") != nil -public func != (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { +public func != (lhs: some SQLSpecificExpressible, rhs: (any SQLExpressible)?) -> SQLExpression { !(lhs == rhs) } @@ -90,7 +90,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpress /// /// // validated /// Column("validated") != false -public func != (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { +public func != (lhs: some SQLSpecificExpressible, rhs: Bool) -> SQLExpression { !(lhs == rhs) } @@ -103,7 +103,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression { /// /// // name IS NOT NULL /// nil != Column("name") -public func != (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { +public func != (lhs: (any SQLExpressible)?, rhs: some SQLSpecificExpressible) -> SQLExpression { !(lhs == rhs) } @@ -116,7 +116,7 @@ public func != (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpress /// /// // validated /// false != Column("validated") -public func != (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { +public func != (lhs: Bool, rhs: some SQLSpecificExpressible) -> SQLExpression { !(lhs == rhs) } @@ -124,7 +124,7 @@ public func != (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression { /// /// // email <> login /// Column("email") != Column("login") -public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func != (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { !(lhs == rhs) } @@ -132,7 +132,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// /// // name IS 'Arthur' /// Column("name") === "Arthur" -public func === (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { +public func === (lhs: some SQLSpecificExpressible, rhs: (any SQLExpressible)?) -> SQLExpression { .compare(.is, lhs.sqlExpression, rhs?.sqlExpression ?? .null) } @@ -140,7 +140,7 @@ public func === (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpres /// /// // name IS 'Arthur' /// "Arthur" === Column("name") -public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { +public func === (lhs: (any SQLExpressible)?, rhs: some SQLSpecificExpressible) -> SQLExpression { if let lhs = lhs { return .compare(.is, lhs.sqlExpression, rhs.sqlExpression) } else { @@ -152,7 +152,7 @@ public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpres /// /// // email IS login /// Column("email") === Column("login") -public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func === (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .compare(.is, lhs.sqlExpression, rhs.sqlExpression) } @@ -160,7 +160,7 @@ public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQ /// /// // name IS NOT 'Arthur' /// Column("name") !== "Arthur" -public func !== (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { +public func !== (lhs: some SQLSpecificExpressible, rhs: (any SQLExpressible)?) -> SQLExpression { !(lhs === rhs) } @@ -168,7 +168,7 @@ public func !== (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpres /// /// // name IS NOT 'Arthur' /// "Arthur" !== Column("name") -public func !== (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { +public func !== (lhs: (any SQLExpressible)?, rhs: some SQLSpecificExpressible) -> SQLExpression { !(lhs === rhs) } @@ -176,7 +176,7 @@ public func !== (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpres /// /// // email IS NOT login /// Column("email") !== Column("login") -public func !== (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func !== (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { !(lhs === rhs) } @@ -186,7 +186,7 @@ public func !== (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQ /// /// // score < 18 /// Column("score") < 18 -public func < (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func < (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .binary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) } @@ -194,7 +194,7 @@ public func < (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// /// // 18 < score /// 18 < Column("score") -public func < (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func < (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) } @@ -202,7 +202,7 @@ public func < (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// /// // width < height /// Column("width") < Column("height") -public func < (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func < (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.lessThan, lhs.sqlExpression, rhs.sqlExpression) } @@ -210,7 +210,7 @@ public func < (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// /// // score <= 18 /// Column("score") <= 18 -public func <= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func <= (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .binary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } @@ -218,7 +218,7 @@ public func <= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// /// // 18 <= score /// 18 <= Column("score") -public func <= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func <= (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } @@ -226,7 +226,7 @@ public func <= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// /// // width <= height /// Column("width") <= Column("height") -public func <= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func <= (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } @@ -234,7 +234,7 @@ public func <= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// /// // score > 18 /// Column("score") > 18 -public func > (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func > (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .binary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) } @@ -242,7 +242,7 @@ public func > (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// /// // 18 > score /// 18 > Column("score") -public func > (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func > (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) } @@ -250,7 +250,7 @@ public func > (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// /// // width > height /// Column("width") > Column("height") -public func > (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func > (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression) } @@ -258,7 +258,7 @@ public func > (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// /// // score >= 18 /// Column("score") >= 18 -public func >= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func >= (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .binary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } @@ -266,7 +266,7 @@ public func >= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// /// // 18 >= score /// 18 >= Column("score") -public func >= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func >= (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } @@ -274,7 +274,7 @@ public func >= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// /// // width >= height /// Column("width") >= Column("height") -public func >= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func >= (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression) } @@ -285,7 +285,7 @@ extension Range where Bound: SQLExpressible { /// /// // email >= 'A' AND email < 'B' /// ("A"..<"B").contains(Column("email")) - public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { + public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { (element >= lowerBound) && (element < upperBound) } } @@ -295,7 +295,7 @@ extension ClosedRange where Bound: SQLExpressible { /// /// // email BETWEEN 'A' AND 'B' /// ("A"..."B").contains(Column("email")) - public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { + public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { .between( expression: element.sqlExpression, lowerBound: lowerBound.sqlExpression, @@ -308,7 +308,7 @@ extension CountableRange where Bound: SQLExpressible { /// /// // id BETWEEN 1 AND 9 /// (1..<10).contains(Column("id")) - public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { + public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { (element >= lowerBound) && (element < upperBound) } } @@ -318,7 +318,7 @@ extension CountableClosedRange where Bound: SQLExpressible { /// /// // id BETWEEN 1 AND 10 /// (1...10).contains(Column("id")) - public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { + public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { .between( expression: element.sqlExpression, lowerBound: lowerBound.sqlExpression, @@ -332,7 +332,7 @@ extension Sequence where Self.Iterator.Element: SQLExpressible { /// /// // id IN (1,2,3) /// [1, 2, 3].contains(Column("id")) - public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { + public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { SQLCollection.array(map(\.sqlExpression)).contains(element.sqlExpression) } } @@ -343,7 +343,7 @@ extension Sequence where Self.Iterator.Element == SQLExpressible { /// /// // id IN (1,2,3) /// [1, 2, 3].contains(Column("id")) - public func contains(_ element: SQLSpecificExpressible) -> SQLExpression { + public func contains(_ element: some SQLSpecificExpressible) -> SQLExpression { SQLCollection.array(map(\.sqlExpression)).contains(element.sqlExpression) } } @@ -355,7 +355,7 @@ extension Sequence where Self.Iterator.Element == SQLExpressible { /// /// // width * 2 /// Column("width") * 2 -public func * (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func * (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .associativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -363,7 +363,7 @@ public func * (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// /// // 2 * width /// 2 * Column("width") -public func * (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func * (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .associativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -371,7 +371,7 @@ public func * (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// /// // width * height /// Column("width") * Column("height") -public func * (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func * (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .associativeBinary(.multiply, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -379,7 +379,7 @@ public func * (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// /// // width / 2 /// Column("width") / 2 -public func / (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func / (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .binary(.divide, lhs.sqlExpression, rhs.sqlExpression) } @@ -387,7 +387,7 @@ public func / (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// /// // 2 / width /// 2 / Column("width") -public func / (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func / (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.divide, lhs.sqlExpression, rhs.sqlExpression) } @@ -395,7 +395,7 @@ public func / (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// /// // width / height /// Column("width") / Column("height") -public func / (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func / (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.divide, lhs.sqlExpression, rhs.sqlExpression) } @@ -403,7 +403,7 @@ public func / (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// /// // width + 2 /// Column("width") + 2 -public func + (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func + (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .associativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -411,7 +411,7 @@ public func + (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// /// // 2 + width /// 2 + Column("width") -public func + (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func + (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .associativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -419,7 +419,7 @@ public func + (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// /// // width + height /// Column("width") + Column("height") -public func + (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func + (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .associativeBinary(.add, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -427,7 +427,7 @@ public func + (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// /// // -width /// -Column("width") -public prefix func - (value: SQLSpecificExpressible) -> SQLExpression { +public prefix func - (value: some SQLSpecificExpressible) -> SQLExpression { .unary(.minus, value.sqlExpression) } @@ -435,7 +435,7 @@ public prefix func - (value: SQLSpecificExpressible) -> SQLExpression { /// /// // width - 2 /// Column("width") - 2 -public func - (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func - (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .binary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } @@ -443,7 +443,7 @@ public func - (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressio /// /// // 2 - width /// 2 - Column("width") -public func - (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func - (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } @@ -451,7 +451,7 @@ public func - (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressio /// /// // width - height /// Column("width") - Column("height") -public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func - (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .binary(.subtract, lhs.sqlExpression, rhs.sqlExpression) } @@ -462,7 +462,7 @@ public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE /// /// // favorite AND 0 /// Column("favorite") && false -public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func && (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .associativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -470,7 +470,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// /// // 0 AND favorite /// false && Column("favorite") -public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func && (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .associativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -478,7 +478,7 @@ public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// /// // email IS NOT NULL AND favorite /// Column("email") != nil && Column("favorite") -public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func && (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .associativeBinary(.and, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -486,7 +486,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// /// // favorite OR 1 /// Column("favorite") || true -public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { +public func || (lhs: some SQLSpecificExpressible, rhs: some SQLExpressible) -> SQLExpression { .associativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -494,7 +494,7 @@ public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// /// // 0 OR favorite /// true || Column("favorite") -public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func || (lhs: some SQLExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .associativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -502,7 +502,7 @@ public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// /// // email IS NULL OR hidden /// Column("email") == nil || Column("hidden") -public func || (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { +public func || (lhs: some SQLSpecificExpressible, rhs: some SQLSpecificExpressible) -> SQLExpression { .associativeBinary(.or, [lhs.sqlExpression, rhs.sqlExpression]) } @@ -515,14 +515,13 @@ public func || (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// /// // id NOT BETWEEN 1 AND 10 /// !((1...10).contains(Column("id"))) -public prefix func ! (value: SQLSpecificExpressible) -> SQLExpression { +public prefix func ! (value: some SQLSpecificExpressible) -> SQLExpression { value.sqlExpression.is(.falsey) } // MARK: - Like Operator extension SQLSpecificExpressible { - /// An SQL expression with the `LIKE` SQL operator. /// /// // email LIKE '%@example.com" @@ -530,7 +529,7 @@ extension SQLSpecificExpressible { /// /// // title LIKE '%10\%%' ESCAPE '\' /// Column("title").like("%10\\%%", escape: "\\") - public func like(_ pattern: SQLExpressible, escape: SQLExpressible? = nil) -> SQLExpression { + public func like(_ pattern: some SQLExpressible, escape: (any SQLExpressible)? = nil) -> SQLExpression { .escapableBinary(.like, sqlExpression, pattern.sqlExpression, escape: escape?.sqlExpression) } } diff --git a/GRDB/QueryInterface/SQL/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift index e37707cb1..f2da3af91 100644 --- a/GRDB/QueryInterface/SQL/SQLSelection.swift +++ b/GRDB/QueryInterface/SQL/SQLSelection.swift @@ -288,7 +288,7 @@ extension SQLSelection: SQLSelectable { /// /// struct Player : TableRecord { /// static var databaseTableName = "player" -/// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] +/// static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] /// } /// /// // SELECT *, rowid FROM player diff --git a/GRDB/QueryInterface/SQL/SQLSubquery.swift b/GRDB/QueryInterface/SQL/SQLSubquery.swift index f7d91a98a..093b1812d 100644 --- a/GRDB/QueryInterface/SQL/SQLSubquery.swift +++ b/GRDB/QueryInterface/SQL/SQLSubquery.swift @@ -110,7 +110,7 @@ extension SQLSubqueryable { /// // 1000 IN (SELECT score FROM player) /// let request = Player.select(Column("score"), as: Int.self) /// let condition = request.contains(1000) - public func contains(_ element: SQLExpressible) -> SQLExpression { + public func contains(_ element: some SQLExpressible) -> SQLExpression { SQLCollection.subquery(sqlSubquery).contains(element.sqlExpression) } diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index 4f4fb6131..3945e9ab6 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -71,7 +71,7 @@ extension Table { /// // SELECT id, email FROM player /// let table = Table("player") /// let request = table.select(Column("id"), Column("email")) - public func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest { + public func select(_ selection: any SQLSelectable...) -> QueryInterfaceRequest { all().select(selection) } @@ -80,7 +80,7 @@ extension Table { /// // SELECT id, email FROM player /// let table = Table("player") /// let request = table.select([Column("id"), Column("email")]) - public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest { + public func select(_ selection: [any SQLSelectable]) -> QueryInterfaceRequest { all().select(selection) } @@ -122,7 +122,7 @@ extension Table { /// let maxScore: Int? = try request.fetchOne(db) /// } public func select( - _ selection: [SQLSelectable], + _ selection: [any SQLSelectable], as type: RowDecoder.Type = RowDecoder.self) -> QueryInterfaceRequest { @@ -139,7 +139,7 @@ extension Table { /// let maxScore: Int? = try request.fetchOne(db) /// } public func select( - _ selection: SQLSelectable..., + _ selection: any SQLSelectable..., as type: RowDecoder.Type = RowDecoder.self) -> QueryInterfaceRequest { @@ -192,7 +192,7 @@ extension Table { /// let request = table /// .select([Column("id"), Column("email")]) /// .annotated(with: [Column("name")]) - public func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest { + public func annotated(with selection: [any SQLSelectable]) -> QueryInterfaceRequest { all().annotated(with: selection) } @@ -203,7 +203,7 @@ extension Table { /// let request = table /// .select([Column("id"), Column("email")]) /// .annotated(with: Column("name")) - public func annotated(with selection: SQLSelectable...) -> QueryInterfaceRequest { + public func annotated(with selection: any SQLSelectable...) -> QueryInterfaceRequest { all().annotated(with: selection) } @@ -212,7 +212,7 @@ extension Table { /// // SELECT * FROM player WHERE email = 'arthur@example.com' /// let table = Table("player") /// let request = table.filter(Column("email") == "arthur@example.com") - public func filter(_ predicate: SQLSpecificExpressible) -> QueryInterfaceRequest { + public func filter(_ predicate: some SQLSpecificExpressible) -> QueryInterfaceRequest { all().filter(predicate) } @@ -221,10 +221,7 @@ extension Table { /// // SELECT * FROM player WHERE id = 1 /// let table = Table("player") /// let request = table.filter(key: 1) - public func filter(key: PrimaryKeyType) - -> QueryInterfaceRequest - where PrimaryKeyType: DatabaseValueConvertible - { + public func filter(key: some DatabaseValueConvertible) -> QueryInterfaceRequest { all().filter(key: key) } @@ -233,9 +230,8 @@ extension Table { /// // SELECT * FROM player WHERE id IN (1, 2, 3) /// let table = Table("player") /// let request = table.filter(keys: [1, 2, 3]) - public func filter(keys: Sequence) + public func filter(keys: some Sequence) -> QueryInterfaceRequest - where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { all().filter(keys: keys) } @@ -248,7 +244,7 @@ extension Table { /// /// When executed, this request raises a fatal error if there is no unique /// index on the key columns. - public func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest { + public func filter(key: [String: (any DatabaseValueConvertible)?]?) -> QueryInterfaceRequest { all().filter(key: key) } @@ -260,7 +256,7 @@ extension Table { /// /// When executed, this request raises a fatal error if there is no unique /// index on the key columns. - public func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest { + public func filter(keys: [[String: (any DatabaseValueConvertible)?]]) -> QueryInterfaceRequest { all().filter(keys: keys) } @@ -297,7 +293,7 @@ extension Table { /// // SELECT * FROM player ORDER BY name /// let table = Table("player") /// let request = table.order(Column("name")) - public func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest { + public func order(_ orderings: any SQLOrderingTerm...) -> QueryInterfaceRequest { all().order(orderings) } @@ -307,7 +303,7 @@ extension Table { /// // SELECT * FROM player ORDER BY name /// let table = Table("player") /// let request = table.order([Column("name")]) - public func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest { + public func order(_ orderings: [any SQLOrderingTerm]) -> QueryInterfaceRequest { all().order(orderings) } @@ -394,10 +390,7 @@ extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConv /// let request = table.filter(ids: [1, 2, 3]) /// /// - parameter ids: A collection of primary keys - public func filter(ids: Collection) - -> QueryInterfaceRequest - where Collection: Swift.Collection, Collection.Element == RowDecoder.ID - { + public func filter(ids: some Collection) -> QueryInterfaceRequest { all().filter(ids: ids) } @@ -863,7 +856,7 @@ extension Table { /// - returns: An association to the common table expression. public func association( to cte: CommonTableExpression, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible) + on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( @@ -1162,10 +1155,7 @@ extension Table { /// - db: A database connection. /// - key: A primary key value. /// - returns: Whether a row exists for this primary key. - public func exists(_ db: Database, key: PrimaryKeyType) - throws -> Bool - where PrimaryKeyType: DatabaseValueConvertible - { + public func exists(_ db: Database, key: some DatabaseValueConvertible) throws -> Bool { try !filter(key: key).isEmpty(db) } } @@ -1210,7 +1200,7 @@ extension Table { /// - db: A database connection. /// - key: A dictionary of values. /// - returns: Whether a row exists for this key. - public func exists(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool { + public func exists(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { try !filter(key: key).isEmpty(db) } } @@ -1238,9 +1228,8 @@ extension Table { /// - keys: A sequence of primary keys. /// - returns: The number of deleted rows @discardableResult - public func deleteAll(_ db: Database, keys: Sequence) + public func deleteAll(_ db: Database, keys: some Sequence) throws -> Int - where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { let keys = Array(keys) if keys.isEmpty { @@ -1270,10 +1259,7 @@ extension Table { /// - key: A primary key value. /// - returns: Whether a database row was deleted. @discardableResult - public func deleteOne(_ db: Database, key: PrimaryKeyType) - throws -> Bool - where PrimaryKeyType: DatabaseValueConvertible - { + public func deleteOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Bool { if key.databaseValue.isNull { // Don't hit the database return false @@ -1307,10 +1293,7 @@ where RowDecoder: Identifiable, /// - ids: A collection of primary keys. /// - returns: The number of deleted rows @discardableResult - public func deleteAll(_ db: Database, ids: Collection) - throws -> Int - where Collection: Swift.Collection, Collection.Element == RowDecoder.ID - { + public func deleteAll(_ db: Database, ids: some Collection) throws -> Int { if ids.isEmpty { // Avoid hitting the database return 0 @@ -1360,7 +1343,7 @@ extension Table { /// - keys: An array of key dictionaries. /// - returns: The number of deleted rows @discardableResult - public func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int { + public func deleteAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Int { if keys.isEmpty { // Avoid hitting the database return 0 @@ -1378,7 +1361,7 @@ extension Table { /// - key: A dictionary of values. /// - returns: Whether a database row was deleted. @discardableResult - public func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool { + public func deleteOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { try deleteAll(db, keys: [key]) > 0 } } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index 633a4edea..a761c8de8 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -399,19 +399,19 @@ public class TableAlias: Hashable { /// Returns a qualified value that is able to resolve ambiguities in /// joined queries. - public subscript(_ selectable: SQLSelectable) -> SQLSelection { + public subscript(_ selectable: some SQLSelectable) -> SQLSelection { selectable.sqlSelection.qualified(with: self) } /// Returns a qualified expression that is able to resolve ambiguities in /// joined queries. - public subscript(_ expression: SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> SQLExpression { + public subscript(_ expression: some SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> SQLExpression { expression.sqlExpression.qualified(with: self) } /// Returns a qualified ordering that is able to resolve ambiguities in /// joined queries. - public subscript(_ ordering: SQLOrderingTerm) -> SQLOrdering { + public subscript(_ ordering: some SQLOrderingTerm) -> SQLOrdering { ordering.sqlOrdering.qualified(with: self) } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index dbe6271c0..1ceaea2d9 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -473,7 +473,7 @@ struct SQLQueryGenerator: Refinable { /// row.scopes["author"] // [id:12, name:"Herman Melville"] /// let author: Author = row["author"] /// } - private func rowAdapter(_ context: SQLGenerationContext) throws -> RowAdapter? { + private func rowAdapter(_ context: SQLGenerationContext) throws -> (any RowAdapter)? { try relation.rowAdapter(context, fromIndex: 0, rootRelation: true)?.adapter } } @@ -605,7 +605,7 @@ private struct SQLQualifiedRelation { _ context: SQLGenerationContext, fromIndex startIndex: Int, rootRelation: Bool) throws - -> (adapter: RowAdapter, endIndex: Int)? + -> (adapter: any RowAdapter, endIndex: Int)? { // Root relation && no join => no need for any adapter if rootRelation && joins.isEmpty { @@ -619,7 +619,7 @@ private struct SQLQualifiedRelation { // Recursively build adapters for each joined relation with a selection. // Name them according to the join keys. var endIndex = startIndex + sourceSelectionWidth - var scopes: [String: RowAdapter] = [:] + var scopes: [String: any RowAdapter] = [:] for (key, join) in joins { if let (joinAdapter, joinEndIndex) = try join .relation diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index a8334fb76..a68dda642 100644 --- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift @@ -7,9 +7,7 @@ extension SQLInterpolation { /// /// // SELECT * FROM player /// let request: SQLRequest = "SELECT * FROM \(Player.self)" - public mutating func appendInterpolation(_ table: T.Type) - where T: TableRecord - { + public mutating func appendInterpolation(_ table: (some TableRecord).Type) { appendLiteral(table.databaseTableName.quotedDatabaseIdentifier) } @@ -18,7 +16,7 @@ extension SQLInterpolation { /// // SELECT * FROM player /// let request: SQLRequest = "SELECT * FROM \(Player.self)" @_disfavoredOverload - public mutating func appendInterpolation(_ table: TableRecord.Type) { + public mutating func appendInterpolation(_ table: any TableRecord.Type) { appendLiteral(table.databaseTableName.quotedDatabaseIdentifier) } @@ -27,9 +25,7 @@ extension SQLInterpolation { /// // INSERT INTO player ... /// let player: Player = ... /// let request: SQLRequest = "INSERT INTO \(tableOf: player) ..." - public mutating func appendInterpolation(tableOf record: T) - where T: TableRecord - { + public mutating func appendInterpolation(tableOf record: some TableRecord) { appendInterpolation(type(of: record)) } @@ -39,7 +35,7 @@ extension SQLInterpolation { /// let player: Player = ... /// let request: SQLRequest = "INSERT INTO \(tableOf: player) ..." @_disfavoredOverload - public mutating func appendInterpolation(tableOf record: TableRecord) { + public mutating func appendInterpolation(tableOf record: any TableRecord) { appendInterpolation(type(of: record)) } @@ -52,11 +48,9 @@ extension SQLInterpolation { /// // SELECT p.* FROM player p /// let player: Player = ... /// let request: SQLRequest = "SELECT \(columnsOf: Player.self, tableAlias: "p") FROM player p" - public mutating func appendInterpolation(columnsOf record: T.Type, tableAlias: String? = nil) - where T: TableRecord - { - let alias = TableAlias(name: tableAlias ?? T.databaseTableName) - elements.append(contentsOf: T.databaseSelection + public mutating func appendInterpolation(columnsOf recordType: (some TableRecord).Type, tableAlias: String? = nil) { + let alias = TableAlias(name: tableAlias ?? recordType.databaseTableName) + elements.append(contentsOf: recordType.databaseSelection .map { CollectionOfOne(.selection($0.sqlSelection.qualified(with: alias))) } .joined(separator: CollectionOfOne(.sql(", ")))) } @@ -69,9 +63,7 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// SELECT \(AllColumns()) FROM player /// """ - public mutating func appendInterpolation(_ selection: T) - where T: SQLSelectable - { + public mutating func appendInterpolation(_ selection: some SQLSelectable) { elements.append(.selection(selection.sqlSelection)) } @@ -82,7 +74,7 @@ extension SQLInterpolation { /// SELECT \(AllColumns()) FROM player /// """ @_disfavoredOverload - public mutating func appendInterpolation(_ selection: SQLSelectable?) { + public mutating func appendInterpolation(_ selection: (any SQLSelectable)?) { if let selection = selection { elements.append(.selection(selection.sqlSelection)) } else { @@ -98,9 +90,7 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// SELECT * FROM player ORDER BY \(Column("name").desc) /// """ - public mutating func appendInterpolation(_ orderingTerm: T) - where T: SQLOrderingTerm - { + public mutating func appendInterpolation(_ orderingTerm: some SQLOrderingTerm) { elements.append(.ordering(orderingTerm.sqlOrdering)) } @@ -111,7 +101,7 @@ extension SQLInterpolation { /// SELECT * FROM player ORDER BY \(Column("name").desc) /// """ @_disfavoredOverload - public mutating func appendInterpolation(_ orderingTerm: SQLOrderingTerm) { + public mutating func appendInterpolation(_ orderingTerm: any SQLOrderingTerm) { elements.append(.ordering(orderingTerm.sqlOrdering)) } @@ -123,8 +113,9 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// SELECT \(Column("name")) FROM player /// """ - public mutating func appendInterpolation(_ expressible: T) - where T: SQLExpressible & SQLSelectable & SQLOrderingTerm + public mutating func appendInterpolation(_ expressible: some SQLExpressible + & SQLSelectable + & SQLOrderingTerm) { elements.append(.expression(expressible.sqlExpression)) } @@ -136,7 +127,7 @@ extension SQLInterpolation { /// SELECT \(Column("name")) FROM player /// """ @_disfavoredOverload - public mutating func appendInterpolation(_ expressible: SQLExpressible?) { + public mutating func appendInterpolation(_ expressible: (any SQLExpressible)?) { if let expressible = expressible { elements.append(.expression(expressible.sqlExpression)) } else { @@ -152,9 +143,7 @@ extension SQLInterpolation { /// let request: SQLRequest = " /// SELECT \(CodingKey.name) FROM player /// """ - public mutating func appendInterpolation(_ key: T) - where T: CodingKey - { + public mutating func appendInterpolation(_ key: some CodingKey) { appendInterpolation(Column(key.stringValue)) } @@ -164,8 +153,10 @@ extension SQLInterpolation { /// let request: SQLRequest = " /// SELECT \(CodingKey.name) FROM player /// """ - public mutating func appendInterpolation(_ key: T) - where T: CodingKey & SQLExpressible & SQLSelectable & SQLOrderingTerm + public mutating func appendInterpolation(_ key: some CodingKey + & SQLExpressible + & SQLSelectable + & SQLOrderingTerm) { appendInterpolation(Column(key.stringValue)) } @@ -177,7 +168,7 @@ extension SQLInterpolation { /// SELECT \(CodingKey.name) FROM player /// """ @_disfavoredOverload - public mutating func appendInterpolation(_ key: CodingKey) { + public mutating func appendInterpolation(_ key: any CodingKey) { appendInterpolation(Column(key.stringValue)) } @@ -193,8 +184,10 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// SELECT * FROM player WHERE score = (\(subquery)) /// """ - public mutating func appendInterpolation(_ subquery: T) - where T: SQLSubqueryable & SQLExpressible & SQLSelectable & SQLOrderingTerm + public mutating func appendInterpolation(_ subquery: some SQLSubqueryable + & SQLExpressible + & SQLSelectable + & SQLOrderingTerm) { elements.append(.subquery(subquery.sqlSubquery)) } @@ -216,9 +209,7 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// SELECT * FROM player WHERE id IN \(ids) /// """ - public mutating func appendInterpolation(_ sequence: T) - where T: Sequence, T.Element: SQLExpressible - { + public mutating func appendInterpolation(_ sequence: some Sequence) { let e: [SQL.Element] = sequence.map { .expression($0.sqlExpression) } if e.isEmpty { appendLiteral("(SELECT NULL WHERE NULL)") @@ -244,18 +235,14 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// SELECT * FROM player WHERE a IN \(expressions) /// """ - public mutating func appendInterpolation(_ sequence: T) - where T: Sequence, T.Element == SQLExpressible - { + public mutating func appendInterpolation(_ sequence: some Sequence){ appendInterpolation(sequence.lazy.map(\.sqlExpression)) } // When a value is both an expression and a sequence of expressions, // favor the expression side. Use case: Foundation.Data interpolation. /// :nodoc: - public mutating func appendInterpolation(_ expressible: T) - where T: Sequence, T: SQLExpressible, T.Element: SQLExpressible - { + public mutating func appendInterpolation(_ expressible: some SQLExpressible & Sequence) { elements.append(.expression(expressible.sqlExpression)) } @@ -268,7 +255,7 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// WITH \(definitionFor: cte) SELECT * FROM \(cte) /// """ - public mutating func appendInterpolation(_ cte: CommonTableExpression) { + public mutating func appendInterpolation(_ cte: CommonTableExpression) { elements.append(.sql(cte.tableName.quotedDatabaseIdentifier)) } @@ -279,7 +266,7 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// WITH \(definitionFor: cte) SELECT * FROM \(cte) /// """ - public mutating func appendInterpolation(definitionFor cte: CommonTableExpression) { + public mutating func appendInterpolation(definitionFor cte: CommonTableExpression) { elements.append(.sql(cte.tableName.quotedDatabaseIdentifier)) if let columns = cte.cte.columns, !columns.isEmpty { diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 820d45278..e5112e3bf 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -144,7 +144,7 @@ extension Database { columns: [String], unique: Bool = false, ifNotExists: Bool = false, - condition: SQLExpressible? = nil) + condition: (any SQLExpressible)? = nil) throws { var options: IndexOptions = [] @@ -177,7 +177,7 @@ extension Database { on table: String, columns: [String], options: IndexOptions = [], - condition: SQLExpressible? = nil) + condition: (any SQLExpressible)? = nil) throws { let definition = IndexDefinition( @@ -477,7 +477,7 @@ public final class TableDefinition { /// See /// /// - parameter condition: The checked condition - public func check(_ condition: SQLExpressible) { + public func check(_ condition: some SQLExpressible) { checkConstraints.append(condition.sqlExpression) } @@ -1003,7 +1003,7 @@ public final class ColumnDefinition { /// represents the defined column, and returns the expression to check. /// - returns: Self so that you can further refine the column definition. @discardableResult - public func check(_ condition: (Column) -> SQLExpressible) -> Self { + public func check(_ condition: (Column) -> any SQLExpressible) -> Self { checkConstraints.append(condition(Column(name)).sqlExpression) return self } @@ -1035,7 +1035,7 @@ public final class ColumnDefinition { /// - parameter value: A DatabaseValueConvertible value. /// - returns: Self so that you can further refine the column definition. @discardableResult - public func defaults(to value: DatabaseValueConvertible) -> Self { + public func defaults(to value: some DatabaseValueConvertible) -> Self { defaultExpression = value.sqlExpression return self } @@ -1138,7 +1138,7 @@ public final class ColumnDefinition { /// - returns: Self so that you can further refine the column definition. @discardableResult public func generatedAs( - _ expression: SQLExpressible, + _ expression: some SQLExpressible, _ qualification: GeneratedColumnQualification = .virtual) -> Self { diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index 98b49fa7d..05685015d 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -336,7 +336,7 @@ extension TableRecord { /// - returns: An association to the common table expression. public static func association( to cte: CommonTableExpression, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible) + on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index 4cbbc74dd..08584faf7 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -23,7 +23,7 @@ extension TableRecord { /// /// // SELECT id, email FROM player /// let request = Player.select(Column("id"), Column("email")) - public static func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest { + public static func select(_ selection: any SQLSelectable...) -> QueryInterfaceRequest { all().select(selection) } @@ -31,7 +31,7 @@ extension TableRecord { /// /// // SELECT id, email FROM player /// let request = Player.select([Column("id"), Column("email")]) - public static func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest { + public static func select(_ selection: [any SQLSelectable]) -> QueryInterfaceRequest { all().select(selection) } @@ -70,7 +70,7 @@ extension TableRecord { /// let maxScore: Int? = try request.fetchOne(db) /// } public static func select( - _ selection: [SQLSelectable], + _ selection: [any SQLSelectable], as type: RowDecoder.Type = RowDecoder.self) -> QueryInterfaceRequest { @@ -86,7 +86,7 @@ extension TableRecord { /// let maxScore: Int? = try request.fetchOne(db) /// } public static func select( - _ selection: SQLSelectable..., + _ selection: any SQLSelectable..., as type: RowDecoder.Type = RowDecoder.self) -> QueryInterfaceRequest { @@ -136,7 +136,7 @@ extension TableRecord { /// let request = Player /// .select([Column("id"), Column("email")]) /// .annotated(with: [Column("name")]) - public static func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest { + public static func annotated(with selection: [any SQLSelectable]) -> QueryInterfaceRequest { all().annotated(with: selection) } @@ -146,7 +146,7 @@ extension TableRecord { /// let request = Player /// .select([Column("id"), Column("email")]) /// .annotated(with: Column("name")) - public static func annotated(with selection: SQLSelectable...) -> QueryInterfaceRequest { + public static func annotated(with selection: any SQLSelectable...) -> QueryInterfaceRequest { all().annotated(with: selection) } @@ -157,7 +157,7 @@ extension TableRecord { /// /// // SELECT * FROM player WHERE email = 'arthur@example.com' /// let request = Player.filter(Column("email") == "arthur@example.com") - public static func filter(_ predicate: SQLSpecificExpressible) -> QueryInterfaceRequest { + public static func filter(_ predicate: some SQLSpecificExpressible) -> QueryInterfaceRequest { all().filter(predicate) } @@ -165,10 +165,7 @@ extension TableRecord { /// /// // SELECT * FROM player WHERE id = 1 /// let request = Player.filter(key: 1) - public static func filter(key: PrimaryKeyType) - -> QueryInterfaceRequest - where PrimaryKeyType: DatabaseValueConvertible - { + public static func filter(key: some DatabaseValueConvertible) -> QueryInterfaceRequest { all().filter(key: key) } @@ -176,9 +173,8 @@ extension TableRecord { /// /// // SELECT * FROM player WHERE id IN (1, 2, 3) /// let request = Player.filter(keys: [1, 2, 3]) - public static func filter(keys: Sequence) + public static func filter(keys: some Sequence) -> QueryInterfaceRequest - where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { all().filter(keys: keys) } @@ -190,7 +186,7 @@ extension TableRecord { /// /// When executed, this request raises a fatal error if there is no unique /// index on the key columns. - public static func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest { + public static func filter(key: [String: (any DatabaseValueConvertible)?]?) -> QueryInterfaceRequest { all().filter(key: key) } @@ -201,7 +197,7 @@ extension TableRecord { /// /// When executed, this request raises a fatal error if there is no unique /// index on the key columns. - public static func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest { + public static func filter(keys: [[String: (any DatabaseValueConvertible)?]]) -> QueryInterfaceRequest { all().filter(keys: keys) } @@ -236,7 +232,7 @@ extension TableRecord { /// /// // SELECT * FROM player ORDER BY name /// let request = Player.order(Column("name")) - public static func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest { + public static func order(_ orderings: any SQLOrderingTerm...) -> QueryInterfaceRequest { all().order(orderings) } @@ -245,7 +241,7 @@ extension TableRecord { /// /// // SELECT * FROM player ORDER BY name /// let request = Player.order([Column("name")]) - public static func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest { + public static func order(_ orderings: [any SQLOrderingTerm]) -> QueryInterfaceRequest { all().order(orderings) } @@ -365,10 +361,7 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// let request = Player.filter(ids: [1, 2, 3]) /// /// - parameter ids: A collection of primary keys - public static func filter(ids: Collection) - -> QueryInterfaceRequest - where Collection: Swift.Collection, Collection.Element == ID - { + public static func filter(ids: some Collection) -> QueryInterfaceRequest { all().filter(ids: ids) } diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift index 06c1e133c..a9f052a67 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -12,7 +12,7 @@ extension EncodableRecord where Self: Encodable { /// The encoder that encodes a record into GRDB's PersistenceContainer private class RecordEncoder: Encoder { - var codingPath: [CodingKey] { [] } + var codingPath: [any CodingKey] { [] } var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } private var _persistenceContainer: PersistenceContainer var persistenceContainer: PersistenceContainer { _persistenceContainer } @@ -49,7 +49,7 @@ private class RecordEncoder: Encoder { private struct KeyedContainer: KeyedEncodingContainerProtocol { var recordEncoder: RecordEncoder var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } - var codingPath: [CodingKey] { [] } + var codingPath: [any CodingKey] { [] } // swiftlint:disable comma func encode(_ value: Bool, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) } @@ -121,16 +121,16 @@ private class RecordEncoder: Encoder { } /// Helper methods - fileprivate func persist(_ value: DatabaseValueConvertible?, forKey key: CodingKey) { + fileprivate func persist(_ value: (any DatabaseValueConvertible)?, forKey key: any CodingKey) { _persistenceContainer[keyEncodingStrategy.column(forKey: key)] = value } - fileprivate func encode(_ value: T, forKey key: CodingKey) throws where T: Encodable { + fileprivate func encode(_ value: T, forKey key: any CodingKey) throws where T: Encodable { if let date = value as? Date { persist(Record.databaseDateEncodingStrategy.encode(date), forKey: key) } else if let uuid = value as? UUID { persist(Record.databaseUUIDEncodingStrategy.encode(uuid), forKey: key) - } else if let value = value as? DatabaseValueConvertible { + } else if let value = value as? any DatabaseValueConvertible { // Prefer DatabaseValueConvertible encoding over Decodable. persist(value.databaseValue, forKey: key) } else { @@ -170,12 +170,12 @@ private class RecordEncoder: Encoder { /// The encoder that encodes into a database column private class ColumnEncoder: Encoder { var recordEncoder: RecordEncoder - var key: CodingKey - var codingPath: [CodingKey] { [key] } + var key: any CodingKey + var codingPath: [any CodingKey] { [key] } var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo } var requiresJSON = false - init(recordEncoder: RecordEncoder, key: CodingKey) { + init(recordEncoder: RecordEncoder, key: some CodingKey) { self.recordEncoder = recordEncoder self.key = key } diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 9ced8258e..ab5fefb52 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -212,14 +212,14 @@ public struct PersistenceContainer { // fileprivate for Row(_:PersistenceContainer) // The ordering of the OrderedDictionary helps generating always the same // SQL queries, and hit the statement cache. - fileprivate var storage: OrderedDictionary + fileprivate var storage: OrderedDictionary /// Accesses the value associated with the given column. /// /// It is undefined behavior to set different values for the same column. /// Column names are case insensitive, so defining both "name" and "NAME" /// is considered undefined behavior. - public subscript(_ column: String) -> DatabaseValueConvertible? { + public subscript(_ column: String) -> (any DatabaseValueConvertible)? { get { storage[column] ?? nil } set { storage.updateValue(newValue, forKey: column) } } @@ -229,7 +229,7 @@ public struct PersistenceContainer { /// It is undefined behavior to set different values for the same column. /// Column names are case insensitive, so defining both "name" and "NAME" /// is considered undefined behavior. - public subscript(_ column: Column) -> DatabaseValueConvertible? { + public subscript(_ column: some ColumnExpression) -> (any DatabaseValueConvertible)? { get { self[column.name] } set { self[column.name] = newValue } } @@ -252,13 +252,13 @@ public struct PersistenceContainer { var columns: [String] { Array(storage.keys) } /// Values stored in the container, ordered like columns. - var values: [DatabaseValueConvertible?] { Array(storage.values) } + var values: [(any DatabaseValueConvertible)?] { Array(storage.values) } /// Accesses the value associated with the given column, in a /// case-insensitive fashion. /// /// :nodoc: - subscript(caseInsensitive column: String) -> DatabaseValueConvertible? { + subscript(caseInsensitive column: String) -> (any DatabaseValueConvertible)? { get { if let value = storage[column] { return value @@ -296,7 +296,7 @@ public struct PersistenceContainer { var isEmpty: Bool { storage.isEmpty } /// An iterator over the (column, value) pairs - func makeIterator() -> IndexingIterator> { + func makeIterator() -> IndexingIterator> { storage.makeIterator() } @@ -370,7 +370,7 @@ public enum DatabaseDateEncodingStrategy { case formatted(DateFormatter) /// Encodes the result of the user-provided function - case custom((Date) -> DatabaseValueConvertible?) + case custom((Date) -> (any DatabaseValueConvertible)?) private static let iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() @@ -378,24 +378,24 @@ public enum DatabaseDateEncodingStrategy { return formatter }() - func encode(_ date: Date) -> DatabaseValueConvertible? { + func encode(_ date: Date) -> DatabaseValue { switch self { case .deferredToDate: return date.databaseValue case .timeIntervalSinceReferenceDate: - return date.timeIntervalSinceReferenceDate + return date.timeIntervalSinceReferenceDate.databaseValue case .timeIntervalSince1970: - return date.timeIntervalSince1970 + return date.timeIntervalSince1970.databaseValue case .millisecondsSince1970: - return Int64(floor(1000.0 * date.timeIntervalSince1970)) + return Int64(floor(1000.0 * date.timeIntervalSince1970)).databaseValue case .secondsSince1970: - return Int64(floor(date.timeIntervalSince1970)) + return Int64(floor(date.timeIntervalSince1970)).databaseValue case .iso8601: - return Self.iso8601Formatter.string(from: date) + return Self.iso8601Formatter.string(from: date).databaseValue case .formatted(let formatter): - return formatter.string(from: date) + return formatter.string(from: date).databaseValue case .custom(let format): - return format(date) + return format(date)?.databaseValue ?? .null } } } @@ -425,14 +425,14 @@ public enum DatabaseUUIDEncodingStrategy { /// Encodes UUIDs as lowercased strings such as "e621e1f8-c36c-495a-93fc-0c247a3e6e5f" case lowercaseString - func encode(_ uuid: UUID) -> DatabaseValueConvertible { + func encode(_ uuid: UUID) -> DatabaseValue { switch self { case .deferredToUUID: return uuid.databaseValue case .uppercaseString: - return uuid.uuidString + return uuid.uuidString.databaseValue case .lowercaseString: - return uuid.uuidString.lowercased() + return uuid.uuidString.lowercased().databaseValue } } } @@ -459,9 +459,9 @@ public enum DatabaseColumnEncodingStrategy { case convertToSnakeCase /// A key encoding strategy defined by the closure you supply. - case custom((CodingKey) -> String) + case custom((any CodingKey) -> String) - func column(forKey key: CodingKey) -> String { + func column(forKey key: some CodingKey) -> String { switch self { case .useDefaultKeys: return key.stringValue diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 73b51064b..1bf3de91e 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -208,9 +208,9 @@ private struct _RowDecoder: Decoder { return try R.databaseDateDecodingStrategy.decodeIfPresent( fromRow: row, atUncheckedIndex: index) as! T? - } else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type { + } else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type { return try type.fastDecodeIfPresent(fromRow: row, atUncheckedIndex: index) as! T? - } else if let type = T.self as? DatabaseValueConvertible.Type { + } else if let type = T.self as? any DatabaseValueConvertible.Type { return try type.decodeIfPresent(fromRow: row, atUncheckedIndex: index) as! T? } else if row.impl.hasNull(atUncheckedIndex: index) { return nil @@ -251,9 +251,9 @@ private struct _RowDecoder: Decoder { // This allows decoding Date from String, or DatabaseValue from NULL. if type == Date.self { return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: index) as! T - } else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type { + } else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type { return try type.fastDecode(fromRow: row, atUncheckedIndex: index) as! T - } else if let type = T.self as? DatabaseValueConvertible.Type { + } else if let type = T.self as? any DatabaseValueConvertible.Type { return try type.decode(fromRow: row, atUncheckedIndex: index) as! T } else { return try decode(type, fromRow: row, columnAtIndex: index, key: key) @@ -340,7 +340,7 @@ private struct _RowDecoder: Decoder { throws -> T where T: Decodable { - if let type = T.self as? FetchableRecord.Type { + if let type = T.self as? any FetchableRecord.Type { // Prefer FetchableRecord decoding over Decodable. return type.init(row: row) as! T } else { @@ -414,7 +414,7 @@ extension PrefetchedRowsDecoder: UnkeyedDecodingContainer { defer { currentIndex += 1 } let columnDecodingStrategy: DatabaseColumnDecodingStrategy - if let type = T.self as? FetchableRecord.Type { + if let type = T.self as? any FetchableRecord.Type { columnDecodingStrategy = type.databaseColumnDecodingStrategy } else { columnDecodingStrategy = .useDefaultKeys @@ -490,9 +490,9 @@ extension ColumnDecoder: SingleValueDecodingContainer { // This allows decoding Date from String, or DatabaseValue from NULL. if type == Date.self { return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T - } else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type { + } else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type { return try type.fastDecode(fromRow: row, atUncheckedIndex: columnIndex) as! T - } else if let type = T.self as? DatabaseValueConvertible.Type { + } else if let type = T.self as? any DatabaseValueConvertible.Type { return try type.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T } else { return try T(from: self) diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift index ba17b07cd..2799a2592 100644 --- a/GRDB/Record/FetchableRecord+TableRecord.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -94,9 +94,8 @@ extension FetchableRecord where Self: TableRecord { /// - keys: A sequence of primary keys. /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, keys: Sequence) + public static func fetchCursor(_ db: Database, keys: some Sequence) throws -> RecordCursor - where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { try filter(keys: keys).fetchCursor(db) } @@ -112,9 +111,8 @@ extension FetchableRecord where Self: TableRecord { /// - keys: A sequence of primary keys. /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, keys: Sequence) + public static func fetchAll(_ db: Database, keys: some Sequence) throws -> [Self] - where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { let keys = Array(keys) if keys.isEmpty { @@ -133,10 +131,7 @@ extension FetchableRecord where Self: TableRecord { /// - key: A primary key value. /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, key: PrimaryKeyType) - throws -> Self? - where PrimaryKeyType: DatabaseValueConvertible - { + public static func fetchOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Self? { if key.databaseValue.isNull { // Don't hit the database return nil @@ -164,9 +159,8 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa /// - ids: A collection of primary keys. /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, ids: Collection) + public static func fetchCursor(_ db: Database, ids: some Collection) throws -> RecordCursor - where Collection: Swift.Collection, Collection.Element == ID { try filter(ids: ids).fetchCursor(db) } @@ -182,10 +176,7 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa /// - ids: A collection of primary keys. /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, ids: Collection) - throws -> [Self] - where Collection: Swift.Collection, Collection.Element == ID - { + public static func fetchAll(_ db: Database, ids: some Collection) throws -> [Self] { if ids.isEmpty { // Avoid hitting the database return [] @@ -217,9 +208,8 @@ extension FetchableRecord where Self: TableRecord & Hashable { /// - keys: A sequence of primary keys. /// - returns: A set of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, keys: Sequence) + public static func fetchSet(_ db: Database, keys: some Sequence) throws -> Set - where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { let keys = Array(keys) if keys.isEmpty { @@ -241,10 +231,7 @@ extension FetchableRecord where Self: TableRecord & Hashable & Identifiable, ID: /// - ids: A collection of primary keys. /// - returns: A set of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, ids: Collection) - throws -> Set - where Collection: Swift.Collection, Collection.Element == ID - { + public static func fetchSet(_ db: Database, ids: some Collection) throws -> Set { if ids.isEmpty { // Avoid hitting the database return [] @@ -275,7 +262,7 @@ extension FetchableRecord where Self: TableRecord { /// - keys: An array of key dictionaries. /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) + public static func fetchCursor(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> RecordCursor { try filter(keys: keys).fetchCursor(db) @@ -296,7 +283,7 @@ extension FetchableRecord where Self: TableRecord { /// - keys: An array of key dictionaries. /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> [Self] { + public static func fetchAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> [Self] { if keys.isEmpty { // Avoid hitting the database return [] @@ -314,7 +301,7 @@ extension FetchableRecord where Self: TableRecord { /// - key: A dictionary of values. /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]?) throws -> Self? { + public static func fetchOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]?) throws -> Self? { guard let key else { // Avoid hitting the database return nil @@ -337,7 +324,7 @@ extension FetchableRecord where Self: TableRecord & Hashable { /// - keys: An array of key dictionaries. /// - returns: A set of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Set { + public static func fetchSet(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Set { if keys.isEmpty { // Avoid hitting the database return [] diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 004bc9014..bb2932dd5 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -173,7 +173,7 @@ extension FetchableRecord { public static func fetchCursor( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> RecordCursor { try RecordCursor(statement: statement, arguments: arguments, adapter: adapter) @@ -193,7 +193,7 @@ extension FetchableRecord { public static func fetchAll( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> [Self] { try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) @@ -213,7 +213,7 @@ extension FetchableRecord { public static func fetchOne( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Self? { try fetchCursor(statement, arguments: arguments, adapter: adapter).next() @@ -235,7 +235,7 @@ extension FetchableRecord where Self: Hashable { public static func fetchSet( _ statement: Statement, arguments: StatementArguments? = nil, - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Set { try Set(fetchCursor(statement, arguments: arguments, adapter: adapter)) @@ -269,7 +269,7 @@ extension FetchableRecord { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> RecordCursor { try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -290,7 +290,7 @@ extension FetchableRecord { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> [Self] { try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -311,7 +311,7 @@ extension FetchableRecord { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Self? { try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -334,7 +334,7 @@ extension FetchableRecord where Self: Hashable { _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), - adapter: RowAdapter? = nil) + adapter: (any RowAdapter)? = nil) throws -> Set { try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter)) @@ -446,7 +446,8 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// A cursor over fetched records. /// - /// let request: ... // Some FetchRequest that fetches Player + /// struct Player: FetchableRecord { ... } + /// let request: some FetchRequest = ... /// let players = try request.fetchCursor(db) // Cursor of Player /// while let player = try players.next() { // Player /// ... @@ -466,7 +467,8 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// An array of fetched records. /// - /// let request: ... // Some FetchRequest that fetches Player + /// struct Player: FetchableRecord { ... } + /// let request: some FetchRequest = ... /// let players = try request.fetchAll(db) // [Player] /// /// - parameter db: A database connection. @@ -478,7 +480,8 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// The first fetched record. /// - /// let request: ... // Some FetchRequest that fetches Player + /// struct Player: FetchableRecord { ... } + /// let request: some FetchRequest = ... /// let player = try request.fetchOne(db) // Player? /// /// - parameter db: A database connection. @@ -492,7 +495,8 @@ extension FetchRequest where RowDecoder: FetchableRecord { extension FetchRequest where RowDecoder: FetchableRecord & Hashable { /// A set of fetched records. /// - /// let request: ... // Some FetchRequest that fetches Player + /// struct Player: FetchableRecord, Hashable { ... } + /// let request: some FetchRequest = ... /// let players = try request.fetchSet(db) // Set /// /// - parameter db: A database connection. @@ -518,7 +522,7 @@ public final class RecordCursor: DatabaseCursor { public var _isDone = false private let row: Row // Instanciated once, reused for performance - init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { + init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws { self.statement = statement row = try Row(statement: statement).adapted(with: adapter, layout: statement) try statement.reset(withArguments: arguments) diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index a09a63995..df5408616 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -236,10 +236,7 @@ extension MutablePersistableRecord { /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database. - public func update(_ db: Database, columns: Sequence) - throws - where Sequence: Swift.Sequence, Sequence.Element: ColumnExpression - { + public func update(_ db: Database, columns: some Sequence) throws { try update(db, columns: Set(columns.map(\.name))) } @@ -250,10 +247,7 @@ extension MutablePersistableRecord { /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database. - public func update(_ db: Database, columns: Sequence) - throws - where Sequence: Swift.Sequence, Sequence.Element == String - { + public func update(_ db: Database, columns: some Sequence) throws { try update(db, columns: Set(columns)) } @@ -668,7 +662,7 @@ extension PersistableRecord { extension PersistenceContainer { /// Convenience initializer from a database connection and a record - init(_ db: Database, _ record: Record) throws { + init(_ db: Database, _ record: some EncodableRecord & TableRecord) throws { let databaseTableName = type(of: record).databaseTableName let columnCount = try db.columns(in: databaseTableName).count self.init(minimumCapacity: columnCount) diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index e1a1c882c..0334f1042 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -71,7 +71,7 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// of columns: /// /// class RestrictedPlayer : Record { - /// override static var databaseSelection: [SQLSelectable] { + /// override static var databaseSelection: [any SQLSelectable] { /// return [Column("id"), Column("name")] /// } /// } @@ -82,14 +82,14 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord { /// You can also add extra columns such as the `rowid` column: /// /// class ExtendedPlayer : Player { - /// override static var databaseSelection: [SQLSelectable] { + /// override static var databaseSelection: [any SQLSelectable] { /// return [AllColumns(), Column.rowID] /// } /// } /// /// // SELECT *, rowid FROM player /// try ExtendedPlayer.fetchAll(db) - open class var databaseSelection: [SQLSelectable] { + open class var databaseSelection: [any SQLSelectable] { [AllColumns()] } diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index c9c265042..944da1316 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -41,12 +41,12 @@ public protocol TableRecord { /// /// struct ExtendedPlayer : TableRecord { /// static var databaseTableName = "player" - /// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] + /// static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] /// } /// /// // SELECT *, rowid FROM player /// try ExtendedPlayer.fetchAll(db) - static var databaseSelection: [SQLSelectable] { get } + static var databaseSelection: [any SQLSelectable] { get } } extension TableRecord { @@ -91,7 +91,7 @@ extension TableRecord { } /// Default value: `[AllColumns()]`. - public static var databaseSelection: [SQLSelectable] { + public static var databaseSelection: [any SQLSelectable] { [AllColumns()] } } @@ -172,10 +172,7 @@ extension TableRecord { /// - db: A database connection. /// - key: A primary key value. /// - returns: Whether a row exists for this primary key. - public static func exists(_ db: Database, key: PrimaryKeyType) - throws -> Bool - where PrimaryKeyType: DatabaseValueConvertible - { + public static func exists(_ db: Database, key: some DatabaseValueConvertible) throws -> Bool { try !filter(key: key).isEmpty(db) } } @@ -217,7 +214,7 @@ extension TableRecord { /// - db: A database connection. /// - key: A dictionary of values. /// - returns: Whether a row exists for this key. - public static func exists(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool { + public static func exists(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { try !filter(key: key).isEmpty(db) } } @@ -246,9 +243,8 @@ extension TableRecord { /// - keys: A sequence of primary keys. /// - returns: The number of deleted rows @discardableResult - public static func deleteAll(_ db: Database, keys: Sequence) + public static func deleteAll(_ db: Database, keys: some Sequence) throws -> Int - where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible { let keys = Array(keys) if keys.isEmpty { @@ -278,10 +274,7 @@ extension TableRecord { /// - key: A primary key value. /// - returns: Whether a database row was deleted. @discardableResult - public static func deleteOne(_ db: Database, key: PrimaryKeyType) - throws -> Bool - where PrimaryKeyType: DatabaseValueConvertible - { + public static func deleteOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Bool { if key.databaseValue.isNull { // Don't hit the database return false @@ -312,10 +305,7 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// - ids: A collection of primary keys. /// - returns: The number of deleted rows @discardableResult - public static func deleteAll(_ db: Database, ids: Collection) - throws -> Int - where Collection: Swift.Collection, Collection.Element == ID - { + public static func deleteAll(_ db: Database, ids: some Collection) throws -> Int { if ids.isEmpty { // Avoid hitting the database return 0 @@ -361,7 +351,7 @@ extension TableRecord { /// - keys: An array of key dictionaries. /// - returns: The number of deleted rows @discardableResult - public static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int { + public static func deleteAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Int { if keys.isEmpty { // Avoid hitting the database return 0 @@ -379,7 +369,7 @@ extension TableRecord { /// - key: A dictionary of values. /// - returns: Whether a database row was deleted. @discardableResult - public static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool { + public static func deleteOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { try deleteAll(db, keys: [key]) > 0 } } diff --git a/GRDB/Utils/OrderedDictionary.swift b/GRDB/Utils/OrderedDictionary.swift index 3bd60eaf2..c4e1f0ccb 100644 --- a/GRDB/Utils/OrderedDictionary.swift +++ b/GRDB/Utils/OrderedDictionary.swift @@ -114,11 +114,10 @@ struct OrderedDictionary { return OrderedDictionary(keys: keys, dictionary: dictionary) } - mutating func merge( - _ other: S, + mutating func merge( + _ other: some Sequence<(Key, Value)>, uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows - where S: Sequence, S.Element == (Key, Value) { for (key, value) in other { if let current = self[key] { @@ -129,11 +128,10 @@ struct OrderedDictionary { } } - mutating func merge( - _ other: S, + mutating func merge( + _ other: some Sequence<(key: Key, value: Value)>, uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows - where S: Sequence, S.Element == (key: Key, value: Value) { for (key, value) in other { if let current = self[key] { @@ -144,22 +142,20 @@ struct OrderedDictionary { } } - func merging( - _ other: S, + func merging( + _ other: some Sequence<(Key, Value)>, uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows -> OrderedDictionary - where S: Sequence, S.Element == (Key, Value) { var result = self try result.merge(other, uniquingKeysWith: combine) return result } - func merging( - _ other: S, + func merging( + _ other: some Sequence<(key: Key, value: Value)>, uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows -> OrderedDictionary - where S: Sequence, S.Element == (key: Key, value: Value) { var result = self try result.merge(other, uniquingKeysWith: combine) diff --git a/GRDB/ValueObservation/DatabaseCancellable.swift b/GRDB/ValueObservation/DatabaseCancellable.swift index f58ecd2b8..079b08e9f 100644 --- a/GRDB/ValueObservation/DatabaseCancellable.swift +++ b/GRDB/ValueObservation/DatabaseCancellable.swift @@ -19,8 +19,8 @@ public class AnyDatabaseCancellable: DatabaseCancellable { /// Creates a cancellable object that forwards cancellation to the /// provided cancellable. - public convenience init(_ cancellable: DatabaseCancellable) { - var cancellable: DatabaseCancellable? = cancellable + public convenience init(_ cancellable: some DatabaseCancellable) { + var cancellable = Optional.some(cancellable) self.init { cancellable?.cancel() cancellable = nil // Release memory diff --git a/GRDB/ValueObservation/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift index 8f0bd8ab3..28cd65402 100644 --- a/GRDB/ValueObservation/SharedValueObservation.swift +++ b/GRDB/ValueObservation/SharedValueObservation.swift @@ -79,7 +79,7 @@ extension ValueObservation { /// - parameter extent: The extent of the shared database observation. /// - returns: A `SharedValueObservation` public func shared( - in reader: DatabaseReader, + in reader: some DatabaseReader, scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main), extent: SharedValueObservationExtent = .whileObserved) -> SharedValueObservation @@ -175,7 +175,7 @@ public final class SharedValueObservation { public func start( onError: @escaping (Error) -> Void, onChange: @escaping (Element) -> Void) - -> DatabaseCancellable + -> AnyDatabaseCancellable { synchronized { // Support for reentrancy: a shared immediate observation is @@ -194,7 +194,7 @@ public final class SharedValueObservation { // Side effect if needsStart { // Self retains the cancellable, so don't have the cancellable retain self. - cancellable = AnyDatabaseCancellable(startObservation( + cancellable = startObservation( // onError { [weak self] error in self?.handleError(error) @@ -202,7 +202,7 @@ public final class SharedValueObservation { // onChange { [weak self] element in self?.handleChange(element) - })) + }) } else if let result = lastResult { // Notify last result as an initial value scheduler.scheduleInitial { diff --git a/GRDB/ValueObservation/ValueConcurrentObserver.swift b/GRDB/ValueObservation/ValueConcurrentObserver.swift index 98b3f06ef..d3669c4c7 100644 --- a/GRDB/ValueObservation/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/ValueConcurrentObserver.swift @@ -191,7 +191,7 @@ final class ValueConcurrentObserver { // `WALSnapshot` class. extension ValueConcurrentObserver { // Starts the observation - func start() -> DatabaseCancellable { + func start() -> AnyDatabaseCancellable { let (notificationCallbacks, databaseAccess) = lock.synchronized { (self.notificationCallbacks, self.databaseAccess) } diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 33c11b930..edd31390b 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -55,7 +55,7 @@ enum ValueObservationTrackingMode { /// /// // Tracked Region is always the full player table /// ValueObservation.trackingConstantRegion(Player.all()) { db in ... } - case constantRegion([DatabaseRegionConvertible]) + case constantRegion([any DatabaseRegionConvertible]) /// The tracked region is constant and inferred from the fetched values. /// @@ -88,7 +88,7 @@ struct ValueObservationEvents: Refinable { typealias ValueObservationStart = ( _ onError: @escaping (Error) -> Void, _ onChange: @escaping (T) -> Void) --> DatabaseCancellable +-> AnyDatabaseCancellable extension ValueObservation: Refinable { @@ -137,12 +137,13 @@ extension ValueObservation: Refinable { /// - parameter onError: A closure that is provided eventual errors that /// happen during observation /// - parameter onChange: A closure that is provided fresh values - /// - returns: a DatabaseCancellable + /// - returns: a cancellable. public func start( - in reader: DatabaseReader, + in reader: some DatabaseReader, scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main), onError: @escaping (Error) -> Void, - onChange: @escaping (Reducer.Value) -> Void) -> DatabaseCancellable + onChange: @escaping (Reducer.Value) -> Void) + -> AnyDatabaseCancellable { let observation = self.with { $0.events.didFail = concat($0.events.didFail, onError) @@ -264,7 +265,7 @@ extension ValueObservation { /// dispatched asynchronously on the main queue. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public func values( - in reader: DatabaseReader, + in reader: some DatabaseReader, scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main), bufferingPolicy: AsyncValueObservation.BufferingPolicy = .unbounded) -> AsyncValueObservation @@ -309,7 +310,7 @@ public struct AsyncValueObservation: AsyncSequence { // the iterator. var cancellable: AnyDatabaseCancellable? let stream = AsyncThrowingStream(Element.self, bufferingPolicy: bufferingPolicy) { continuation in - cancellable = AnyDatabaseCancellable(start( + cancellable = start( // onError { error in continuation.finish(throwing: error) @@ -320,7 +321,7 @@ public struct AsyncValueObservation: AsyncSequence { // TODO: I could never see this code running. Is it needed? cancellable?.cancel() } - })) + }) continuation.onTermination = { @Sendable [weak cancellable] _ in cancellable?.cancel() } @@ -396,7 +397,7 @@ extension ValueObservation { /// - returns: A Combine publisher @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) public func publisher( - in reader: DatabaseReader, + in reader: some DatabaseReader, scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main)) -> DatabasePublishers.Value { @@ -458,7 +459,7 @@ extension DatabasePublishers { // Cancellable is not stored in self.state because we must enter the // .observing state *before* the observation starts, so that the user // can change the state even before the cancellable is known. - private var cancellable: DatabaseCancellable? + private var cancellable: AnyDatabaseCancellable? private var state: State private var lock = NSRecursiveLock() // Allow re-entrancy @@ -667,7 +668,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto { /// - parameter fetch: A function that fetches the observed value from /// the database. public static func tracking( - region: DatabaseRegionConvertible..., + region: any DatabaseRegionConvertible..., fetch: @escaping (Database) throws -> Value) -> ValueObservation> { @@ -712,7 +713,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto { /// - parameter fetch: A function that fetches the observed value from /// the database. public static func tracking( - regions: [DatabaseRegionConvertible], + regions: [any DatabaseRegionConvertible], fetch: @escaping (Database) throws -> Value) -> ValueObservation> { diff --git a/GRDB/ValueObservation/ValueObservationScheduler.swift b/GRDB/ValueObservation/ValueObservationScheduler.swift index 46c380d95..37cf5ac5f 100644 --- a/GRDB/ValueObservation/ValueObservationScheduler.swift +++ b/GRDB/ValueObservation/ValueObservationScheduler.swift @@ -4,9 +4,9 @@ import Foundation /// ValueObservationScheduler determines how `ValueObservation` notifies its /// fresh values. public class ValueObservationScheduler { - private let impl: ValueObservationSchedulerImpl + private let impl: any ValueObservationSchedulerImpl - private init(impl: ValueObservationSchedulerImpl) { + private init(impl: any ValueObservationSchedulerImpl) { self.impl = impl } diff --git a/GRDB/ValueObservation/ValueWriteOnlyObserver.swift b/GRDB/ValueObservation/ValueWriteOnlyObserver.swift index d1d114b8c..9f9b499e3 100644 --- a/GRDB/ValueObservation/ValueWriteOnlyObserver.swift +++ b/GRDB/ValueObservation/ValueWriteOnlyObserver.swift @@ -151,7 +151,7 @@ final class ValueWriteOnlyObserver DatabaseCancellable { + func start() -> AnyDatabaseCancellable { let (notificationCallbacks, writer) = lock.synchronized { (self.notificationCallbacks, self.databaseAccess?.writer) } diff --git a/README.md b/README.md index c8fb63e25..253fdfdb5 100644 --- a/README.md +++ b/README.md @@ -2741,7 +2741,7 @@ See [fetching methods](#fetching-methods) for information about the `fetchCursor ```swift protocol TableRecord { static var databaseTableName: String { get } - static var databaseSelection: [SQLSelectable] { get } + static var databaseSelection: [any SQLSelectable] { get } } ``` @@ -3638,12 +3638,12 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](Doc ```swift struct Event : TableRecord { - static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] + static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] } // When you subclass Record, you need an override: class Book : Record { - override class var databaseSelection: [SQLSelectable] { + override class var databaseSelection: [any SQLSelectable] { [AllColums(), Column.rowID] } } @@ -3893,7 +3893,7 @@ extension Place: TableRecord { } /// Arrange the selected columns and lock their order - static let databaseSelection: [SQLSelectable] = [ + static let databaseSelection: [any SQLSelectable] = [ Columns.id, Columns.title, Columns.favorite, @@ -4756,12 +4756,12 @@ The default selection for a record type is controlled by the `databaseSelection` ```swift struct RestrictedPlayer : TableRecord { static let databaseTableName = "player" - static let databaseSelection: [SQLSelectable] = [Column("id"), Column("name")] + static let databaseSelection: [any SQLSelectable] = [Column("id"), Column("name")] } struct ExtendedPlayer : TableRecord { static let databaseTableName = "player" - static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] + static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] } // SELECT id, name FROM player @@ -4771,7 +4771,7 @@ let request = RestrictedPlayer.all() let request = ExtendedPlayer.all() ``` -> :point_up: **Note**: make sure the `databaseSelection` property is explicitly declared as `[SQLSelectable]`. If it is not, the Swift compiler may silently miss the protocol requirement, resulting in sticky `SELECT *` requests. To verify your setup, see the [How do I print a request as SQL?](#how-do-i-print-a-request-as-sql) FAQ. +> :point_up: **Note**: make sure the `databaseSelection` property is explicitly declared as `[any SQLSelectable]`. If it is not, the Swift compiler may silently miss the protocol requirement, resulting in sticky `SELECT *` requests. To verify your setup, see the [How do I print a request as SQL?](#how-do-i-print-a-request-as-sql) FAQ. ## Expressions @@ -5169,7 +5169,7 @@ LIMIT ... -- 9 Such expression literals allow you to build a reusable support library of SQL functions or operators that are missing from the query interface. For example, you can define a Swift `date` function: ```swift - func date(_ value: SQLSpecificExpressible) -> SQLExpression { + func date(_ value: some SQLSpecificExpressible) -> SQLExpression { SQL("DATE(\(value))").sqlExpression } diff --git a/TODO.md b/TODO.md index 12b64e2a9..ad6c0707b 100644 --- a/TODO.md +++ b/TODO.md @@ -23,6 +23,8 @@ - [ ] Property wrapper that decodes dictionaries (but how to tell the key column?) - [X] See if SQLITE_FCNTL_DATA_VERSION could help working around the lack of snapshots in order to avoid double initial fetch of ValueObservation. Result: no, it does not look it returns values that are comparable between two distinct SQLite connections (from the initial reader, and from the writer thhat starts the observation) - [ ] Grab all FTS tokens in a string +- [ ] GRDB 6: databaseregionconvertible should return a cancellable +- [ ] RangeReplaceableCollection should have append(contentsOf: cursor) - [ ] GRDB 6: Swift 5.7 - [ ] GRDB 6: any / some - [ ] GRDB 6: primary associated types (cursor, requests, ...) diff --git a/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift b/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift index 6d312b357..aa4957c01 100644 --- a/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift @@ -31,7 +31,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { return writer } - func test(reader: DatabaseReader) throws { + func test(reader: some DatabaseReader) throws { let publisher = reader.readPublisher(value: { db in try Player.fetchCount(db) }) @@ -40,11 +40,10 @@ class DatabaseReaderReadPublisherTests : XCTestCase { XCTAssertEqual(value, 0) } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } } // MARK: - @@ -130,7 +129,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { throw XCTSkip("Combine is not available") } - func test(reader: DatabaseReader) throws { + func test(reader: some DatabaseReader) throws { let publisher = reader.readPublisher(value: { db in try Row.fetchAll(db, sql: "THIS IS NOT SQL") }) @@ -143,11 +142,10 @@ class DatabaseReaderReadPublisherTests : XCTestCase { } } - try Test(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshot() } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshot() } } // MARK: - @@ -162,7 +160,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { return writer } - func test(reader: DatabaseReader) throws { + func test(reader: some DatabaseReader) throws { let expectation = self.expectation(description: "") let semaphore = DispatchSemaphore(value: 0) let cancellable = reader @@ -181,11 +179,10 @@ class DatabaseReaderReadPublisherTests : XCTestCase { cancellable.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } } // MARK: - @@ -200,7 +197,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { return writer } - func test(reader: DatabaseReader) { + func test(reader: some DatabaseReader) { let expectation = self.expectation(description: "") let cancellable = reader .readPublisher(value: { db in @@ -219,11 +216,10 @@ class DatabaseReaderReadPublisherTests : XCTestCase { cancellable.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } } // MARK: - @@ -238,7 +234,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { return writer } - func test(reader: DatabaseReader) { + func test(reader: some DatabaseReader) { let queue = DispatchQueue(label: "test") let expectation = self.expectation(description: "") let cancellable = reader @@ -258,11 +254,10 @@ class DatabaseReaderReadPublisherTests : XCTestCase { cancellable.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } } // MARK: - @@ -272,7 +267,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { throw XCTSkip("Combine is not available") } - func test(reader: DatabaseReader) throws { + func test(reader: some DatabaseReader) throws { let publisher = reader.readPublisher(value: { db in try Player.createTable(db) }) @@ -284,11 +279,10 @@ class DatabaseReaderReadPublisherTests : XCTestCase { } } - try Test(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshot() } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshot() } } } #endif diff --git a/Tests/GRDBCombineTests/DatabaseRegionObservationPublisherTests.swift b/Tests/GRDBCombineTests/DatabaseRegionObservationPublisherTests.swift index c03c2c07a..a870a0066 100644 --- a/Tests/GRDBCombineTests/DatabaseRegionObservationPublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseRegionObservationPublisherTests.swift @@ -29,7 +29,7 @@ class DatabaseRegionObservationPublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = DatabaseRegionObservation(tracking: Player.all()) .publisher(in: writer) .tryMap(Player.fetchCount) @@ -49,10 +49,9 @@ class DatabaseRegionObservationPublisherTests : XCTestCase { XCTAssertEqual(elements, [1, 3]) } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // This is an usage test. Do the available APIs allow to prepend a @@ -71,7 +70,7 @@ class DatabaseRegionObservationPublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let expectation = self.expectation(description: "") let testSubject = PassthroughSubject() let testCancellable = testSubject @@ -108,10 +107,9 @@ class DatabaseRegionObservationPublisherTests : XCTestCase { observationCancellable.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } } #endif diff --git a/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift b/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift index 1ef238a31..4f07e7960 100644 --- a/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift @@ -31,7 +31,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { try XCTAssertEqual(writer.read(Player.fetchCount), 0) let publisher = writer.writePublisher(updates: { db in try Player(id: 1, name: "Arthur", score: 1000).insert(db) @@ -41,10 +41,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { try XCTAssertEqual(writer.read(Player.fetchCount), 1) } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - @@ -59,7 +58,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = writer.writePublisher(updates: { db -> Int in try Player(id: 1, name: "Arthur", score: 1000).insert(db) return try Player.fetchCount(db) @@ -69,10 +68,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { XCTAssertEqual(count, 1) } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - @@ -82,7 +80,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = writer.writePublisher(updates: { db in try db.execute(sql: "THIS IS NOT SQL") }) @@ -95,10 +93,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { } } - try Test(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testWritePublisherErrorRollbacksTransaction() throws { @@ -111,7 +108,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = writer.writePublisher(updates: { db in try Player(id: 1, name: "Arthur", score: 1000).insert(db) try db.execute(sql: "THIS IS NOT SQL") @@ -127,10 +124,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { XCTAssertEqual(count, 0) } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - @@ -145,7 +141,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let expectation = self.expectation(description: "") let semaphore = DispatchSemaphore(value: 0) let cancellable = writer @@ -164,10 +160,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { cancellable.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - @@ -182,7 +177,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) { + func test(writer: Writer) { let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = 2 // value + completion let cancellable = writer @@ -203,10 +198,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { cancellable.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - @@ -221,7 +215,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) { + func test(writer: Writer) { let queue = DispatchQueue(label: "test") let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = 2 // value + completion @@ -243,10 +237,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { cancellable.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - @@ -263,7 +256,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = writer .writePublisher( updates: { db in try Player(id: 1, name: "Arthur", score: 1000).insert(db) }, @@ -273,10 +266,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { XCTAssertEqual(count, 1) } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - @@ -286,7 +278,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = writer .writePublisher( updates: { _ in }, @@ -299,10 +291,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { } } - try Test(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } // MARK: - @@ -312,7 +303,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = writer.writePublisher( updates: { db in try db.execute(sql: "THIS IS NOT SQL") }, thenRead: { _, _ in XCTFail("Should not read") }) @@ -325,10 +316,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { } } - try Test(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testWriteThenReadPublisherWriteErrorRollbacksTransaction() throws { @@ -341,7 +331,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = writer.writePublisher( updates: { db in try Player(id: 1, name: "Arthur", score: 1000).insert(db) @@ -359,10 +349,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { XCTAssertEqual(count, 0) } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - @@ -374,7 +363,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = writer.writePublisher( updates: { _ in }, thenRead: { db, _ in try Row.fetchAll(db, sql: "THIS IS NOT SQL") }) @@ -387,10 +376,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { } } - try Test(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } // MARK: - Regression tests @@ -425,10 +413,9 @@ class DatabaseWriterWritePublisherTests : XCTestCase { XCTAssertEqual(count, 1) } - try Test(repeatCount: 100, test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(repeatCount: 100, test).run { try setUp(DatabaseQueue()) } + try Test(repeatCount: 100, test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(repeatCount: 100, test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } } #endif diff --git a/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift b/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift index f74294afb..eedd4afc3 100644 --- a/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift +++ b/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift @@ -31,7 +31,7 @@ class ValueObservationPublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = ValueObservation .trackingConstantRegion(Player.fetchCount) .publisher(in: writer) @@ -58,10 +58,9 @@ class ValueObservationPublisherTests : XCTestCase { } } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } func testDefaultSchedulerFirstValueIsEmittedAsynchronously() throws { @@ -74,7 +73,7 @@ class ValueObservationPublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let expectation = self.expectation(description: "") let semaphore = DispatchSemaphore(value: 0) let cancellable = ValueObservation @@ -92,10 +91,9 @@ class ValueObservationPublisherTests : XCTestCase { cancellable.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } func testDefaultSchedulerError() throws { @@ -103,7 +101,7 @@ class ValueObservationPublisherTests : XCTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = ValueObservation .trackingConstantRegion { try $0.execute(sql: "THIS IS NOT SQL") } .publisher(in: writer) @@ -117,10 +115,9 @@ class ValueObservationPublisherTests : XCTestCase { } } - try Test(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } // MARK: - Immediate Scheduler @@ -135,7 +132,7 @@ class ValueObservationPublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = ValueObservation .trackingConstantRegion(Player.fetchCount) .publisher(in: writer, scheduling: .immediate) @@ -162,10 +159,9 @@ class ValueObservationPublisherTests : XCTestCase { } } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } func testImmediateSchedulerEmitsFirstValueSynchronously() throws { @@ -178,7 +174,7 @@ class ValueObservationPublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let semaphore = DispatchSemaphore(value: 0) let testSubject = PassthroughSubject() let testCancellable = testSubject @@ -199,10 +195,9 @@ class ValueObservationPublisherTests : XCTestCase { observationCancellable.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } func testImmediateSchedulerError() throws { @@ -210,7 +205,7 @@ class ValueObservationPublisherTests : XCTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let publisher = ValueObservation .trackingConstantRegion { try $0.execute(sql: "THIS IS NOT SQL") } .publisher(in: writer, scheduling: .immediate) @@ -224,10 +219,9 @@ class ValueObservationPublisherTests : XCTestCase { } } - try Test(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } // MARK: - Demand @@ -272,7 +266,7 @@ class ValueObservationPublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let subscriber = DemandSubscriber() let expectation = self.expectation(description: "") @@ -292,10 +286,9 @@ class ValueObservationPublisherTests : XCTestCase { subscriber.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } func testDemandOneReceivesOneElement() throws { @@ -308,7 +301,7 @@ class ValueObservationPublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let subscriber = DemandSubscriber() let expectation = self.expectation(description: "") @@ -331,10 +324,9 @@ class ValueObservationPublisherTests : XCTestCase { subscriber.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } func testDemandOneDoesNotReceiveTwoElements() throws { @@ -347,7 +339,7 @@ class ValueObservationPublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let subscriber = DemandSubscriber() let expectation = self.expectation(description: "") expectation.isInverted = true @@ -374,10 +366,9 @@ class ValueObservationPublisherTests : XCTestCase { subscriber.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } func testDemandTwoReceivesTwoElements() throws { @@ -390,7 +381,7 @@ class ValueObservationPublisherTests : XCTestCase { return writer } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let subscriber = DemandSubscriber() let expectation = self.expectation(description: "") @@ -418,10 +409,9 @@ class ValueObservationPublisherTests : XCTestCase { subscriber.cancel() } - try Test(test) - .run { try setUp(DatabaseQueue()) } - .runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } - .runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } + try Test(test).run { try setUp(DatabaseQueue()) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } + try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } } // MARK: - Regression Tests diff --git a/Tests/GRDBTests/AssociationAggregateTests.swift b/Tests/GRDBTests/AssociationAggregateTests.swift index e16f00ab8..8f6338e92 100644 --- a/Tests/GRDBTests/AssociationAggregateTests.swift +++ b/Tests/GRDBTests/AssociationAggregateTests.swift @@ -43,7 +43,7 @@ private struct CustomTeamInfo: Decodable, FetchableRecord { class AssociationAggregateTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "team") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift index d68fdb353..9431170df 100644 --- a/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift @@ -47,7 +47,7 @@ extension QueryInterfaceRequest where RowDecoder == Player { /// Test support for Decodable records class AssociationBelongsToDecodableRecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "teams") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift index 8c4eb67f5..a0efecca4 100644 --- a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift @@ -49,7 +49,7 @@ private struct PlayerWithTeamName: FetchableRecord { /// Test support for FetchableRecord records class AssociationBelongsToFetchableRecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "teams") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift index 11cbaf274..8b04ac643 100644 --- a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift @@ -19,7 +19,7 @@ private struct Player: Codable, FetchableRecord, PersistableRecord { /// Test row scopes class AssociationBelongsToRowScopeTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "teams") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift index 05f2a71cf..187de9ae9 100644 --- a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift @@ -27,7 +27,7 @@ private struct ExtendedB : TableRecord { /// Test SQL generation class AssociationBelongsToSQLDerivationTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationChainRowScopesTests.swift b/Tests/GRDBTests/AssociationChainRowScopesTests.swift index 582a74456..987d4047b 100644 --- a/Tests/GRDBTests/AssociationChainRowScopesTests.swift +++ b/Tests/GRDBTests/AssociationChainRowScopesTests.swift @@ -35,7 +35,7 @@ private struct D: Codable, FetchableRecord, PersistableRecord { /// Test row scopes class AssociationChainRowScopesTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationChainSQLTests.swift b/Tests/GRDBTests/AssociationChainSQLTests.swift index e00f12776..e944fe86c 100644 --- a/Tests/GRDBTests/AssociationChainSQLTests.swift +++ b/Tests/GRDBTests/AssociationChainSQLTests.swift @@ -30,7 +30,7 @@ private struct D: TableRecord { /// Test SQL generation class AssociationChainSQLTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationHasManyOrderingTests.swift b/Tests/GRDBTests/AssociationHasManyOrderingTests.swift index a66fb3061..40cada2b6 100644 --- a/Tests/GRDBTests/AssociationHasManyOrderingTests.swift +++ b/Tests/GRDBTests/AssociationHasManyOrderingTests.swift @@ -28,7 +28,7 @@ private struct TeamWithOptionalPlayers: Decodable, FetchableRecord, Equatable { /// A usage test for ordered hasMany association class AssociationHasManyOrderingTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "team") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift b/Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift index 2db26ac54..52522c233 100644 --- a/Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift +++ b/Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift @@ -29,7 +29,7 @@ private struct TeamInfo: Decodable, FetchableRecord, Equatable { /// A usage test for ordered hasManyThrough association class AssociationHasManyThroughOrderingTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "team") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift index a1518b07a..8d24f0a37 100644 --- a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift +++ b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift @@ -27,7 +27,7 @@ private struct ExtendedB : TableRecord { /// Test SQL generation class AssociationHasOneSQLDerivationTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "a") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationHasOneThroughDecodableRecordTests.swift b/Tests/GRDBTests/AssociationHasOneThroughDecodableRecordTests.swift index ff7bb134d..dccbce7b4 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughDecodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughDecodableRecordTests.swift @@ -41,7 +41,7 @@ private struct AWithRequiredBAndOptionalC: Decodable, FetchableRecord { /// Test support for FetchableRecord records class AssociationHasOneThroughDecodableRecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") diff --git a/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift b/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift index feb415424..06ea3a483 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift @@ -78,7 +78,7 @@ private struct AWithRequiredBNameAndOptionalCName: FetchableRecord { /// Test support for FetchableRecord records class AssociationHasOneThroughFetchableRecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") diff --git a/Tests/GRDBTests/AssociationHasOneThroughRowScopeTests.swift b/Tests/GRDBTests/AssociationHasOneThroughRowScopeTests.swift index f07532c22..05981b01f 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughRowScopeTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughRowScopeTests.swift @@ -27,7 +27,7 @@ private struct C: Codable, FetchableRecord, PersistableRecord { /// Test row scopes class AssociationHasOneThroughRowscopeTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") diff --git a/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift index 1bfae259b..a9f4d9f07 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift @@ -30,7 +30,7 @@ private struct ExtendedC : TableRecord { /// Test SQL generation class AssociationHasOneThroughSQLDerivationTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") diff --git a/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift b/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift index b2782e91b..b27807b79 100644 --- a/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift @@ -45,7 +45,7 @@ private struct AWithOptionalBD: Decodable, FetchableRecord { /// Test support for Decodable records class AssociationParallelDecodableRecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationParallelRowScopesTests.swift b/Tests/GRDBTests/AssociationParallelRowScopesTests.swift index e05ab4fa3..17f9c4e57 100644 --- a/Tests/GRDBTests/AssociationParallelRowScopesTests.swift +++ b/Tests/GRDBTests/AssociationParallelRowScopesTests.swift @@ -43,7 +43,7 @@ private struct D: Codable, FetchableRecord, PersistableRecord { /// Test row scopes class AssociationParallelRowScopesTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationParallelSQLTests.swift b/Tests/GRDBTests/AssociationParallelSQLTests.swift index 15aaa7610..9c1b42562 100644 --- a/Tests/GRDBTests/AssociationParallelSQLTests.swift +++ b/Tests/GRDBTests/AssociationParallelSQLTests.swift @@ -28,7 +28,7 @@ private struct D: TableRecord { /// Test SQL generation class AssociationParallelSQLTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift index 7db9f641f..4c7635125 100644 --- a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift @@ -21,7 +21,7 @@ private struct D: TableRecord, FetchableRecord, Decodable, Equatable { } class AssociationPrefetchingCodableRecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("cola1") diff --git a/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift b/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift index 8589d33cd..6b597fe7b 100644 --- a/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingFetchableRecordTests.swift @@ -43,7 +43,7 @@ private struct D: TableRecord, FetchableRecord, Equatable { } class AssociationPrefetchingFetchableRecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("cola1") diff --git a/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift b/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift index 8d850380e..45972b0d3 100644 --- a/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift @@ -31,7 +31,7 @@ class AssociationPrefetchingObservationTests: GRDBTestCase { } } - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("cola1") diff --git a/Tests/GRDBTests/AssociationPrefetchingRowTests.swift b/Tests/GRDBTests/AssociationPrefetchingRowTests.swift index 5cab99c6d..5962b2e7b 100644 --- a/Tests/GRDBTests/AssociationPrefetchingRowTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingRowTests.swift @@ -7,7 +7,7 @@ private struct C: TableRecord { } private struct D: TableRecord { } class AssociationPrefetchingRowTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("cola1") diff --git a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift index 6ac24fd6b..140520cc4 100644 --- a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift @@ -7,7 +7,7 @@ private struct C: TableRecord { } private struct D: TableRecord { } class AssociationPrefetchingSQLTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { // A.hasMany(B) // A.hasMany(C) // B.belongsTo(A) diff --git a/Tests/GRDBTests/AssociationRowScopeSearchTests.swift b/Tests/GRDBTests/AssociationRowScopeSearchTests.swift index aa6bdf2f8..e1c05d05e 100644 --- a/Tests/GRDBTests/AssociationRowScopeSearchTests.swift +++ b/Tests/GRDBTests/AssociationRowScopeSearchTests.swift @@ -30,7 +30,7 @@ private struct D: TableRecord, FetchableRecord, Decodable { } class AssociationRowScopeSearchTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in // 1. Prepare data try db.create(table: "a") { t in diff --git a/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift index 4948224c4..7dce1d24e 100644 --- a/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift +++ b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift @@ -21,7 +21,7 @@ private struct B : TableRecord { /// user-defined table aliases, and expressions that involve several tables. class AssociationTableAliasTestsSQLTests : GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/BackupTestCase.swift b/Tests/GRDBTests/BackupTestCase.swift index bc6dba2e1..1d969c6cb 100644 --- a/Tests/GRDBTests/BackupTestCase.swift +++ b/Tests/GRDBTests/BackupTestCase.swift @@ -6,7 +6,7 @@ class BackupTestCase: GRDBTestCase { // A "user" error simply for testing purposes private struct AbandonBackupError: Error {} - private func setupBackupSource(_ writer: DatabaseWriter) throws -> Int { + private func setupBackupSource(_ writer: some DatabaseWriter) throws -> Int { try writer.write { db in try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") try db.execute(sql: "INSERT INTO items (id) VALUES (0)") @@ -22,14 +22,14 @@ class BackupTestCase: GRDBTestCase { return pageCount } - private func setupBackupDestination(_ writer: DatabaseWriter) throws { + private func setupBackupDestination(_ writer: some DatabaseWriter) throws { try writer.write { db in try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") try db.execute(sql: "INSERT INTO items (id) VALUES (1)") } } - func testDatabaseWriterBackup(from source: DatabaseWriter, to destination: DatabaseWriter) throws { + func testDatabaseWriterBackup(from source: some DatabaseWriter, to destination: some DatabaseWriter) throws { let sourceDbPageCount = try setupBackupSource(source) try setupBackupDestination(destination) @@ -80,7 +80,7 @@ class BackupTestCase: GRDBTestCase { } } - func testDatabaseBackup(from source: DatabaseWriter, to destination: DatabaseWriter) throws { + func testDatabaseBackup(from source: some DatabaseWriter, to destination: some DatabaseWriter) throws { let sourceDbPageCount = try setupBackupSource(source) try setupBackupDestination(destination) diff --git a/Tests/GRDBTests/CompilationSubClassTests.swift b/Tests/GRDBTests/CompilationSubClassTests.swift index 37ba8f720..494e099f9 100644 --- a/Tests/GRDBTests/CompilationSubClassTests.swift +++ b/Tests/GRDBTests/CompilationSubClassTests.swift @@ -10,7 +10,7 @@ private class UserRecord : Record { required init(row: Row) { super.init(row: row) } override class var databaseTableName: String { super.databaseTableName } override class var persistenceConflictPolicy: PersistenceConflictPolicy { super.persistenceConflictPolicy } - override class var databaseSelection: [SQLSelectable] { super.databaseSelection } + override class var databaseSelection: [any SQLSelectable] { super.databaseSelection } override func encode(to container: inout PersistenceContainer) { super.encode(to: &container) } override func didInsert(with rowID: Int64, for column: String?) { super.didInsert(with: rowID, for: column) } override func copy() -> Self { preconditionFailure() } diff --git a/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift b/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift index a88eb8dd7..55d929fff 100644 --- a/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift +++ b/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift @@ -91,7 +91,7 @@ class DatabaseAbortedTransactionTests : GRDBTestCase { } return dbWriter } - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { let semaphore1 = DispatchSemaphore(value: 0) let semaphore2 = DispatchSemaphore(value: 0) @@ -138,7 +138,7 @@ class DatabaseAbortedTransactionTests : GRDBTestCase { } return dbWriter } - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { let semaphore1 = DispatchSemaphore(value: 0) let semaphore2 = DispatchSemaphore(value: 0) @@ -216,7 +216,7 @@ class DatabaseAbortedTransactionTests : GRDBTestCase { } return dbWriter } - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { let semaphore1 = DispatchSemaphore(value: 0) let semaphore2 = DispatchSemaphore(value: 0) @@ -267,7 +267,7 @@ class DatabaseAbortedTransactionTests : GRDBTestCase { } return dbWriter } - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { do { try dbWriter.write { db in do { diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 1bbc2c5fa..144686272 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -4,19 +4,18 @@ import GRDB class DatabaseMigratorTests : GRDBTestCase { func testEmptyMigratorSync() throws { - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let migrator = DatabaseMigrator() try migrator.migrate(writer) } - try Test(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testEmptyMigratorAsync() throws { - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let expectation = self.expectation(description: "") let migrator = DatabaseMigrator() migrator.asyncMigrate(writer, completion: { dbResult in @@ -30,10 +29,9 @@ class DatabaseMigratorTests : GRDBTestCase { waitForExpectations(timeout: 5, handler: nil) } - try Test(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testEmptyMigratorPublisher() throws { @@ -41,21 +39,20 @@ class DatabaseMigratorTests : GRDBTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let migrator = DatabaseMigrator() let publisher = migrator.migratePublisher(writer) let recorder = publisher.record() try wait(for: recorder.single, timeout: 1) } - try Test(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testNonEmptyMigratorSync() throws { - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in try db.execute(sql: """ @@ -93,14 +90,13 @@ class DatabaseMigratorTests : GRDBTestCase { } } - try Test(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testNonEmptyMigratorAsync() throws { - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in try db.execute(sql: """ @@ -145,10 +141,9 @@ class DatabaseMigratorTests : GRDBTestCase { waitForExpectations(timeout: 5, handler: nil) } - try Test(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testNonEmptyMigratorPublisher() throws { @@ -156,7 +151,7 @@ class DatabaseMigratorTests : GRDBTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in try db.execute(sql: """ @@ -202,10 +197,9 @@ class DatabaseMigratorTests : GRDBTestCase { } } - try Test(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testEmptyMigratorPublisherIsAsynchronous() throws { @@ -213,7 +207,7 @@ class DatabaseMigratorTests : GRDBTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { let migrator = DatabaseMigrator() let expectation = self.expectation(description: "") let semaphore = DispatchSemaphore(value: 0) @@ -229,10 +223,9 @@ class DatabaseMigratorTests : GRDBTestCase { cancellable.cancel() } - try Test(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testNonEmptyMigratorPublisherIsAsynchronous() throws { @@ -240,7 +233,7 @@ class DatabaseMigratorTests : GRDBTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("first", migrate: { _ in }) let expectation = self.expectation(description: "") @@ -257,10 +250,9 @@ class DatabaseMigratorTests : GRDBTestCase { cancellable.cancel() } - try Test(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testMigratorPublisherDefaultScheduler() throws { @@ -268,7 +260,7 @@ class DatabaseMigratorTests : GRDBTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) { + func test(writer: Writer) { var migrator = DatabaseMigrator() migrator.registerMigration("first", migrate: { _ in }) let expectation = self.expectation(description: "") @@ -287,10 +279,9 @@ class DatabaseMigratorTests : GRDBTestCase { cancellable.cancel() } - try Test(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testMigratorPublisherCustomScheduler() throws { @@ -298,7 +289,7 @@ class DatabaseMigratorTests : GRDBTestCase { throw XCTSkip("Combine is not available") } - func test(writer: DatabaseWriter) { + func test(writer: Writer) { var migrator = DatabaseMigrator() migrator.registerMigration("first", migrate: { _ in }) let queue = DispatchQueue(label: "test") @@ -318,14 +309,13 @@ class DatabaseMigratorTests : GRDBTestCase { cancellable.cancel() } - try Test(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testMigrateUpTo() throws { - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("a") { db in try db.execute(sql: "CREATE TABLE a (id INTEGER PRIMARY KEY)") @@ -370,10 +360,9 @@ class DatabaseMigratorTests : GRDBTestCase { // try migrator.migrate(writer, upTo: "b") } - try Test(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try Test(test).run { try DatabaseQueue() } + try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } func testMigrationFailureTriggersRollback() throws { diff --git a/Tests/GRDBTests/DatabasePoolBackupTests.swift b/Tests/GRDBTests/DatabasePoolBackupTests.swift index 12eaac17e..c9a3287c4 100644 --- a/Tests/GRDBTests/DatabasePoolBackupTests.swift +++ b/Tests/GRDBTests/DatabasePoolBackupTests.swift @@ -4,14 +4,14 @@ class DatabasePoolBackupTests: BackupTestCase { func testDatabaseWriterBackup() throws { // SQLCipher can't backup encrypted databases: use a pristine Configuration - let source: DatabaseWriter = try makeDatabasePool(filename: "source.sqlite", configuration: Configuration()) - let destination: DatabaseWriter = try makeDatabasePool(filename: "destination.sqlite", configuration: Configuration()) + let source = try makeDatabasePool(filename: "source.sqlite", configuration: Configuration()) + let destination = try makeDatabasePool(filename: "destination.sqlite", configuration: Configuration()) try testDatabaseWriterBackup(from: source, to: destination) } func testDatabaseBackup() throws { - let source: DatabaseWriter = try makeDatabasePool(filename: "source.sqlite", configuration: Configuration()) - let destination: DatabaseWriter = try makeDatabasePool(filename: "destination.sqlite", configuration: Configuration()) + let source = try makeDatabasePool(filename: "source.sqlite", configuration: Configuration()) + let destination = try makeDatabasePool(filename: "destination.sqlite", configuration: Configuration()) try testDatabaseBackup(from: source, to: destination) } diff --git a/Tests/GRDBTests/DatabaseQueueBackupTests.swift b/Tests/GRDBTests/DatabaseQueueBackupTests.swift index 2af8fc5dc..4bc739fd2 100644 --- a/Tests/GRDBTests/DatabaseQueueBackupTests.swift +++ b/Tests/GRDBTests/DatabaseQueueBackupTests.swift @@ -4,14 +4,14 @@ class DatabaseQueueBackupTests: BackupTestCase { func testDatabaseWriterBackup() throws { // SQLCipher can't backup encrypted databases: use a pristine Configuration - let source: DatabaseWriter = try makeDatabaseQueue(filename: "source.sqlite", configuration: Configuration()) - let destination: DatabaseWriter = try makeDatabaseQueue(filename: "destination.sqlite", configuration: Configuration()) + let source = try makeDatabaseQueue(filename: "source.sqlite", configuration: Configuration()) + let destination = try makeDatabaseQueue(filename: "destination.sqlite", configuration: Configuration()) try testDatabaseWriterBackup(from: source, to: destination) } func testDatabaseBackup() throws { - let source: DatabaseWriter = try makeDatabaseQueue(filename: "source.sqlite", configuration: Configuration()) - let destination: DatabaseWriter = try makeDatabaseQueue(filename: "destination.sqlite", configuration: Configuration()) + let source = try makeDatabaseQueue(filename: "source.sqlite", configuration: Configuration()) + let destination = try makeDatabaseQueue(filename: "destination.sqlite", configuration: Configuration()) try testDatabaseBackup(from: source, to: destination) } } diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index fabe17716..d2935629b 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -5,8 +5,8 @@ class DatabaseReaderTests : GRDBTestCase { func testAnyDatabaseReader() throws { // This test passes if this code compiles. - let reader: DatabaseReader = try DatabaseQueue() - let _: DatabaseReader = AnyDatabaseReader(reader) + let dbQueue = try DatabaseQueue() + let _: any DatabaseReader = AnyDatabaseReader(dbQueue) } // MARK: - Read diff --git a/Tests/GRDBTests/DatabaseSavepointTests.swift b/Tests/GRDBTests/DatabaseSavepointTests.swift index d1235cc04..b1858773f 100644 --- a/Tests/GRDBTests/DatabaseSavepointTests.swift +++ b/Tests/GRDBTests/DatabaseSavepointTests.swift @@ -43,7 +43,7 @@ private class Observer : TransactionObserver { class DatabaseSavepointTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.execute(sql: "CREATE TABLE items (name TEXT)") } diff --git a/Tests/GRDBTests/DatabaseValueConversionTests.swift b/Tests/GRDBTests/DatabaseValueConversionTests.swift index 022977cce..dbf12b844 100644 --- a/Tests/GRDBTests/DatabaseValueConversionTests.swift +++ b/Tests/GRDBTests/DatabaseValueConversionTests.swift @@ -99,7 +99,7 @@ class DatabaseValueConversionTests : GRDBTestCase { // Datatypes In SQLite Version 3: https://www.sqlite.org/datatype3.html - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index eda69a5cd..8f2e4b1e3 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -40,7 +40,7 @@ class DatabaseWriterTests : GRDBTestCase { } func testAsyncWriteWithoutTransactionSuccess() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { let expectation = self.expectation(description: "updates") let semaphore = DispatchSemaphore(value: 0) dbWriter.asyncWriteWithoutTransaction { db in @@ -65,7 +65,7 @@ class DatabaseWriterTests : GRDBTestCase { } func testAsyncWriteWithoutTransactionError() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { let expectation = self.expectation(description: "updates") let semaphore = DispatchSemaphore(value: 0) dbWriter.asyncWriteWithoutTransaction { db in @@ -90,7 +90,7 @@ class DatabaseWriterTests : GRDBTestCase { } func testAsyncWriteSuccess() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { let expectation = self.expectation(description: "updates") let semaphore = DispatchSemaphore(value: 0) dbWriter.asyncWrite({ db in @@ -119,7 +119,7 @@ class DatabaseWriterTests : GRDBTestCase { } func testAsyncWriteError() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { let expectation = self.expectation(description: "updates") let semaphore = DispatchSemaphore(value: 0) dbWriter.asyncWrite({ db in @@ -150,8 +150,8 @@ class DatabaseWriterTests : GRDBTestCase { func testAnyDatabaseWriter() throws { // This test passes if this code compiles. - let writer: DatabaseWriter = try DatabaseQueue() - let _: DatabaseWriter = AnyDatabaseWriter(writer) + let dbQueue = try DatabaseQueue() + let _: any DatabaseWriter = AnyDatabaseWriter(dbQueue) } func testEraseAndVacuum() throws { @@ -159,7 +159,7 @@ class DatabaseWriterTests : GRDBTestCase { try testEraseAndVacuum(writer: makeDatabasePool()) } - private func testEraseAndVacuum(writer: DatabaseWriter) throws { + private func testEraseAndVacuum(writer: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("init") { db in // Create a database with recursive constraints, so that we test @@ -203,7 +203,7 @@ class DatabaseWriterTests : GRDBTestCase { throw XCTSkip("VACUUM INTO is not available") } - func testVacuumInto(writer: DatabaseWriter) throws { + func testVacuumInto(writer: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("init") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/FTS3PatternTests.swift b/Tests/GRDBTests/FTS3PatternTests.swift index 2e79a0f5c..0bcbb5638 100644 --- a/Tests/GRDBTests/FTS3PatternTests.swift +++ b/Tests/GRDBTests/FTS3PatternTests.swift @@ -3,7 +3,7 @@ import GRDB class FTS3PatternTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(virtualTable: "books", using: FTS3()) { t in t.column("title") diff --git a/Tests/GRDBTests/FTS3RecordTests.swift b/Tests/GRDBTests/FTS3RecordTests.swift index 6f25c8aa0..6baea9ffd 100644 --- a/Tests/GRDBTests/FTS3RecordTests.swift +++ b/Tests/GRDBTests/FTS3RecordTests.swift @@ -34,7 +34,7 @@ extension Book : MutablePersistableRecord { } class FTS3RecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(virtualTable: "books", using: FTS3()) { t in t.column("title") diff --git a/Tests/GRDBTests/FTS4RecordTests.swift b/Tests/GRDBTests/FTS4RecordTests.swift index 34690bd73..f23a989b7 100644 --- a/Tests/GRDBTests/FTS4RecordTests.swift +++ b/Tests/GRDBTests/FTS4RecordTests.swift @@ -34,7 +34,7 @@ extension Book : MutablePersistableRecord { } class FTS4RecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(virtualTable: "books", using: FTS4()) { t in t.column("title") diff --git a/Tests/GRDBTests/FTS5PatternTests.swift b/Tests/GRDBTests/FTS5PatternTests.swift index ec9478c29..fc7e1a0bf 100644 --- a/Tests/GRDBTests/FTS5PatternTests.swift +++ b/Tests/GRDBTests/FTS5PatternTests.swift @@ -4,7 +4,7 @@ import GRDB class FTS5PatternTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(virtualTable: "books", using: FTS5()) { t in t.column("title") diff --git a/Tests/GRDBTests/FTS5RecordTests.swift b/Tests/GRDBTests/FTS5RecordTests.swift index c9068f829..8ebc2804a 100644 --- a/Tests/GRDBTests/FTS5RecordTests.swift +++ b/Tests/GRDBTests/FTS5RecordTests.swift @@ -35,7 +35,7 @@ extension Book : MutablePersistableRecord { } class FTS5RecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(virtualTable: "books", using: FTS5()) { t in t.column("title") diff --git a/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift index 52004ac3e..4d19279bf 100644 --- a/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift @@ -46,7 +46,7 @@ extension AltReader : FetchableRecord { class FetchableRecordQueryInterfaceRequestTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createReaders") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/FoundationDateComponentsTests.swift b/Tests/GRDBTests/FoundationDateComponentsTests.swift index 4d16d0979..176145e90 100644 --- a/Tests/GRDBTests/FoundationDateComponentsTests.swift +++ b/Tests/GRDBTests/FoundationDateComponentsTests.swift @@ -3,7 +3,7 @@ import GRDB class FoundationDateComponentsTests : GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createDates") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/FoundationDateTests.swift b/Tests/GRDBTests/FoundationDateTests.swift index 16a1038b2..553cf2e11 100644 --- a/Tests/GRDBTests/FoundationDateTests.swift +++ b/Tests/GRDBTests/FoundationDateTests.swift @@ -3,7 +3,7 @@ import GRDB class FoundationDateTests : GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createDates") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/FoundationNSDateTests.swift b/Tests/GRDBTests/FoundationNSDateTests.swift index f7405715d..d00dbc3c6 100644 --- a/Tests/GRDBTests/FoundationNSDateTests.swift +++ b/Tests/GRDBTests/FoundationNSDateTests.swift @@ -3,7 +3,7 @@ import GRDB class FoundationNSDateTests : GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createDates") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 62c981b14..a81ab226a 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -49,7 +49,7 @@ class GRDBTestCase: XCTestCase { // Subclasses can override // Default implementation is empty. - func setup(_ dbWriter: DatabaseWriter) throws { + func setup(_ dbWriter: some DatabaseWriter) throws { } // The default path for database pool directory @@ -133,7 +133,7 @@ class GRDBTestCase: XCTestCase { XCTAssertTrue(sqlQueries.contains(sql), "Did not execute \(sql)", file: file, line: line) } - func assert(_ record: EncodableRecord, isEncodedIn row: Row, file: StaticString = #filePath, line: UInt = #line) { + func assert(_ record: some EncodableRecord, isEncodedIn row: Row, file: StaticString = #filePath, line: UInt = #line) { let recordDict = record.databaseDictionary let rowDict = Dictionary(row, uniquingKeysWith: { (left, _) in left }) XCTAssertEqual(recordDict, rowDict, file: file, line: line) diff --git a/Tests/GRDBTests/JoinSupportTests.swift b/Tests/GRDBTests/JoinSupportTests.swift index 28bd96f17..ed676751f 100644 --- a/Tests/GRDBTests/JoinSupportTests.swift +++ b/Tests/GRDBTests/JoinSupportTests.swift @@ -198,7 +198,7 @@ private struct CodableNestedModel: FetchableRecord, Codable { class JoinSupportTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "t1") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift index f7b504584..a069f292d 100644 --- a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift @@ -29,7 +29,7 @@ private struct Player: FetchableRecord, MutablePersistableRecord, Codable { } class MutablePersistableRecordChangesTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "players") { t in t.column("id", .integer).primaryKey() diff --git a/Tests/GRDBTests/MutablePersistableRecordTests.swift b/Tests/GRDBTests/MutablePersistableRecordTests.swift index 11eefc9c9..fd7e0708c 100644 --- a/Tests/GRDBTests/MutablePersistableRecordTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordTests.swift @@ -86,7 +86,7 @@ private struct MutablePersistableRecordCustomizedCountry : MutablePersistableRec class MutablePersistableRecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("setUp") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/PersistableRecordTests.swift b/Tests/GRDBTests/PersistableRecordTests.swift index ff7f15316..deb80f7ef 100644 --- a/Tests/GRDBTests/PersistableRecordTests.swift +++ b/Tests/GRDBTests/PersistableRecordTests.swift @@ -106,7 +106,7 @@ private struct Citizenship : PersistableRecord { class PersistableRecordTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("setUp") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index dee5bd5f7..7097c6fe1 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -32,7 +32,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { } } - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createReaders") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/QueryInterfacePromiseTests.swift b/Tests/GRDBTests/QueryInterfacePromiseTests.swift index 389dfde09..1cd1c14de 100644 --- a/Tests/GRDBTests/QueryInterfacePromiseTests.swift +++ b/Tests/GRDBTests/QueryInterfacePromiseTests.swift @@ -10,7 +10,7 @@ private struct NotARecord { } // Here we test that filter(key:), orderByPrimaryKey(), and groupByPrimaryKey() // don't forget their table when the request type is changed. class QueryInterfacePromiseTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "node") { t in t.autoIncrementedPrimaryKey("id") diff --git a/Tests/GRDBTests/QueryInterfaceRequestTests.swift b/Tests/GRDBTests/QueryInterfaceRequestTests.swift index 1be985ede..fa3c35f1c 100644 --- a/Tests/GRDBTests/QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/QueryInterfaceRequestTests.swift @@ -26,7 +26,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { } } - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createReaders") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/RawRepresentable+DatabaseValueConvertibleTests.swift b/Tests/GRDBTests/RawRepresentable+DatabaseValueConvertibleTests.swift index 0d1801a28..7dfdfb171 100644 --- a/Tests/GRDBTests/RawRepresentable+DatabaseValueConvertibleTests.swift +++ b/Tests/GRDBTests/RawRepresentable+DatabaseValueConvertibleTests.swift @@ -60,7 +60,7 @@ extension FastWrapper: StatementColumnConvertible where RawValue: StatementColum class RawRepresentableDatabaseValueConvertibleTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in try db.execute(sql: "CREATE TABLE wines (grape TEXT, color INTEGER)") diff --git a/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift index f3ca0b73b..fc78aec09 100644 --- a/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift @@ -38,7 +38,7 @@ private class Reader : Record { class RecordQueryInterfaceRequestTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createReaders") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/RecordEditedTests.swift b/Tests/GRDBTests/RecordEditedTests.swift index 535e4bafc..4c1dae91c 100644 --- a/Tests/GRDBTests/RecordEditedTests.swift +++ b/Tests/GRDBTests/RecordEditedTests.swift @@ -131,7 +131,7 @@ private class PersonWithModifiedCaseColumns: Record { class RecordEditedTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPerson", migrate: Person.setup) try migrator.migrate(dbWriter) diff --git a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift index 51df91e5d..97bdbddd7 100644 --- a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift @@ -46,7 +46,7 @@ extension MinimalNonOptionalPrimaryKeySingle: Identifiable { } class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createMinimalNonOptionalPrimaryKeySingle", migrate: MinimalNonOptionalPrimaryKeySingle.setup) try migrator.migrate(dbWriter) diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index c7bb89bc5..98a557ac6 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -49,7 +49,7 @@ extension MinimalRowID: Identifiable { } class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createMinimalRowID", migrate: MinimalRowID.setup) try migrator.migrate(dbWriter) diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift index cae1f356c..8fba71a17 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift @@ -47,7 +47,7 @@ extension MinimalSingle: Identifiable { class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createMinimalSingle", migrate: MinimalSingle.setup) try migrator.migrate(dbWriter) diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index 73553f6ff..8c2487690 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -83,7 +83,7 @@ extension Person: Identifiable { } class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPerson", migrate: Person.setup) try migrator.migrate(dbWriter) diff --git a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift index 79835ab01..ac74dda2f 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift @@ -59,7 +59,7 @@ private class Citizenship : Record, Hashable { class RecordPrimaryKeyMultipleTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createCitizenship", migrate: Citizenship.setup) try migrator.migrate(dbWriter) diff --git a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift index c114bfe30..969b8dab8 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift @@ -55,7 +55,7 @@ private class Item : Record, Hashable { class RecordPrimaryKeyNoneTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createItem", migrate: Item.setup) try migrator.migrate(dbWriter) diff --git a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift index d3639adca..8ffc8c00c 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift @@ -77,7 +77,7 @@ private class Person : Record, Hashable { class RecordPrimaryKeyRowIDTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPerson", migrate: Person.setup) try migrator.migrate(dbWriter) diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift index 53686dd82..3ae89c19a 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift @@ -49,7 +49,7 @@ class Pet : Record, Hashable { class RecordPrimaryKeySingleTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPet", migrate: Pet.setup) try migrator.migrate(dbWriter) diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift index 110cde402..5ee5efc71 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift @@ -48,7 +48,7 @@ class Email : Record, Hashable { class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createEmail", migrate: Email.setup) try migrator.migrate(dbWriter) diff --git a/Tests/GRDBTests/RecordSubClassTests.swift b/Tests/GRDBTests/RecordSubClassTests.swift index ff707813f..73f3fded2 100644 --- a/Tests/GRDBTests/RecordSubClassTests.swift +++ b/Tests/GRDBTests/RecordSubClassTests.swift @@ -104,7 +104,7 @@ private class PersonWithOverrides : Person { class RecordSubClassTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPerson", migrate: Person.setup) try migrator.migrate(dbWriter) diff --git a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift index decaff676..3b2c05b36 100644 --- a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift +++ b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift @@ -45,7 +45,7 @@ class BadlyMangledStuff : Record { class RecordWithColumnNameManglingTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createBadlyMangledStuff", migrate: BadlyMangledStuff.setup) try migrator.migrate(dbWriter) diff --git a/Tests/GRDBTests/SQLRequestTests.swift b/Tests/GRDBTests/SQLRequestTests.swift index 58bcaa11c..104cadc28 100644 --- a/Tests/GRDBTests/SQLRequestTests.swift +++ b/Tests/GRDBTests/SQLRequestTests.swift @@ -125,7 +125,7 @@ class SQLRequestTests: GRDBTestCase { """ } - static func filter(excludedIds: S) -> SQLRequest where S: Sequence, S.Element == Int64 { + static func filter(excludedIds: some Sequence) -> SQLRequest { """ SELECT * FROM \(self) diff --git a/Tests/GRDBTests/SelectStatementTests.swift b/Tests/GRDBTests/SelectStatementTests.swift index b03d8560e..a71576d4b 100644 --- a/Tests/GRDBTests/SelectStatementTests.swift +++ b/Tests/GRDBTests/SelectStatementTests.swift @@ -3,7 +3,7 @@ import XCTest class SelectStatementTests : GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/StatementArguments+FoundationTests.swift b/Tests/GRDBTests/StatementArguments+FoundationTests.swift index 812f625c8..61ec4b075 100644 --- a/Tests/GRDBTests/StatementArguments+FoundationTests.swift +++ b/Tests/GRDBTests/StatementArguments+FoundationTests.swift @@ -6,7 +6,7 @@ private class NonDatabaseConvertibleObject: NSObject class StatementArgumentsFoundationTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/StatementArgumentsTests.swift b/Tests/GRDBTests/StatementArgumentsTests.swift index aa00fcf47..de0ab55ae 100644 --- a/Tests/GRDBTests/StatementArgumentsTests.swift +++ b/Tests/GRDBTests/StatementArgumentsTests.swift @@ -3,7 +3,7 @@ import GRDB class StatementArgumentsTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift index f30015da6..3553cec4c 100644 --- a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift @@ -14,7 +14,7 @@ private struct Reader : TableRecord { class TableRecordQueryInterfaceRequestTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createReaders") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/TableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift index a04d3e9ca..167f95dae 100644 --- a/Tests/GRDBTests/TableRecordDeleteTests.swift +++ b/Tests/GRDBTests/TableRecordDeleteTests.swift @@ -24,7 +24,7 @@ private struct Citizenship : TableRecord { class TableRecordDeleteTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.execute(sql: "CREATE TABLE hackers (name TEXT)") try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)") diff --git a/Tests/GRDBTests/UpdateStatementTests.swift b/Tests/GRDBTests/UpdateStatementTests.swift index 401977207..4834bf0d7 100644 --- a/Tests/GRDBTests/UpdateStatementTests.swift +++ b/Tests/GRDBTests/UpdateStatementTests.swift @@ -3,7 +3,7 @@ import GRDB class UpdateStatementTests : GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { + override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in try db.execute(sql: """ diff --git a/Tests/GRDBTests/ValueObservationPrintTests.swift b/Tests/GRDBTests/ValueObservationPrintTests.swift index 8108fa296..35f6da8cd 100644 --- a/Tests/GRDBTests/ValueObservationPrintTests.swift +++ b/Tests/GRDBTests/ValueObservationPrintTests.swift @@ -28,7 +28,7 @@ class ValueObservationPrintTests: GRDBTestCase { try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") } - func test(_ dbReader: DatabaseReader) throws { + func test(_ dbReader: some DatabaseReader) throws { let logger = TestStream() let observation = ValueObservation .trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } @@ -62,7 +62,7 @@ class ValueObservationPrintTests: GRDBTestCase { try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") } - func test(_ dbReader: DatabaseReader) throws { + func test(_ dbReader: some DatabaseReader) throws { let logger = TestStream() let observation = ValueObservation .trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } @@ -91,10 +91,10 @@ class ValueObservationPrintTests: GRDBTestCase { } func test_readonly_failure_asynchronousScheduling() throws { + struct TestError: Error { } _ = try makeDatabasePool(filename: "test") - func test(_ dbReader: DatabaseReader) throws { - struct TestError: Error { } + func test(_ dbReader: some DatabaseReader) throws { let logger = TestStream() let observation = ValueObservation .trackingConstantRegion { _ in throw TestError() } @@ -123,10 +123,10 @@ class ValueObservationPrintTests: GRDBTestCase { } func test_readonly_failure_immediateScheduling() throws { + struct TestError: Error { } _ = try makeDatabasePool(filename: "test") - func test(_ dbReader: DatabaseReader) throws { - struct TestError: Error { } + func test(_ dbReader: some DatabaseReader) throws { let logger = TestStream() let observation = ValueObservation .trackingConstantRegion { _ in throw TestError() } @@ -157,7 +157,7 @@ class ValueObservationPrintTests: GRDBTestCase { // MARK: - Writeonly func test_writeonly_success_asynchronousScheduling() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") } @@ -199,7 +199,7 @@ class ValueObservationPrintTests: GRDBTestCase { } func test_writeonly_success_immediateScheduling() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") } @@ -241,7 +241,7 @@ class ValueObservationPrintTests: GRDBTestCase { } func test_writeonly_immediateFailure_asynchronousScheduling() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { let logger = TestStream() var observation = ValueObservation .trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } @@ -268,7 +268,7 @@ class ValueObservationPrintTests: GRDBTestCase { } func test_writeonly_immediateFailure_immediateScheduling() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { let logger = TestStream() var observation = ValueObservation .trackingConstantRegion { try Int.fetchOne($0, sql: "SELECT MAX(id) FROM player") } @@ -295,7 +295,7 @@ class ValueObservationPrintTests: GRDBTestCase { } func test_writeonly_lateFailure_asynchronousScheduling() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") } @@ -338,7 +338,7 @@ class ValueObservationPrintTests: GRDBTestCase { } func test_writeonly_lateFailure_immediateScheduling() throws { - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.execute(sql: "CREATE TABLE player(id INTEGER PRIMARY KEY)") } diff --git a/Tests/GRDBTests/ValueObservationRecorder.swift b/Tests/GRDBTests/ValueObservationRecorder.swift index 9cfad00dc..70ba5caae 100644 --- a/Tests/GRDBTests/ValueObservationRecorder.swift +++ b/Tests/GRDBTests/ValueObservationRecorder.swift @@ -174,12 +174,12 @@ public class ValueObservationRecorder { } } - fileprivate func receive(_ cancellable: DatabaseCancellable) { + fileprivate func receive(_ cancellable: AnyDatabaseCancellable) { synchronized { if state.cancellable != nil { XCTFail("ValueObservationRecorder is already observing") } - state.cancellable = AnyDatabaseCancellable(cancellable) + state.cancellable = cancellable } } } @@ -218,7 +218,7 @@ extension ValueObservationRecorder { extension ValueObservation { public func record( - in reader: DatabaseReader, + in reader: some DatabaseReader, scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main), onError: ((Error) -> Void)? = nil, onChange: ((Reducer.Value) -> Void)? = nil) @@ -367,7 +367,7 @@ extension GRDBTestCase { scheduling scheduler: ValueObservationScheduler, testValueDispatching: @escaping () -> Void) throws { - func testRecordingEqualWhenWriteAfterStart(writer: DatabaseWriter) throws { + func testRecordingEqualWhenWriteAfterStart(writer: some DatabaseWriter) throws { try writer.write(setup) var value: Reducer.Value? @@ -394,7 +394,7 @@ extension GRDBTestCase { "\(#function), \(writer), \(scheduler)", file: file, line: line) } - func testRecordingEqualWhenWriteAfterFirstValue(writer: DatabaseWriter) throws { + func testRecordingEqualWhenWriteAfterFirstValue(writer: some DatabaseWriter) throws { try writer.write(setup) var valueCount = 0 @@ -424,7 +424,7 @@ extension GRDBTestCase { "\(#function), \(writer), \(scheduler)", file: file, line: line) } - func testRecordingMatchWhenWriteAfterStart(writer: DatabaseWriter) throws { + func testRecordingMatchWhenWriteAfterStart(writer: some DatabaseWriter) throws { try writer.write(setup) var value: Reducer.Value? @@ -469,7 +469,7 @@ extension GRDBTestCase { "\(#function), \(writer), \(scheduler)", file: file, line: line) } - func testRecordingMatchWhenWriteAfterFirstValue(writer: DatabaseWriter) throws { + func testRecordingMatchWhenWriteAfterFirstValue(writer: some DatabaseWriter) throws { try writer.write(setup) var valueCount = 0 @@ -577,7 +577,7 @@ extension GRDBTestCase { scheduling scheduler: ValueObservationScheduler, testErrorDispatching: @escaping () -> Void) throws { - func test(writer: DatabaseWriter) throws { + func test(writer: some DatabaseWriter) throws { try writer.write(setup) let recorder = observation.record( diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index 5966543b3..b29b5d8b7 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -4,9 +4,10 @@ import Dispatch class ValueObservationTests: GRDBTestCase { func testImmediateError() throws { - func test(_ dbWriter: DatabaseWriter) throws { + struct TestError: Error { } + + func test(_ dbWriter: some DatabaseWriter) throws { // Create an observation - struct TestError: Error { } let observation = ValueObservation.trackingConstantRegion { _ in throw TestError() } // Start observation @@ -24,7 +25,9 @@ class ValueObservationTests: GRDBTestCase { } func testErrorCompletesTheObservation() throws { - func test(_ dbWriter: DatabaseWriter) throws { + struct TestError: Error { } + + func test(_ dbWriter: some DatabaseWriter) throws { // We need something to change try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -34,7 +37,6 @@ class ValueObservationTests: GRDBTestCase { notificationExpectation.expectedFulfillmentCount = 4 notificationExpectation.isInverted = true - struct TestError: Error { } var nextError: Error? = nil // If not null, observation throws an error let observation = ValueObservation.trackingConstantRegion { _ = try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t") @@ -589,7 +591,7 @@ class ValueObservationTests: GRDBTestCase { func testCancellableInvalidation1() throws { // Test that observation stops when cancellable is deallocated - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } let notificationExpectation = expectation(description: "notification") @@ -633,7 +635,7 @@ class ValueObservationTests: GRDBTestCase { func testCancellableInvalidation2() throws { // Test that observation stops when cancellable is deallocated - func test(_ dbWriter: DatabaseWriter) throws { + func test(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } let notificationExpectation = expectation(description: "notification") @@ -677,7 +679,7 @@ class ValueObservationTests: GRDBTestCase { } func testIssue1209() throws { - func test(_ dbWriter: Writer) throws { + func test(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -729,7 +731,7 @@ class ValueObservationTests: GRDBTestCase { @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func testAsyncAwait_values_prefix() async throws { - func test(writer: DatabaseWriter) async throws { + func test(_ writer: some DatabaseWriter) async throws { // We need something to change try await writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -756,15 +758,14 @@ class ValueObservationTests: GRDBTestCase { wait(for: [cancellationExpectation], timeout: 2) } - try await AsyncTest(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try await AsyncTest(test).run { try DatabaseQueue() } + try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func testAsyncAwait_values_prefix_immediate_scheduling() async throws { - func test(writer: DatabaseWriter) async throws { + func test(_ writer: some DatabaseWriter) async throws { // We need something to change try await writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -791,15 +792,14 @@ class ValueObservationTests: GRDBTestCase { wait(for: [cancellationExpectation], timeout: 2) } - try await AsyncTest(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try await AsyncTest(test).run { try DatabaseQueue() } + try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func testAsyncAwait_values_break() async throws { - func test(writer: DatabaseWriter) async throws { + func test(_ writer: some DatabaseWriter) async throws { // We need something to change try await writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -830,15 +830,14 @@ class ValueObservationTests: GRDBTestCase { wait(for: [cancellationExpectation], timeout: 2) } - try await AsyncTest(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try await AsyncTest(test).run { try DatabaseQueue() } + try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func testAsyncAwait_values_immediate_break() async throws { - func test(writer: DatabaseWriter) async throws { + func test(_ writer: some DatabaseWriter) async throws { // We need something to change try await writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -866,15 +865,14 @@ class ValueObservationTests: GRDBTestCase { wait(for: [cancellationExpectation], timeout: 2) } - try await AsyncTest(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try await AsyncTest(test).run { try DatabaseQueue() } + try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) func testAsyncAwait_values_cancelled() async throws { - func test(writer: DatabaseWriter) async throws { + func test(_ writer: some DatabaseWriter) async throws { // We need something to change try await writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -914,9 +912,8 @@ class ValueObservationTests: GRDBTestCase { wait(for: [cancellationExpectation], timeout: 2) } - try await AsyncTest(test) - .run { try DatabaseQueue() } - .runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - .runAtTemporaryDatabasePath { try DatabasePool(path: $0) } + try await AsyncTest(test).run { try DatabaseQueue() } + try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } + try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } }