diff --git a/CHANGELOG.md b/CHANGELOG.md index 62c0edeb6..281d48413 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1731,7 +1731,7 @@ The [Advanced DatabasePool](README.md#advanced-databasepool) chapter has been ex ```diff class DatabasePool { -+ func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T ++ func barrierWriteWithoutTransaction(_ updates: (DatabaseBase) throws -> T) rethrows -> T + func invalidateReadOnlyConnections() } @@ -1851,7 +1851,7 @@ The [ValueObservation](README.md#valueobservation) chapter has been updated so t } extension ValueObservation where Reducer == Void { -+ static func tracking(fetch: @escaping (Database) throws -> Value) -> ValueObservation> ++ static func tracking(fetch: @escaping (DatabaseBase) throws -> Value) -> ValueObservation> } ``` @@ -1896,7 +1896,7 @@ The [ValueObservation Error Handling](README.md#valueobservation-error-handling) + var configuration: Configuration { get } + + #if compiler(>=5.0) -+ func asyncRead(_ block: @escaping (Result) -> Void) ++ func asyncRead(_ block: @escaping (Result, Error>) -> Void) + #endif } @@ -1904,7 +1904,7 @@ The [ValueObservation Error Handling](README.md#valueobservation-error-handling) + func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) + + #if compiler(>=5.0) -+ func asyncWrite(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result) -> Void) ++ func asyncWrite(_ updates: @escaping (DatabaseBase) throws -> T, completion: @escaping (Database, Result) -> Void) + #endif } ``` @@ -1984,8 +1984,8 @@ The [ValueObservation Error Handling](README.md#valueobservation-error-handling) protocol FetchRequest { + // deprecated - func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) -+ func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest + func prepare(_ db: DatabaseBase, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) ++ func makePreparedRequest(_ db: DatabaseBase, forSingleResult singleResult: Bool) throws -> PreparedRequest } ``` @@ -2189,37 +2189,37 @@ It comes with new features, but also a few breaking changes. The [GRDB 4 Migrati } class Row { -- static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor -- static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] -- static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? -+ static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RowCursor -+ static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Row] -+ static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Row? +- static func fetchCursor(_ db: DatabaseBase, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor +- static func fetchAll(_ db: DatabaseBase, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] +- static func fetchOne(_ db: DatabaseBase, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? ++ static func fetchCursor(_ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RowCursor ++ static func fetchAll(_ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Row] ++ static func fetchOne(_ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Row? } extension FetchableRecord { -- static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor -- static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] -- static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? -+ static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RecordCursor -+ static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] -+ static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? +- static func fetchCursor(_ db: DatabaseBase, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor +- static func fetchAll(_ db: DatabaseBase, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] +- static func fetchOne(_ db: DatabaseBase, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? ++ static func fetchCursor(_ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RecordCursor ++ static func fetchAll(_ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] ++ static func fetchOne(_ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? } extension DatabaseValueConvertible { -- static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor -- static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] -- static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? -+ static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DatabaseValueCursor -+ static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] -+ static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? +- static func fetchCursor(_ db: DatabaseBase, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor +- static func fetchAll(_ db: DatabaseBase, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] +- static func fetchOne(_ db: DatabaseBase, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? ++ static func fetchCursor(_ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DatabaseValueCursor ++ static func fetchAll(_ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] ++ static func fetchOne(_ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? } extension Optional where Wrapped: DatabaseValueConvertible { -- static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor -- static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] -+ static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor -+ static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?] +- static func fetchCursor(_ db: DatabaseBase, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor +- static func fetchAll(_ db: DatabaseBase, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] ++ static func fetchCursor(_ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor ++ static func fetchAll(_ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?] } extension TableRecord { @@ -2324,7 +2324,7 @@ It comes with new features, but also a few breaking changes. The [GRDB 4 Migrati struct ValueObservation { - var extent: Database.TransactionObservationExtent - static func tracking(_ regions: DatabaseRegionConvertible..., reducer: Reducer) -> ValueObservation -- static func tracking(_ regions: DatabaseRegionConvertible..., fetchDistinct fetch: @escaping (Database) throws -> Value) -> ValueObservation>> where Value: Equatable +- static func tracking(_ regions: DatabaseRegionConvertible..., fetchDistinct fetch: @escaping (DatabaseBase) throws -> Value) -> ValueObservation>> where Value: Equatable } ``` @@ -2467,12 +2467,12 @@ It comes with new features, but also a few breaking changes. The [GRDB 4 Migrati + class DatabaseFuture { } protocol FetchRequest { -- func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) -+ func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) +- func prepare(_ db: DatabaseBase) throws -> (SelectStatement, RowAdapter?) ++ func prepare(_ db: DatabaseBase, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) } struct AnyFetchRequest : FetchRequest { -- init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) +- init(_ prepare: @escaping (DatabaseBase) throws -> (SelectStatement, RowAdapter?)) + init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?)) } @@ -2595,24 +2595,24 @@ This release comes with: } extension MutablePersistableRecord { -+ mutating func updateChanges(_ db: Database, with change: (inout Self) throws -> Void) throws -> Bool ++ mutating func updateChanges(_ db: DatabaseBase, with change: (inout Self) throws -> Void) throws -> Bool } extension PersistableRecord { -+ func updateChanges(_ db: Database, with change: (Self) throws -> Void) throws -> Bool ++ func updateChanges(_ db: DatabaseBase, with change: (Self) throws -> Void) throws -> Bool } struct ValueObservation { + static func tracking( + _ regions: [DatabaseRegionConvertible], -+ reducer: @escaping (Database) throws -> Reducer) ++ reducer: @escaping (DatabaseBase) throws -> Reducer) + -> ValueObservation } +extension ValueObservation where Reducer == Void { + static func tracking( + _ regions: [DatabaseRegionConvertible], -+ fetch: @escaping (Database) throws -> Value) ++ fetch: @escaping (DatabaseBase) throws -> Value) + -> ValueObservation> + static func combine(_ o1: ValueObservation, ...) + -> ValueObservation<...> @@ -2697,13 +2697,13 @@ It used to be possible to define custom types that adopt the [DatabaseReader and } +protocol DatabaseRegionConvertible { -+ func databaseRegion(_ db: Database) throws -> DatabaseRegion ++ func databaseRegion(_ db: DatabaseBase) throws -> DatabaseRegion +} + +extension DatabaseRegion: DatabaseRegionConvertible { } + +struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible { -+ init(_ region: @escaping (Database) throws -> DatabaseRegion) ++ init(_ region: @escaping (DatabaseBase) throws -> DatabaseRegion) + init(_ region: DatabaseRegionConvertible) +} @@ -2719,7 +2719,7 @@ It used to be possible to define custom types that adopt the [DatabaseReader and +protocol ValueReducer { + associatedtype Fetched + associatedtype Value -+ func fetch(_ db: Database) throws -> Fetched ++ func fetch(_ db: DatabaseBase) throws -> Fetched + mutating func value(_ fetched: Fetched) -> Value? +} + @@ -2728,7 +2728,7 @@ It used to be possible to define custom types that adopt the [DatabaseReader and +} + +struct AnyValueReducer: ValueReducer { -+ init(fetch: @escaping (Database) throws -> Fetched, value: @escaping (Fetched) -> Value?) ++ init(fetch: @escaping (DatabaseBase) throws -> Fetched, value: @escaping (Fetched) -> Value?) + init(_ reducer: Reducer) where Reducer.Fetched == Fetched, Reducer.Value == Value +} @@ -2751,12 +2751,12 @@ It used to be possible to define custom types that adopt the [DatabaseReader and +extension ValueObservation where Reducer == Void { + static func tracking( + _ regions: DatabaseRegionConvertible..., -+ fetch: @escaping (Database) throws -> Value) ++ fetch: @escaping (DatabaseBase) throws -> Value) + -> ValueObservation> + + static func tracking( + _ regions: DatabaseRegionConvertible..., -+ fetchDistinct: @escaping (Database) throws -> Value) ++ fetchDistinct: @escaping (DatabaseBase) throws -> Value) + -> ValueObservation> + where Value: Equatable + @@ -2801,7 +2801,7 @@ This release comes with **Association Aggregates**. They let you compute values ```diff protocol AggregatingRequest { - func group(_ expressions: [SQLExpressible]) -> Self -+ func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self ++ func group(_ expressions: @escaping (DatabaseBase) throws -> [SQLExpressible]) -> Self } +extension AggregatingRequest { @@ -2879,7 +2879,7 @@ Released September 16, 2018 • [diff](https://github.com/groue/GRDB.swift/co ```diff protocol DatabaseWriter : DatabaseReader { -+ func concurrentRead(_ block: @escaping (Database) throws -> T) -> Future ++ func concurrentRead(_ block: @escaping (DatabaseBase) throws -> T) -> Future + @available(*, deprecated) func readFromCurrentState(_ block: @escaping (Database) -> Void) throws } @@ -2938,10 +2938,10 @@ Fixes: ```diff class DatabaseQueue { -- func write(_ block: (Database) throws -> T) rethrows -> T { -+ func write(_ block: (Database) throws -> T) throws -> T { -- func unsafeReentrantRead(_ block: (Database) throws -> T) throws -> T { -+ func unsafeReentrantRead(_ block: (Database) throws -> T) rethrows -> T { +- func write(_ block: (DatabaseBase) throws -> T) rethrows -> T { ++ func write(_ block: (DatabaseBase) throws -> T) throws -> T { +- func unsafeReentrantRead(_ block: (DatabaseBase) throws -> T) throws -> T { ++ func unsafeReentrantRead(_ block: (DatabaseBase) throws -> T) rethrows -> T { } ``` @@ -3189,14 +3189,14 @@ Released February 25, 2018 • [diff](https://github.com/groue/GRDB.swift/com extension MutablePersistable { + @discardableResult -+ func updateChanges(_ db: Database, from record: MutablePersistable) throws -> Bool ++ func updateChanges(_ db: DatabaseBase, from record: MutablePersistable) throws -> Bool + func databaseEqual(_ record: Self) -> Bool + func databaseChanges(from record: MutablePersistable) -> [String: DatabaseValue] } class Record { -- final func updateChanges(_ db: Database) throws +- final func updateChanges(_ db: DatabaseBase) throws + @discardableResult -+ final func updateChanges(_ db: Database) throws -> Bool ++ final func updateChanges(_ db: DatabaseBase) throws -> Bool } +@available(*, deprecated, message: "Prefer changes methods defined on the MutablePersistable protocol: databaseEqual(_:), databaseChanges(from:), updateChanges(from:)") @@ -3212,7 +3212,7 @@ Released February 25, 2018 • [diff](https://github.com/groue/GRDB.swift/com extension TableMapping { + static func selectionSQL(alias: String? = nil) -> String -+ static func numberOfSelectedColumns(_ db: Database) throws -> Int ++ static func numberOfSelectedColumns(_ db: DatabaseBase) throws -> Int } +struct EmptyRowAdapter: RowAdapter { } @@ -3335,7 +3335,7 @@ Released January 18, 2018 • [diff](https://github.com/groue/GRDB.swift/comp protocol Request { + // Default implementation -+ func fetchedRegion(_ db: Database) throws -> DatabaseRegion ++ func fetchedRegion(_ db: DatabaseBase) throws -> DatabaseRegion } +extension Row: RandomAccessCollection { @@ -3402,8 +3402,8 @@ Released January 11, 2018 • [diff](https://github.com/groue/GRDB.swift/comp } extension RowConvertible where Self: TableMapping { -- static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Self? -+ static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]?) throws -> Self? +- static func fetchOne(_ db: DatabaseBase, key: [String: DatabaseValueConvertible?]) throws -> Self? ++ static func fetchOne(_ db: DatabaseBase, key: [String: DatabaseValueConvertible?]?) throws -> Self? } ``` @@ -3533,7 +3533,7 @@ Released October 24, 2017 • [diff](https://github.com/groue/GRDB.swift/comp ```diff extension Request { -+ func asSQLRequest(_ db: Database, cached: Bool = false) throws -> SQLRequest ++ func asSQLRequest(_ db: DatabaseBase, cached: Bool = false) throws -> SQLRequest } struct SQLRequest { + let sql: String @@ -3784,15 +3784,15 @@ New features have been added in order to plug a few holes and support the [RxGRD -extension TableMapping { +extension MutablePersistable { - @discardableResult static func deleteAll(_ db: Database) throws -> Int - @discardableResult static func deleteAll(_ db: Database, keys: Sequence) throws -> Int where Sequence.Element: DatabaseValueConvertible - @discardableResult static func deleteOne(_ db: Database, key: PrimaryKeyType?) throws -> Bool - @discardableResult static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int - @discardableResult static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool + @discardableResult static func deleteAll(_ db: DatabaseBase) throws -> Int + @discardableResult static func deleteAll(_ db: DatabaseBase, keys: Sequence) throws -> Int where Sequence.Element: DatabaseValueConvertible + @discardableResult static func deleteOne(_ db: DatabaseBase, key: PrimaryKeyType?) throws -> Bool + @discardableResult static func deleteAll(_ db: DatabaseBase, keys: [[String: DatabaseValueConvertible?]]) throws -> Int + @discardableResult static func deleteOne(_ db: DatabaseBase, key: [String: DatabaseValueConvertible?]) throws -> Bool } -extension QueryInterfaceRequest { +extension QueryInterfaceRequest where RowDecoder: MutablePersistable { - @discardableResult func deleteAll(_ db: Database) throws -> Int + @discardableResult func deleteAll(_ db: DatabaseBase) throws -> Int } protocol TableMapping { @@ -3862,30 +3862,30 @@ New features have been added in order to plug a few holes and support the [RxGRD + static func fetchCursor(...) throws -> RecordCursor } extension TypedRequest where RowDecoder: RowConvertible { -- func fetchCursor(_ db: Database) throws -> DatabaseCursor -+ func fetchCursor(_ db: Database) throws -> RecordCursor +- func fetchCursor(_ db: DatabaseBase) throws -> DatabaseCursor ++ func fetchCursor(_ db: DatabaseBase) throws -> RecordCursor } extension TypedRequest where RowDecoder: DatabaseValueConvertible { -- func fetchCursor(_ db: Database) throws -> DatabaseCursor -+ func fetchCursor(_ db: Database) throws -> DatabaseValueCursor +- func fetchCursor(_ db: DatabaseBase) throws -> DatabaseCursor ++ func fetchCursor(_ db: DatabaseBase) throws -> DatabaseValueCursor } extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible { -+ func fetchCursor(_ db: Database) throws -> ColumnCursor ++ func fetchCursor(_ db: DatabaseBase) throws -> ColumnCursor } extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible { -- func fetchCursor(_ db: Database) throws -> DatabaseCursor -+ func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor +- func fetchCursor(_ db: DatabaseBase) throws -> DatabaseCursor ++ func fetchCursor(_ db: DatabaseBase) throws -> NullableDatabaseValueCursor } extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible { -+ func fetchCursor(_ db: Database) throws -> NullableColumnCursor ++ func fetchCursor(_ db: DatabaseBase) throws -> NullableColumnCursor } extension TypedRequest where RowDecoder: Row { -- func fetchCursor(_ db: Database) throws -> DatabaseCursor -+ func fetchCursor(_ db: Database) throws -> RowCursor +- func fetchCursor(_ db: DatabaseBase) throws -> DatabaseCursor ++ func fetchCursor(_ db: DatabaseBase) throws -> RowCursor } extension TableMapping { -- @available(*, deprecated) static func primaryKeyRowComparator(_ db: Database) throws -> (Row, Row) -> Bool +- @available(*, deprecated) static func primaryKeyRowComparator(_ db: DatabaseBase) throws -> (Row, Row) -> Bool } +final class AnyDatabaseReader : DatabaseReader { @@ -4048,7 +4048,7 @@ Released July 13, 2017 • [diff](https://github.com/groue/GRDB.swift/compare } protocol DatabaseReader { -+ func unsafeReentrantRead(_ block: (Database) throws -> T) throws -> T ++ func unsafeReentrantRead(_ block: (DatabaseBase) throws -> T) throws -> T } ``` @@ -4110,7 +4110,7 @@ Released July 1, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/ extension TableMapping { + @available(*, deprecated) - static func primaryKeyRowComparator(_ db: Database) throws -> (Row, Row) -> Bool + static func primaryKeyRowComparator(_ db: DatabaseBase) throws -> (Row, Row) -> Bool } ``` @@ -4235,8 +4235,8 @@ It comes with breaking changes, but the good news is that they are the last (unt } extension Request { -- func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AnyRequest -+ func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedRequest +- func adapted(_ adapter: @escaping (DatabaseBase) throws -> RowAdapter) -> AnyRequest ++ func adapted(_ adapter: @escaping (DatabaseBase) throws -> RowAdapter) -> AdaptedRequest } protocol TypedRequest : Request { @@ -4245,8 +4245,8 @@ protocol TypedRequest : Request { } extension TypedRequest { -- func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AnyTypedRequest -+ func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedTypedRequest +- func adapted(_ adapter: @escaping (DatabaseBase) throws -> RowAdapter) -> AnyTypedRequest ++ func adapted(_ adapter: @escaping (DatabaseBase) throws -> RowAdapter) -> AdaptedTypedRequest } ``` @@ -4366,7 +4366,7 @@ Released April 3, 2017 - Support for [reactive](https://reactivex.io) extensions: - `SelectStatement.SelectionInfo` is an opaque value that knows which database tables and columns are read by a [select statement](https://github.com/groue/GRDB.swift#prepared-statements). - `DatabaseEventKind.impacts(_ selectionInfo:SelectStatement.SelectionInfo)` tells whether a database change has any impact on the results of a select statement. See [Database Changes Observation](https://github.com/groue/GRDB.swift#database-changes-observation) - - `TableMapping.primaryKeyRowComparator(_ db: Database)` returns a function that compares two database rows and return true if and only if they have the same non-null primary key. + - `TableMapping.primaryKeyRowComparator(_ db: DatabaseBase)` returns a function that compares two database rows and return true if and only if they have the same non-null primary key. **Breaking Changes** @@ -4684,19 +4684,19 @@ Many APIs were changed: } final class DatabasePool { -- func read(_ block: (Database) throws -> T) rethrows -> T -- func nonIsolatedRead(_ block: (Database) throws -> T) rethrows -> T +- func read(_ block: (DatabaseBase) throws -> T) rethrows -> T +- func nonIsolatedRead(_ block: (DatabaseBase) throws -> T) rethrows -> T - func readFromWrite(_ block: @escaping (Database) -> Void) -+ func read(_ block: (Database) throws -> T) throws -> T -+ func nonIsolatedRead(_ block: (Database) throws -> T) throws -> T ++ func read(_ block: (DatabaseBase) throws -> T) throws -> T ++ func nonIsolatedRead(_ block: (DatabaseBase) throws -> T) throws -> T + func readFromWrite(_ block: @escaping (Database) -> Void) throws } protocol DatabaseReader { -- func read(_ block: (Database) throws -> T) rethrows -> T -- func nonIsolatedRead(_ block: (Database) throws -> T) rethrows -> T -+ func read(_ block: (Database) throws -> T) throws -> T -+ func nonIsolatedRead(_ block: (Database) throws -> T) throws -> T +- func read(_ block: (DatabaseBase) throws -> T) rethrows -> T +- func nonIsolatedRead(_ block: (DatabaseBase) throws -> T) rethrows -> T ++ func read(_ block: (DatabaseBase) throws -> T) throws -> T ++ func nonIsolatedRead(_ block: (DatabaseBase) throws -> T) throws -> T } protocol DatabaseWriter { @@ -4747,13 +4747,13 @@ Many APIs were changed: } protocol MutablePersistable : TableMapping { -- func exists(_ db: Database) -> Bool -+ func exists(_ db: Database) throws -> Bool +- func exists(_ db: DatabaseBase) -> Bool ++ func exists(_ db: DatabaseBase) throws -> Bool } extension MutablePersistable { -- func performExists(_ db: Database) -> Bool -+ func performExists(_ db: Database) throws -> Bool +- func performExists(_ db: DatabaseBase) -> Bool ++ func performExists(_ db: DatabaseBase) throws -> Bool } extension QueryInterfaceRequest { @@ -4780,8 +4780,8 @@ Many APIs were changed: } extension TableMapping { -- static func fetchCount(_ db: Database) -> Int -+ static func fetchCount(_ db: Database) throws -> Int +- static func fetchCount(_ db: DatabaseBase) -> Int ++ static func fetchCount(_ db: DatabaseBase) throws -> Int } ``` @@ -4959,7 +4959,7 @@ Released October 16, 2016 protocol VirtualTableModule { - func moduleArguments(_ definition: TableDefinition) -> [String] + func moduleArguments(for definition: TableDefinition, in db: Database) throws -> [String] - + func database(_ db: Database, didCreate tableName: String, using definition: TableDefinition) throws + + func database(_ db: DatabaseBase, didCreate tableName: String, using definition: TableDefinition) throws } ``` @@ -5032,7 +5032,7 @@ Released September 28, 2016 **Breaking Changes** -- The SQLForeignKeyAction, SQLColumnType, SQLConflictResolution, and SQLCollation types have been renamed Database.ForeignKeyAction, Database.ColumnType, Database.ConflictResolution, and Database.CollationName. +- The SQLForeignKeyAction, SQLColumnType, SQLConflictResolution, and SQLCollation types have been renamed Database.ForeignKeyAction, Database.ColumnType, DatabaseConflictResolution, and Database.CollationName. ## 0.84.0 @@ -5295,8 +5295,8 @@ Released September 11, 2016 - func databaseDidRollback(db: Database) + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool + func databaseDidChange(with event: DatabaseEvent) - + func databaseDidCommit(_ db: Database) - + func databaseDidRollback(_ db: Database) + + func databaseDidCommit(_ db: DatabaseBase) + + func databaseDidRollback(_ db: DatabaseBase) #if SQLITE_ENABLE_PREUPDATE_HOOK - func databaseWillChangeWithEvent(event: DatabasePreUpdateEvent) + func databaseWillChange(with event: DatabasePreUpdateEvent) @@ -5319,19 +5319,19 @@ Released September 11, 2016 - func delete(db: Database) throws -> Bool - func exists(db: Database) -> Bool + mutating func didInsert(with rowID: Int64, for column: String?) - + mutating func insert(_ db: Database) throws - + func update(_ db: Database, columns: Set) throws - + mutating func save(_ db: Database) throws - + @discardableResult func delete(_ db: Database) throws -> Bool - + func exists(_ db: Database) -> Bool + + mutating func insert(_ db: DatabaseBase) throws + + func update(_ db: DatabaseBase, columns: Set) throws + + mutating func save(_ db: DatabaseBase) throws + + @discardableResult func delete(_ db: DatabaseBase) throws -> Bool + + func exists(_ db: DatabaseBase) -> Bool } protocol Persistable : MutablePersistable { - func didInsertWithRowID(rowID: Int64, forColumn column: String?) - func insert(db: Database) throws - func save(db: Database) throws + func didInsert(with rowID: Int64, for column: String?) - + func insert(_ db: Database) throws - + func save(_ db: Database) throws + + func insert(_ db: DatabaseBase) throws + + func save(_ db: DatabaseBase) throws } protocol TableMapping { - static func databaseTableName() -> String @@ -5351,10 +5351,10 @@ Released September 11, 2016 + class var databaseTableName: String + func awakeFromFetch(row: Row) + func didInsert(with rowID: Int64, for column: String?) - + func update(_ db: Database, columns: Set) throws - + func insert(_ db: Database) throws - + func save(_ db: Database) throws - + @discardableResult func delete(_ db: Database) throws -> Bool + + func update(_ db: DatabaseBase, columns: Set) throws + + func insert(_ db: DatabaseBase) throws + + func save(_ db: DatabaseBase) throws + + @discardableResult func delete(_ db: DatabaseBase) throws -> Bool } ``` @@ -5363,7 +5363,7 @@ Released September 11, 2016 ```diff protocol FetchRequest { - func prepare(db: Database) throws -> (SelectStatement, RowAdapter?) - + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) + + func prepare(_ db: DatabaseBase) throws -> (SelectStatement, RowAdapter?) } -struct SQLColumn {} +struct Column {} @@ -5943,10 +5943,10 @@ Released May 17, 2016 ```diff struct DatabaseMigrator { - - mutating func registerMigration(identifier: String, withDisabledForeignKeyChecks disabledForeignKeyChecks: Bool = false, migrate: (Database) throws -> Void) - + mutating func registerMigration(identifier: String, migrate: (Database) throws -> Void) + - mutating func registerMigration(identifier: String, withDisabledForeignKeyChecks disabledForeignKeyChecks: Bool = false, migrate: (DatabaseBase) throws -> Void) + + mutating func registerMigration(identifier: String, migrate: (DatabaseBase) throws -> Void) + @available(iOS 8.2, OSX 10.10, *) - + mutating func registerMigrationWithDisabledForeignKeyChecks(identifier: String, migrate: (Database) throws -> Void) + + mutating func registerMigrationWithDisabledForeignKeyChecks(identifier: String, migrate: (DatabaseBase) throws -> Void) ``` diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Database/AppDatabase.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Database/AppDatabase.swift index e3965accb..b5cdc5a8d 100644 --- a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Database/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Database/AppDatabase.swift @@ -165,7 +165,7 @@ extension AppDatabase { } /// Support for `createRandomPlayersIfEmpty()` and `refreshPlayers()`. - private func createRandomPlayers(_ db: Database) throws { + private func createRandomPlayers(_ db: DatabaseBase) throws { for _ in 0..<8 { _ = try Player.makeRandom().inserted(db) // insert but ignore inserted id } diff --git a/Documentation/GRDB6MigrationGuide.md b/Documentation/GRDB6MigrationGuide.md index bccc9cb88..2e661f60c 100644 --- a/Documentation/GRDB6MigrationGuide.md +++ b/Documentation/GRDB6MigrationGuide.md @@ -178,12 +178,12 @@ The record protocols have been refactored. We tried to keep the amount of modifi ```swift // GRDB 6: remove those methods from your code - func insert(_ db: Database) throws + func insert(_ db: DatabaseBase) throws func didInsert(with rowID: Int64, for column: String?) - func update(_ db: Database, columns: Set) throws - func save(_ db: Database) throws - func delete(_ db: Database) throws -> Bool - func exists(_ db: Database) throws -> Bool + func update(_ db: DatabaseBase, columns: Set) throws + func save(_ db: DatabaseBase) throws + func delete(_ db: DatabaseBase) throws -> Bool + func exists(_ db: DatabaseBase) throws -> Bool ``` - `insert(_:)`: customization is now made with [persistence callbacks]. @@ -204,12 +204,12 @@ The record protocols have been refactored. We tried to keep the amount of modifi struct Link: PersistableRecord { var url: URL - func insert(_ db: Database) throws { + func insert(_ db: DatabaseBase) throws { try validate() try performInsert(db) } - func update(_ db: Database, columns: Set) throws { + func update(_ db: DatabaseBase, columns: Set) throws { try validate() try performUpdate(db, columns: columns) } @@ -229,7 +229,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi struct Link: PersistableRecord { var url: URL - func willSave(_ db: Database) throws { + func willSave(_ db: DatabaseBase) throws { if url.host == nil { throw ValidationError("url must be absolute.") } @@ -249,7 +249,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi class Link: Record { var url: URL - override func willSave(_ db: Database) throws { + override func willSave(_ db: DatabaseBase) throws { try super.willSave(db) if url.host == nil { throw ValidationError("url must be absolute.") diff --git a/Documentation/Playgrounds/TransactionObserver.playground/Contents.swift b/Documentation/Playgrounds/TransactionObserver.playground/Contents.swift index 0db433c81..de5f9edbf 100644 --- a/Documentation/Playgrounds/TransactionObserver.playground/Contents.swift +++ b/Documentation/Playgrounds/TransactionObserver.playground/Contents.swift @@ -40,12 +40,12 @@ class TableChangeObserver : NSObject, TransactionObserver { changedTableNames.insert(event.tableName) } - func databaseDidCommit(_ db: Database) { + func databaseDidCommit(_ db: DatabaseBase) { print("Changed table(s): \(changedTableNames.joined(separator: ", "))") changedTableNames = [] } - func databaseDidRollback(_ db: Database) { + func databaseDidRollback(_ db: DatabaseBase) { changedTableNames = [] } } diff --git a/Documentation/QueryInterfaceOrganization.md b/Documentation/QueryInterfaceOrganization.md index 4a3b44d62..24351e90f 100644 --- a/Documentation/QueryInterfaceOrganization.md +++ b/Documentation/QueryInterfaceOrganization.md @@ -123,7 +123,7 @@ Columns are special expressions that allow some optimizations and niceties: ```swift protocol DatabaseRegionConvertible { - func databaseRegion(_ db: Database) throws -> DatabaseRegion + func databaseRegion(_ db: DatabaseBase) throws -> DatabaseRegion } ``` @@ -207,10 +207,10 @@ protocol FetchRequest: SQLSubqueryable, DatabaseRegionConvertible { associatedtype RowDecoder /// Returns a PreparedRequest that is ready to be executed. - func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest + func makePreparedRequest(_ db: DatabaseBase, forSingleResult singleResult: Bool) throws -> PreparedRequest /// Returns the number of rows fetched by the request. - func fetchCount(_ db: Database) throws -> Int + func fetchCount(_ db: DatabaseBase) throws -> Int } ``` diff --git a/Documentation/SQLInterpolation.md b/Documentation/SQLInterpolation.md index 0de946d3c..f3417fbb0 100644 --- a/Documentation/SQLInterpolation.md +++ b/Documentation/SQLInterpolation.md @@ -204,7 +204,7 @@ Let's extend Player with database methods. ```swift extension Player { /// Deletes all player with no score - static func deleteAllWithoutScore(_ db: Database) throws { + static func deleteAllWithoutScore(_ db: DatabaseBase) throws { try db.execute(literal: "DELETE FROM \(self) WHERE \(CodingKeys.score) IS NULL") } } diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 933fb9c2b..2472b9adb 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif #if !canImport(Darwin) @preconcurrency @@ -201,7 +201,7 @@ public struct Configuration: Sendable { // MARK: - Managing SQLite Connections - private var setups: [@Sendable (Database) throws -> Void] = [] + private var setups: [@Sendable (DatabaseBase) throws -> Void] = [] /// Defines a function to run whenever an SQLite connection is opened. /// @@ -238,7 +238,7 @@ public struct Configuration: Sendable { /// /// On newly created databases files, ``DatabasePool`` activates the WAL /// mode after the preparation functions have run. - public mutating func prepareDatabase(_ setup: @escaping @Sendable (Database) throws -> Void) { + public mutating func prepareDatabase(_ setup: @escaping @Sendable (DatabaseBase) throws -> Void) { setups.append(setup) } @@ -481,7 +481,7 @@ public struct Configuration: Sendable { return threadingMode.SQLiteOpenFlags | flags } - func setUp(_ db: Database) throws { + func setUp(_ db: DatabaseBase) throws { for f in setups { try f(db) } diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 593a1fcd8..ef404cb10 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -1,16 +1,16 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif -extension Database { +extension DatabaseBase { /// A cache for the available database schemas. struct SchemaCache { /// The available schema identifiers, in the order of SQLite resolution: @@ -966,7 +966,7 @@ extension Database { } } -extension Database { +extension DatabaseBase { /// Returns the columns in a table or a view. /// @@ -1485,7 +1485,7 @@ public struct ForeignKeyViolation: Sendable { /// ``` /// /// See also ``description``. - public func failureDescription(_ db: Database) throws -> String { + public func failureDescription(_ db: DatabaseBase) throws -> String { // Grab detailed information, if possible, for better error message let originRow = try originRowID.flatMap { rowid in try Row.fetchOne(db, sql: "SELECT * FROM \(originTable.quotedDatabaseIdentifier) WHERE rowid = \(rowid)") @@ -1517,7 +1517,7 @@ public struct ForeignKeyViolation: Sendable { /// Converts the violation into a ``DatabaseError``. /// /// The returned error has the extended code `SQLITE_CONSTRAINT_FOREIGNKEY`. - public func databaseError(_ db: Database) -> DatabaseError { + public func databaseError(_ db: DatabaseBase) -> DatabaseError { // Grab detailed information, if possible, for better error message. // If detailed information is not available, fallback to plain description. let message = (try? failureDescription(db)) ?? String(describing: self) @@ -1840,7 +1840,7 @@ struct SchemaInfo: Equatable { extension SchemaInfo { /// - parameter schemaTableName: "sqlite_master" or "sqlite_temp_master" - init(_ db: Database, schemaTableName: String) throws { + init(_ db: DatabaseBase, schemaTableName: String) throws { objects = try SchemaObject.fetchSet(db, sql: """ SELECT type, name, tbl_name, sql FROM \(schemaTableName) """) diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 34a362b9d..900d2302c 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -1,18 +1,18 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import Foundation -extension Database { +extension DatabaseBase { // MARK: - Statements @@ -434,10 +434,10 @@ extension SQLStatementCursor: Cursor { } } -extension Database { +extension DatabaseBase { /// Makes sure statement can be executed, and prepares database observation. @usableFromInline - func statementWillExecute(_ statement: Statement) throws { + func statementWillExecute(_ statement: StatementBase) throws { // Aborted transactions prevent statement execution (see the // documentation of this method for more information). try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments) @@ -458,7 +458,7 @@ extension Database { /// May throw a cancelled commit error, if a transaction observer cancels /// an empty transaction. @usableFromInline - func statementDidExecute(_ statement: Statement) throws { + func statementDidExecute(_ statement: StatementBase) throws { if statement.invalidatesDatabaseSchemaCache { clearSchemaCache() } @@ -471,7 +471,7 @@ extension Database { /// Always throws an error @usableFromInline - func statementDidFail(_ statement: Statement, withResultCode resultCode: CInt) throws -> Never { + func statementDidFail(_ statement: StatementBase, withResultCode resultCode: CInt) throws -> Never { // Failed statements can not be reused, because `sqlite3_reset` won't // be able to restore the statement to its initial state: // https://www.sqlite.org/c3ref/reset.html @@ -534,15 +534,15 @@ extension Database { } /// A thread-unsafe statement cache -struct StatementCache { - unowned let db: Database - private var statements: [String: Statement] = [:] +struct StatementCache { + unowned let db: DatabaseBase + private var statements: [String: StatementBase] = [:] - init(database: Database) { + init(database: DatabaseBase) { self.db = database } - mutating func statement(_ sql: String) throws -> Statement { + mutating func statement(_ sql: String) throws -> StatementBase { if let statement = statements[sql] { return statement } @@ -562,11 +562,11 @@ struct StatementCache { statements = [:] } - mutating func remove(_ statement: Statement) { + mutating func remove(_ statement: StatementBase) { statements.removeFirst { $0.value === statement } } - mutating func removeAll(where shouldBeRemoved: (Statement) -> Bool) { + mutating func removeAll(where shouldBeRemoved: (StatementBase) -> Bool) { statements = statements.filter { (_, statement) in !shouldBeRemoved(statement) } } } diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 2614602dd..76688e92a 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import Foundation @@ -142,7 +142,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_ /// - ``StorageClass`` /// - ``TraceEvent`` /// - ``TracingOptions`` -public final class Database: CustomStringConvertible, CustomDebugStringConvertible { +public final class DatabaseBase: CustomStringConvertible, CustomDebugStringConvertible { // The Database class is not thread-safe. An instance should always be // used through a SerializedDatabase. @@ -315,7 +315,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// /// It is nil in read-only connections, because we do not report read-only /// transactions to transaction observers. - private(set) var observationBroker: DatabaseObservationBroker? + private(set) var observationBroker: DatabaseObservationBroker? /// The list of compile options used when building SQLite static func sqliteCompileOptions() throws -> Set { @@ -1491,7 +1491,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// either ``TransactionCompletion/commit`` or ``TransactionCompletion/rollback``. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the /// error thrown by `operations`. - public func inTransaction(_ kind: TransactionKind? = nil, _ operations: () throws -> TransactionCompletion) throws { + public func inTransaction(_ kind: DatabaseTransactionKind? = nil, _ operations: () throws -> DatabaseTransactionCompletion) throws { // Begin transaction try beginTransaction(kind) @@ -1703,7 +1703,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// If nil, the transaction kind is DEFERRED when the current /// database access is read-only, and IMMEDIATE otherwise. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func beginTransaction(_ kind: TransactionKind? = nil) throws { + public func beginTransaction(_ kind: DatabaseTransactionKind? = nil) throws { // SQLite throws an error for non-deferred transactions when read-only. // We prefer immediate transactions for writes, so that write // transactions can not overlap. This reduces the opportunity for @@ -1945,10 +1945,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // Explicit non-conformance to Sendable: `Database` must be used from a // serialized database access dispatch queue (see `SerializedDatabase`). @available(*, unavailable) -extension Database: Sendable { } +extension DatabaseBase: Sendable { } #if SQLITE_HAS_CODEC -extension Database { +extension DatabaseBase { // MARK: - Encryption @@ -2021,7 +2021,7 @@ extension Database { } #endif -extension Database { +extension DatabaseBase { /// Returns the count of changes executed by one statement execution. func countChanges(_ count: inout Int, forTable tableName: String, updates: () throws -> T) throws -> T { // Database.changesCount calls sqlite3_changes(), whose documentation says: @@ -2049,7 +2049,7 @@ extension Database { } } -extension Database { +extension DatabaseBase { // MARK: - Database-Related Types @@ -2207,26 +2207,6 @@ extension Database { public static let any = ColumnType(rawValue: "ANY") } - /// An SQLite conflict resolution. - /// - /// Related SQLite documentation: - public enum ConflictResolution: String, Sendable { - /// The `ROLLBACK` conflict resolution. - case rollback = "ROLLBACK" - - /// The `ABORT` conflict resolution. - case abort = "ABORT" - - /// The `FAIL` conflict resolution. - case fail = "FAIL" - - /// The `IGNORE` conflict resolution. - case ignore = "IGNORE" - - /// The `REPLACE` conflict resolution. - case replace = "REPLACE" - } - /// A foreign key action. /// /// Related SQLite documentation: @@ -2413,29 +2393,6 @@ extension Database { } } - /// A transaction commit, or rollback. - /// - /// Related SQLite documentation: . - @frozen - public enum TransactionCompletion: Sendable { - case commit - case rollback - } - - /// A transaction kind. - /// - /// Related SQLite documentation: . - public enum TransactionKind: String, Sendable { - /// The `DEFERRED` transaction kind. - case deferred = "DEFERRED" - - /// The `IMMEDIATE` transaction kind. - case immediate = "IMMEDIATE" - - /// The `EXCLUSIVE` transaction kind. - case exclusive = "EXCLUSIVE" - } - /// An SQLite threading mode. See . /// /// - Note: Only the multi-thread mode (`SQLITE_OPEN_NOMUTEX`) is currently @@ -2459,6 +2416,79 @@ extension Database { } } +#warning("TODO: export as DatabaseConflictResolution") +/// An SQLite conflict resolution. +/// +/// Related SQLite documentation: +public enum DatabaseConflictResolution: String, Sendable { + /// The `ROLLBACK` conflict resolution. + case rollback = "ROLLBACK" + + /// The `ABORT` conflict resolution. + case abort = "ABORT" + + /// The `FAIL` conflict resolution. + case fail = "FAIL" + + /// The `IGNORE` conflict resolution. + case ignore = "IGNORE" + + /// The `REPLACE` conflict resolution. + case replace = "REPLACE" +} + +#warning("TODO: export as Database.StorageClass") +/// An SQLite storage class. +/// +/// For more information, see +/// [Datatypes In SQLite](https://www.sqlite.org/datatype3.html). +public struct DatabaseStorageClass: RawRepresentable, Hashable, Sendable { + /// The SQL for the storage class (`"INTEGER"`, `"REAL"`, etc.) + public let rawValue: String + + /// Creates an SQL storage class. + public init(rawValue: String) { + self.rawValue = rawValue + } + + /// The `INTEGER` storage class. + public static let integer = StorageClass(rawValue: "INTEGER") + + /// The `REAL` storage class. + public static let real = StorageClass(rawValue: "REAL") + + /// The `TEXT` storage class. + public static let text = StorageClass(rawValue: "TEXT") + + /// The `BLOB` storage class. + public static let blob = StorageClass(rawValue: "BLOB") +} + +#warning("TODO: export as Database.TransactionCompletion") +/// A transaction commit, or rollback. +/// +/// Related SQLite documentation: . +@frozen +public enum DatabaseTransactionCompletion: Sendable { + case commit + case rollback +} + +#warning("TODO: export as Database.TransactionKind") +/// A transaction kind. +/// +/// Related SQLite documentation: . +public enum DatabaseTransactionKind: String, Sendable { + /// The `DEFERRED` transaction kind. + case deferred = "DEFERRED" + + /// The `IMMEDIATE` transaction kind. + case immediate = "IMMEDIATE" + + /// The `EXCLUSIVE` transaction kind. + case exclusive = "EXCLUSIVE" +} + // Explicit non-conformance to Sendable: a trace event contains transient // information. @available(*, unavailable) diff --git a/GRDB/Core/DatabaseCollation.swift b/GRDB/Core/DatabaseCollation.swift index af59112ba..9e236c843 100644 --- a/GRDB/Core/DatabaseCollation.swift +++ b/GRDB/Core/DatabaseCollation.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import Foundation diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index 78151bfca..07d475cb8 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import Foundation diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index 35bc52bd0..9082ff2c9 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif /// A custom SQL function or aggregate. /// @@ -237,7 +237,7 @@ public final class DatabaseFunction: Identifiable, Sendable { /// Calls sqlite3_create_function_v2 /// See - func install(in db: Database) { + func install(in db: DatabaseBase) { // Retain the function definition let definition = kind.definition let definitionP = Unmanaged.passRetained(definition).toOpaque() @@ -264,7 +264,7 @@ public final class DatabaseFunction: Identifiable, Sendable { /// Calls sqlite3_create_function_v2 /// See - func uninstall(in db: Database) { + func uninstall(in db: DatabaseBase) { let code = sqlite3_create_function_v2( db.sqliteConnection, id.name, diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 08f4c2610..b2898114f 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -4,8 +4,8 @@ import Foundation import UIKit #endif -public final class DatabasePool { - private let writer: SerializedDatabase +public final class DatabasePoolBase { + private let writer: SerializedDatabase /// The pool of reader connections. /// It is constant, until close() sets it to nil. @@ -143,9 +143,9 @@ public final class DatabasePool { } // @unchecked because of readerPool and suspensionObservers -extension DatabasePool: @unchecked Sendable { } +extension DatabasePoolBase: @unchecked Sendable { } -extension DatabasePool { +extension DatabasePoolBase { // MARK: - Memory management @@ -263,7 +263,7 @@ extension DatabasePool { #endif } -extension DatabasePool: DatabaseReader { +extension DatabasePoolBase: DatabaseReaderBase { public func close() throws { try readerPool?.barrier { @@ -336,7 +336,7 @@ extension DatabasePool: DatabaseReader { // MARK: - Reading from Database @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func read(_ value: (Database) throws -> T) throws -> T { + public func read(_ value: (DatabaseBase) throws -> T) throws -> T { GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.") guard let readerPool else { throw DatabaseError.connectionIsClosed() @@ -352,7 +352,7 @@ extension DatabasePool: DatabaseReader { } public func read( - _ value: @Sendable (Database) throws -> T + _ value: @Sendable (DatabaseBase) throws -> T ) async throws -> T { guard let readerPool else { throw DatabaseError.connectionIsClosed() @@ -379,7 +379,7 @@ extension DatabasePool: DatabaseReader { } public func asyncRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: @escaping @Sendable (Result, Error>) -> Void ) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) @@ -418,7 +418,7 @@ extension DatabasePool: DatabaseReader { } @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func unsafeRead(_ value: (Database) throws -> T) throws -> T { + public func unsafeRead(_ value: (DatabaseBase) throws -> T) throws -> T { GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.") guard let readerPool else { throw DatabaseError.connectionIsClosed() @@ -432,7 +432,7 @@ extension DatabasePool: DatabaseReader { } public func unsafeRead( - _ value: @Sendable (Database) throws -> T + _ value: @Sendable (DatabaseBase) throws -> T ) async throws -> T { guard let readerPool else { throw DatabaseError.connectionIsClosed() @@ -447,7 +447,7 @@ extension DatabasePool: DatabaseReader { } public func asyncUnsafeRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: @escaping @Sendable (Result, Error>) -> Void ) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) @@ -475,7 +475,7 @@ extension DatabasePool: DatabaseReader { } } - public func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T { + public func unsafeReentrantRead(_ value: (DatabaseBase) throws -> T) throws -> T { if let reader = currentReader { return try reader.reentrantSync(value) } else if writer.onValidQueue { @@ -494,7 +494,7 @@ extension DatabasePool: DatabaseReader { } public func spawnConcurrentRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: @escaping @Sendable (Result, Error>) -> Void ) { asyncConcurrentRead(value) } @@ -537,7 +537,7 @@ extension DatabasePool: DatabaseReader { /// /// - parameter value: A function that accesses the database. public func asyncConcurrentRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: @escaping @Sendable (Result, Error>) -> Void ) { // Check that we're on the writer queue... writer.execute { db in @@ -686,13 +686,13 @@ extension DatabasePool: DatabaseReader { #if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT /// Returns a long-lived WAL snapshot transaction on a reader connection. - func walSnapshotTransaction() throws -> WALSnapshotTransaction { + func walSnapshotTransaction() throws -> WALSnapshotTransactionBase { guard let readerPool else { throw DatabaseError.connectionIsClosed() } let (reader, releaseReader) = try readerPool.get() - return try WALSnapshotTransaction(onReader: reader, release: { isInsideTransaction in + return try WALSnapshotTransactionBase(onReader: reader, release: { isInsideTransaction in // Discard the connection if the transaction could not be // properly ended. If we'd reuse it, the next read would // fail because we'd fail starting a read transaction. @@ -705,7 +705,7 @@ extension DatabasePool: DatabaseReader { /// - important: The `completion` argument is executed in a serial /// dispatch queue, so make sure you use the transaction asynchronously. func asyncWALSnapshotTransaction( - _ completion: @escaping @Sendable (Result) -> Void + _ completion: @escaping @Sendable (Result, Error>) -> Void ) { guard let readerPool else { completion(.failure(DatabaseError.connectionIsClosed())) @@ -777,22 +777,22 @@ extension DatabasePool: DatabaseReader { } } -extension DatabasePool: DatabaseWriter { +extension DatabasePoolBase: DatabaseWriterBase { // MARK: - Writing in Database @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { + public func writeWithoutTransaction(_ updates: (DatabaseBase) throws -> T) rethrows -> T { try writer.sync(updates) } public func writeWithoutTransaction( - _ updates: @Sendable (Database) throws -> T + _ updates: @Sendable (DatabaseBase) throws -> T ) async throws -> T { try await writer.execute(updates) } @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T { + public func barrierWriteWithoutTransaction(_ updates: (DatabaseBase) throws -> T) throws -> T { guard let readerPool else { throw DatabaseError.connectionIsClosed() } @@ -802,7 +802,7 @@ extension DatabasePool: DatabaseWriter { } public func barrierWriteWithoutTransaction( - _ updates: @Sendable (Database) throws -> T + _ updates: @Sendable (DatabaseBase) throws -> T ) async throws -> T { guard let readerPool else { throw DatabaseError.connectionIsClosed() @@ -832,7 +832,7 @@ extension DatabasePool: DatabaseWriter { } public func asyncBarrierWriteWithoutTransaction( - _ updates: @escaping @Sendable (Result) -> Void + _ updates: @escaping @Sendable (Result, Error>) -> Void ) { guard let readerPool else { updates(.failure(DatabaseError.connectionIsClosed())) @@ -873,7 +873,7 @@ extension DatabasePool: DatabaseWriter { /// - throws: The error thrown by `updates`, or by the wrapping transaction. public func writeInTransaction( _ kind: Database.TransactionKind? = nil, - _ updates: (Database) throws -> Database.TransactionCompletion) + _ updates: (DatabaseBase) throws -> Database.TransactionCompletion) throws { try writer.sync { db in @@ -883,18 +883,18 @@ extension DatabasePool: DatabaseWriter { } } - public func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T { + public func unsafeReentrantWrite(_ updates: (DatabaseBase) throws -> T) rethrows -> T { try writer.reentrantSync(updates) } public func asyncWriteWithoutTransaction( - _ updates: @escaping @Sendable (Database) -> Void + _ updates: @escaping @Sendable (DatabaseBase) -> Void ) { writer.async(updates) } } -extension DatabasePool { +extension DatabasePoolBase { // MARK: - Snapshots diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index b8f32961c..5d96ec63f 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -4,8 +4,8 @@ import Foundation import UIKit #endif -public final class DatabaseQueue { - private let writer: SerializedDatabase +public final class DatabaseQueueBase { + private let writer: SerializedDatabase /// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers. private var suspensionObservers: [NSObjectProtocol] = [] @@ -124,9 +124,9 @@ public final class DatabaseQueue { } // @unchecked because of suspensionObservers -extension DatabaseQueue: @unchecked Sendable { } +extension DatabaseQueueBase: @unchecked Sendable { } -extension DatabaseQueue { +extension DatabaseQueueBase { // MARK: - Memory management @@ -183,7 +183,7 @@ extension DatabaseQueue { #endif } -extension DatabaseQueue: DatabaseReader { +extension DatabaseQueueBase: DatabaseReaderBase { public func close() throws { try writer.sync { try $0.close() } } @@ -225,7 +225,7 @@ extension DatabaseQueue: DatabaseReader { // MARK: - Reading from Database @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func read(_ value: (Database) throws -> T) throws -> T { + public func read(_ value: (DatabaseBase) throws -> T) throws -> T { try writer.sync { db in try db.isolated(readOnly: true) { try value(db) @@ -234,7 +234,7 @@ extension DatabaseQueue: DatabaseReader { } public func read( - _ value: @Sendable (Database) throws -> T + _ value: @Sendable (DatabaseBase) throws -> T ) async throws -> T { try await writer.execute { db in try db.isolated(readOnly: true) { @@ -244,7 +244,7 @@ extension DatabaseQueue: DatabaseReader { } public func asyncRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: @escaping @Sendable (Result, Error>) -> Void ) { writer.async { db in defer { @@ -273,28 +273,28 @@ extension DatabaseQueue: DatabaseReader { } @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func unsafeRead(_ value: (Database) throws -> T) rethrows -> T { + public func unsafeRead(_ value: (DatabaseBase) throws -> T) rethrows -> T { try writer.sync(value) } public func unsafeRead( - _ value: @Sendable (Database) throws -> T + _ value: @Sendable (DatabaseBase) throws -> T ) async throws -> T { try await writer.execute(value) } public func asyncUnsafeRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: @escaping @Sendable (Result, Error>) -> Void ) { writer.async { value(.success($0)) } } - public func unsafeReentrantRead(_ value: (Database) throws -> T) rethrows -> T { + public func unsafeReentrantRead(_ value: (DatabaseBase) throws -> T) rethrows -> T { try writer.reentrantSync(value) } public func spawnConcurrentRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: @escaping @Sendable (Result, Error>) -> Void ) { // Check that we're on the writer queue... writer.execute { db in @@ -349,7 +349,7 @@ extension DatabaseQueue: DatabaseReader { } } -extension DatabaseQueue: DatabaseWriter { +extension DatabaseQueueBase: DatabaseWriterBase { // MARK: - Writing in Database /// Wraps database operations inside a database transaction. @@ -381,7 +381,7 @@ extension DatabaseQueue: DatabaseWriter { /// - throws: The error thrown by `updates`, or by the wrapping transaction. public func inTransaction( _ kind: Database.TransactionKind? = nil, - _ updates: (Database) throws -> Database.TransactionCompletion) + _ updates: (DatabaseBase) throws -> Database.TransactionCompletion) throws { try writer.sync { db in @@ -392,29 +392,29 @@ extension DatabaseQueue: DatabaseWriter { } @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { + public func writeWithoutTransaction(_ updates: (DatabaseBase) throws -> T) rethrows -> T { try writer.sync(updates) } public func writeWithoutTransaction( - _ updates: @Sendable (Database) throws -> T + _ updates: @Sendable (DatabaseBase) throws -> T ) async throws -> T { try await writer.execute(updates) } @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T { + public func barrierWriteWithoutTransaction(_ updates: (DatabaseBase) throws -> T) throws -> T { try writer.sync(updates) } public func barrierWriteWithoutTransaction( - _ updates: @Sendable (Database) throws -> T + _ updates: @Sendable (DatabaseBase) throws -> T ) async throws -> T { try await writer.execute(updates) } public func asyncBarrierWriteWithoutTransaction( - _ updates: @escaping @Sendable (Result) -> Void + _ updates: @escaping @Sendable (Result, Error>) -> Void ) { writer.async { updates(.success($0)) } } @@ -453,16 +453,16 @@ extension DatabaseQueue: DatabaseWriter { /// /// - parameter updates: A closure which accesses the database. /// - throws: The error thrown by `updates`. - public func inDatabase(_ updates: (Database) throws -> T) rethrows -> T { + public func inDatabase(_ updates: (DatabaseBase) throws -> T) rethrows -> T { try writer.sync(updates) } - public func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T { + public func unsafeReentrantWrite(_ updates: (DatabaseBase) throws -> T) rethrows -> T { try writer.reentrantSync(updates) } public func asyncWriteWithoutTransaction( - _ updates: @escaping @Sendable (Database) -> Void + _ updates: @escaping @Sendable (DatabaseBase) -> Void ) { writer.async(updates) } @@ -470,7 +470,7 @@ extension DatabaseQueue: DatabaseWriter { // MARK: - Temp Copy -extension DatabaseQueue { +extension DatabaseQueueBase { /// Returns a connection to an in-memory copy of the database at `path`. /// /// Changes performed on the returned connection do not impact the diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index ef86b3e5d..7f9c090af 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -52,7 +52,8 @@ import Dispatch /// ### Supporting Types /// /// - ``AnyDatabaseReader`` -public protocol DatabaseReader: AnyObject, Sendable { +public protocol DatabaseReaderBase: AnyObject, Sendable { + associatedtype API: SQLiteAPI /// The database configuration. var configuration: Configuration { get } @@ -186,7 +187,7 @@ public protocol DatabaseReader: AnyObject, Sendable { /// - throws: The error thrown by `value`, or any ``DatabaseError`` that /// would happen while establishing the database access. @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - func read(_ value: (Database) throws -> T) throws -> T + func read(_ value: (DatabaseBase) throws -> T) throws -> T /// Executes read-only database operations, and returns their result after /// they have finished executing. @@ -215,7 +216,7 @@ public protocol DatabaseReader: AnyObject, Sendable { /// database access, or the error thrown by `value`, or /// `CancellationError` if the task is cancelled. func read( - _ value: @Sendable (Database) throws -> T + _ value: @Sendable (DatabaseBase) throws -> T ) async throws -> T /// Schedules read-only database operations for execution, and @@ -245,7 +246,7 @@ public protocol DatabaseReader: AnyObject, Sendable { /// is a `Result` that provides the database connection, or the failure /// that would prevent establishing the read access to the database. func asyncRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: @escaping @Sendable (Result, Error>) -> Void ) /// Executes database operations, and returns their result after they have @@ -284,7 +285,7 @@ public protocol DatabaseReader: AnyObject, Sendable { /// - throws: The error thrown by `value`, or any ``DatabaseError`` that /// would happen while establishing the database access. @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - func unsafeRead(_ value: (Database) throws -> T) throws -> T + func unsafeRead(_ value: (DatabaseBase) throws -> T) throws -> T /// Executes database operations, and returns their result after they have /// finished executing. @@ -319,7 +320,7 @@ public protocol DatabaseReader: AnyObject, Sendable { /// database access, or the error thrown by `value`, or /// `CancellationError` if the task is cancelled. func unsafeRead( - _ value: @Sendable (Database) throws -> T + _ value: @Sendable (DatabaseBase) throws -> T ) async throws -> T /// Schedules database operations for execution, and returns immediately. @@ -354,7 +355,7 @@ public protocol DatabaseReader: AnyObject, Sendable { /// is a `Result` that provides the database connection, or the failure /// that would prevent establishing the read access to the database. func asyncUnsafeRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: @escaping @Sendable (Result, Error>) -> Void ) /// Executes database operations, and returns their result after they have @@ -398,7 +399,7 @@ public protocol DatabaseReader: AnyObject, Sendable { /// - parameter value: A closure which accesses the database. /// - throws: The error thrown by `value`, or any ``DatabaseError`` that /// would happen while establishing the database access. - func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T + func unsafeReentrantRead(_ value: (DatabaseBase) throws -> T) throws -> T // MARK: - Value Observation @@ -417,7 +418,7 @@ public protocol DatabaseReader: AnyObject, Sendable { ) -> AnyDatabaseCancellable } -extension DatabaseReader { +extension DatabaseReaderBase { // MARK: - Backup @@ -499,7 +500,7 @@ extension DatabaseReader { } #if canImport(Combine) -extension DatabaseReader { +extension DatabaseReaderBase { // MARK: - Publishing Database Values /// Returns a publisher that publishes one value and completes. @@ -531,7 +532,7 @@ extension DatabaseReader { /// - parameter value: A closure which accesses the database. public func readPublisher( receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main, - value: @escaping @Sendable (Database) throws -> Output + value: @escaping @Sendable (DatabaseBase) throws -> Output ) -> DatabasePublishers.Read { OnDemandFuture { fulfill in self.asyncRead { dbResult in @@ -568,7 +569,7 @@ extension Publisher where Failure == Error { } #endif -extension DatabaseReader { +extension DatabaseReaderBase { // MARK: - Value Observation Support /// Adding an observation in a read-only database emits only the @@ -619,17 +620,17 @@ extension DatabaseReader { /// /// An instance of `AnyDatabaseReader` forwards its operations to an underlying /// base database reader. -public final class AnyDatabaseReader { - private let base: any DatabaseReader +public final class AnyDatabaseReaderBase { + private let base: any DatabaseReader /// Creates a new database reader that wraps and forwards operations /// to `base`. - public init(_ base: any DatabaseReader) { + public init(_ base: any DatabaseReader) { self.base = base } } -extension AnyDatabaseReader: DatabaseReader { +extension AnyDatabaseReaderBase: DatabaseReaderBase { public var configuration: Configuration { base.configuration } @@ -647,40 +648,40 @@ extension AnyDatabaseReader: DatabaseReader { } @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func read(_ value: (Database) throws -> T) throws -> T { + public func read(_ value: (DatabaseBase) throws -> T) throws -> T { try base.read(value) } public func read( - _ value: @Sendable (Database) throws -> T + _ value: @Sendable (DatabaseBase) throws -> T ) async throws -> T { try await base.read(value) } public func asyncRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: @escaping @Sendable (Result, Error>) -> Void ) { base.asyncRead(value) } @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func unsafeRead(_ value: (Database) throws -> T) throws -> T { + public func unsafeRead(_ value: (DatabaseBase) throws -> T) throws -> T { try base.unsafeRead(value) } public func unsafeRead( - _ value: @Sendable (Database) throws -> T + _ value: @Sendable (DatabaseBase) throws -> T ) async throws -> T { try await base.unsafeRead(value) } public func asyncUnsafeRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: @escaping @Sendable (Result, Error>) -> Void ) { base.asyncUnsafeRead(value) } - public func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T { + public func unsafeReentrantRead(_ value: (DatabaseBase) throws -> T) throws -> T { try base.unsafeReentrantRead(value) } @@ -735,20 +736,20 @@ extension DatabaseSnapshotReader { /// - parameter value: A closure which accesses the database. /// - throws: The error thrown by `value`, or any ``DatabaseError`` that /// would happen while establishing the database access. - public func reentrantRead(_ value: (Database) throws -> T) throws -> T { + public func reentrantRead(_ value: (DatabaseBase) throws -> T) throws -> T { // Reentrant reads are safe in a snapshot try unsafeReentrantRead(value) } // There is no such thing as an unsafe access to a snapshot. @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func unsafeRead(_ value: (Database) throws -> T) throws -> T { + public func unsafeRead(_ value: (DatabaseBase) throws -> T) throws -> T { try read(value) } // There is no such thing as an unsafe access to a snapshot. public func asyncUnsafeRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: @escaping @Sendable (Result, Error>) -> Void ) { asyncRead(value) } diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 9c9dd2da6..fc9fd770c 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -163,7 +163,7 @@ public struct DatabaseRegion: Sendable { } /// Returns a region suitable for database observation - func observableRegion(_ db: Database) throws -> DatabaseRegion { + func observableRegion(_ db: DatabaseBase) throws -> DatabaseRegion { // SQLite does not expose schema changes to the // TransactionObserver protocol. By removing internal SQLite tables from // the observed region, we optimize database observation. @@ -178,7 +178,7 @@ public struct DatabaseRegion: Sendable { /// Returns a region only made of actual tables with their canonical names. /// /// This method removes views. - func canonicalTables(_ db: Database) throws -> DatabaseRegion { + func canonicalTables(_ db: DatabaseBase) throws -> DatabaseRegion { guard let tableRegions else { return .fullDatabase } var region = DatabaseRegion() for (table, tableRegion) in tableRegions { @@ -237,7 +237,7 @@ extension DatabaseRegion { /// Returns an array of all event kinds that can impact this region. /// /// - precondition: the region is canonical. - func impactfulEventKinds(_ db: Database) throws -> [DatabaseEventKind] { + func impactfulEventKinds(_ db: DatabaseBase) throws -> [DatabaseEventKind] { if let tableRegions { return try tableRegions.flatMap { (table, tableRegion) -> [DatabaseEventKind] in let tableName = table.rawValue // canonical table name @@ -420,7 +420,7 @@ public protocol DatabaseRegionConvertible: Sendable { /// Returns a database region. /// /// - parameter db: A database connection. - func databaseRegion(_ db: Database) throws -> DatabaseRegion + func databaseRegion(_ db: DatabaseBase) throws -> DatabaseRegion } extension DatabaseRegionConvertible where Self == DatabaseRegion { @@ -430,16 +430,16 @@ extension DatabaseRegionConvertible where Self == DatabaseRegion { } extension DatabaseRegion: DatabaseRegionConvertible { - public func databaseRegion(_ db: Database) throws -> DatabaseRegion { + public func databaseRegion(_ db: DatabaseBase) throws -> DatabaseRegion { self } } /// A type-erased DatabaseRegionConvertible public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible { - let _region: @Sendable (Database) throws -> DatabaseRegion + let _region: @Sendable (DatabaseBase) throws -> DatabaseRegion - public init(_ region: @escaping @Sendable (Database) throws -> DatabaseRegion) { + public init(_ region: @escaping @Sendable (DatabaseBase) throws -> DatabaseRegion) { _region = region } @@ -447,7 +447,7 @@ public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible { _region = { try region.databaseRegion($0) } } - public func databaseRegion(_ db: Database) throws -> DatabaseRegion { + public func databaseRegion(_ db: DatabaseBase) throws -> DatabaseRegion { try _region(db) } } @@ -461,7 +461,7 @@ extension DatabaseRegion { } } - static func union(_ regions: [any DatabaseRegionConvertible]) -> @Sendable (Database) throws -> DatabaseRegion { + static func union(_ regions: [any DatabaseRegionConvertible]) -> @Sendable (DatabaseBase) 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 246e3627a..9f7c1d3e2 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -6,7 +6,7 @@ import Foundation public struct DatabaseRegionObservation: Sendable { /// A closure that is evaluated when the observation starts, and returns /// the observed database region. - var observedRegion: @Sendable (Database) throws -> DatabaseRegion + var observedRegion: @Sendable (DatabaseBase) throws -> DatabaseRegion } extension DatabaseRegionObservation { @@ -87,7 +87,7 @@ extension DatabaseRegionObservation { public func start( in writer: any DatabaseWriter, onError: @escaping @Sendable (Error) -> Void, - onChange: @escaping @Sendable (Database) -> Void) + onChange: @escaping @Sendable (DatabaseBase) -> Void) -> AnyDatabaseCancellable { let stateMutex = Mutex(ObservationState.pending) @@ -146,12 +146,12 @@ extension DatabaseRegionObservation { } #endif -private class DatabaseRegionObserver: TransactionObserver { +private class DatabaseRegionObserver: TransactionObserverBase { let region: DatabaseRegion - let onChange: @Sendable (Database) -> Void + let onChange: @Sendable (DatabaseBase) -> Void var isChanged = false - init(region: DatabaseRegion, onChange: @escaping @Sendable (Database) -> Void) { + init(region: DatabaseRegion, onChange: @escaping @Sendable (DatabaseBase) -> Void) { self.region = region self.onChange = onChange } @@ -172,14 +172,14 @@ private class DatabaseRegionObserver: TransactionObserver { } } - func databaseDidCommit(_ db: Database) { + func databaseDidCommit(_ db: DatabaseBase) { guard isChanged else { return } isChanged = false onChange(db) } - func databaseDidRollback(_ db: Database) { + func databaseDidRollback(_ db: DatabaseBase) { isChanged = false } } diff --git a/GRDB/Core/DatabaseSchemaSource.swift b/GRDB/Core/DatabaseSchemaSource.swift index fa1e6b105..d00eb7ce5 100644 --- a/GRDB/Core/DatabaseSchemaSource.swift +++ b/GRDB/Core/DatabaseSchemaSource.swift @@ -81,7 +81,7 @@ public protocol DatabaseSchemaSource: Sendable { /// // A schema source that specifies that all views are identified by /// // their "id" column: /// struct MySchemaSource: DatabaseSchemaSource { - /// func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) { + /// func columnsForPrimaryKey(_ db: DatabaseBase, inView view: DatabaseObjectID) { /// ["id"] /// } /// } @@ -123,7 +123,7 @@ public protocol DatabaseSchemaSource: Sendable { /// // A well-behaved schema source defined by a library is public /// // and returns nil for unknown views. /// public struct MyLibrarySchemaSource: DatabaseSchemaSource { - /// public func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) { + /// public func columnsForPrimaryKey(_ db: DatabaseBase, inView view: DatabaseObjectID) { /// if view.name == "playerView" { /// // This is a view managed by my library: /// return ["id"] @@ -161,14 +161,14 @@ public protocol DatabaseSchemaSource: Sendable { /// - db: A database connection. /// - view: The identifier of a database view. func columnsForPrimaryKey( - _ db: Database, + _ db: DatabaseBase, inView view: DatabaseObjectID ) throws -> [String]? } extension DatabaseSchemaSource { public func columnsForPrimaryKey( - _ db: Database, + _ db: DatabaseBase, inView view: DatabaseObjectID ) throws -> [String]? { nil @@ -210,7 +210,7 @@ where Source1: DatabaseSchemaSource, var first: Source1 var second: Source2 - func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + func columnsForPrimaryKey(_ db: DatabaseBase, inView view: DatabaseObjectID) throws -> [String]? { if let result = try first.columnsForPrimaryKey(db, inView: view) { return result } if let result = try second.columnsForPrimaryKey(db, inView: view) { return result } return nil diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 5d6370736..daa9456f0 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -154,24 +154,24 @@ extension DatabaseSnapshot: DatabaseSnapshotReader { // MARK: - Reading from Database @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func read(_ block: (Database) throws -> T) rethrows -> T { + public func read(_ block: (DatabaseBase) throws -> T) rethrows -> T { try reader.sync(block) } public func read( - _ value: @Sendable (Database) throws -> T + _ value: @Sendable (DatabaseBase) throws -> T ) async throws -> T { try await reader.execute(value) } public func asyncRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: @escaping @Sendable (Result, Error>) -> Void ) { reader.async { value(.success($0)) } } @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func unsafeRead(_ value: (Database) throws -> T) rethrows -> T { + public func unsafeRead(_ value: (DatabaseBase) throws -> T) rethrows -> T { try reader.sync(value) } @@ -180,18 +180,18 @@ extension DatabaseSnapshot: DatabaseSnapshotReader { // `DatabaseSnapshotReader`, because of // . public func unsafeRead( - _ value: @Sendable (Database) throws -> T + _ value: @Sendable (DatabaseBase) throws -> T ) async throws -> T { try await read(value) } public func asyncUnsafeRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: @escaping @Sendable (Result, Error>) -> Void ) { reader.async { value(.success($0)) } } - public func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T { + public func unsafeReentrantRead(_ value: (DatabaseBase) throws -> T) throws -> T { try reader.reentrantSync(value) } diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index 4604c9c2c..cc4cc3feb 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -1,15 +1,15 @@ #if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif /// A database connection that allows concurrent accesses to an unchanging /// database content, as it existed at the moment the snapshot was created. @@ -132,7 +132,7 @@ public final class DatabaseSnapshotPool { /// - parameter configuration: A configuration. If nil, the configuration of /// `db` is used. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public init(_ db: Database, configuration: Configuration? = nil) throws { + public init(_ db: DatabaseBase, configuration: Configuration? = nil) throws { let path = db.path var configuration = Self.configure(configuration ?? db.configuration) @@ -273,7 +273,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { } @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func read(_ value: (Database) throws -> T) throws -> T { + public func read(_ value: (DatabaseBase) throws -> T) throws -> T { GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.") guard let readerPool else { throw DatabaseError.connectionIsClosed() @@ -297,7 +297,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { } public func read( - _ value: @Sendable (Database) throws -> T + _ value: @Sendable (DatabaseBase) throws -> T ) async throws -> T { guard let readerPool else { throw DatabaseError.connectionIsClosed() @@ -319,7 +319,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { } public func asyncRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: @escaping @Sendable (Result, Error>) -> Void ) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) @@ -345,12 +345,12 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { // `DatabaseSnapshotReader`, because of // . public func unsafeRead( - _ value: @Sendable (Database) throws -> T + _ value: @Sendable (DatabaseBase) throws -> T ) async throws -> T { try await read(value) } - public func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T { + public func unsafeReentrantRead(_ value: (DatabaseBase) throws -> T) throws -> T { if let reader = currentReader { return try reader.reentrantSync { db in let result = try value(db) @@ -399,11 +399,11 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { return readers.first { $0.onValidQueue } } - private func poolCompletion(_ db: Database) -> PoolCompletion { + private func poolCompletion(_ db: DatabaseBase) -> PoolCompletion { snapshotIsLost(db) ? .discard : .reuse } - private func snapshotIsLost(_ db: Database) -> Bool { + private func snapshotIsLost(_ db: DatabaseBase) -> Bool { do { let currentSnapshot = try WALSnapshot(db) if currentSnapshot.compare(walSnapshot) == 0 { diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index 2459e3ba7..00e72744d 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import Foundation @@ -162,7 +162,7 @@ public struct DatabaseValue: Hashable { } /// Creates a `DatabaseValue` initialized from a raw SQLite statement pointer. - public init(sqliteStatement: SQLiteStatement, index: CInt) { + public init(sqliteStatement: SQLiteStatementBase, index: CInt) { switch sqlite3_column_type(sqliteStatement, index) { case SQLITE_NULL: storage = .null @@ -187,7 +187,7 @@ public struct DatabaseValue: Hashable { } extension DatabaseValue: StatementBinding { - public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { + public func bind(to sqliteStatement: SQLiteStatementBase, at index: CInt) -> CInt { switch storage { case .null: return sqlite3_bind_null(sqliteStatement, index) diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 941e59375..acff0d6a8 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -80,7 +80,7 @@ extension DatabaseValueConvertible { .databaseValue(databaseValue) } - public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { + public func bind(to sqliteStatement: SQLiteStatementBase, at index: CInt) -> CInt { databaseValue.bind(to: sqliteStatement, at: index) } @@ -276,7 +276,7 @@ extension DatabaseValueConvertible { /// - returns: A ``DatabaseValueCursor`` over fetched values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor( - _ statement: Statement, + _ statement: StatementBase, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws -> DatabaseValueCursor @@ -307,7 +307,7 @@ extension DatabaseValueConvertible { /// - returns: An array. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll( - _ statement: Statement, + _ statement: StatementBase, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws -> [Self] @@ -341,7 +341,7 @@ extension DatabaseValueConvertible { /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne( - _ statement: Statement, + _ statement: StatementBase, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws -> Self? @@ -376,7 +376,7 @@ extension DatabaseValueConvertible where Self: Hashable { /// - returns: A set. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet( - _ statement: Statement, + _ statement: StatementBase, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws -> Set @@ -421,7 +421,7 @@ extension DatabaseValueConvertible { /// - returns: A ``DatabaseValueCursor`` over fetched values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor( - _ db: Database, + _ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil) @@ -453,7 +453,7 @@ extension DatabaseValueConvertible { /// - returns: An array. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll( - _ db: Database, + _ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil) @@ -488,7 +488,7 @@ extension DatabaseValueConvertible { /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne( - _ db: Database, + _ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil) @@ -522,7 +522,7 @@ extension DatabaseValueConvertible where Self: Hashable { /// - returns: A set. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet( - _ db: Database, + _ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil) @@ -581,7 +581,7 @@ extension DatabaseValueConvertible { /// - request: A fetch request. /// - returns: A ``DatabaseValueCursor`` over fetched values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: some FetchRequest) throws -> DatabaseValueCursor { + public static func fetchCursor(_ db: DatabaseBase, _ request: some FetchRequest) throws -> DatabaseValueCursor { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchCursor(request.statement, adapter: request.adapter) } @@ -622,7 +622,7 @@ extension DatabaseValueConvertible { /// - request: A fetch request. /// - returns: An array. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] { + public static func fetchAll(_ db: DatabaseBase, _ request: some FetchRequest) throws -> [Self] { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchAll(request.statement, adapter: request.adapter) } @@ -666,7 +666,7 @@ extension DatabaseValueConvertible { /// - request: A fetch request. /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? { + public static func fetchOne(_ db: DatabaseBase, _ request: some FetchRequest) throws -> Self? { let request = try request.makePreparedRequest(db, forSingleResult: true) return try fetchOne(request.statement, adapter: request.adapter) } @@ -709,7 +709,7 @@ extension DatabaseValueConvertible where Self: Hashable { /// - request: A fetch request. /// - returns: A set. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set { + public static func fetchSet(_ db: DatabaseBase, _ request: some FetchRequest) throws -> Set { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchSet(request.statement, adapter: request.adapter) } @@ -762,7 +762,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// - parameter db: A database connection. /// - returns: A ``DatabaseValueCursor`` over fetched values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor { + public func fetchCursor(_ db: DatabaseBase) throws -> DatabaseValueCursor { try RowDecoder.fetchCursor(db, self) } @@ -800,7 +800,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// - parameter db: A database connection. /// - returns: An array of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder] { + public func fetchAll(_ db: DatabaseBase) throws -> [RowDecoder] { try RowDecoder.fetchAll(db, self) } @@ -841,7 +841,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// - parameter db: A database connection. /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> RowDecoder? { + public func fetchOne(_ db: DatabaseBase) throws -> RowDecoder? { try RowDecoder.fetchOne(db, self) } } @@ -874,7 +874,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable { /// - parameter db: A database connection. /// - returns: A set of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchSet(_ db: Database) throws -> Set { + public func fetchSet(_ db: DatabaseBase) throws -> Set { try RowDecoder.fetchSet(db, self) } } diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 59fe6ff5f..d82c6f2dd 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -61,7 +61,7 @@ import Dispatch /// ### Supporting Types /// /// - ``AnyDatabaseWriter`` -public protocol DatabaseWriter: DatabaseReader { +public protocol DatabaseWriterBase: DatabaseReaderBase { // MARK: - Writing in Database @@ -98,7 +98,7 @@ public protocol DatabaseWriter: DatabaseReader { /// - parameter updates: A closure which accesses the database. /// - throws: The error thrown by `updates`. @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T + func writeWithoutTransaction(_ updates: (DatabaseBase) throws -> T) rethrows -> T /// Executes database operations, and returns their result after they have /// finished executing. @@ -130,7 +130,7 @@ public protocol DatabaseWriter: DatabaseReader { /// database access, or the error thrown by `updates`, or /// `CancellationError` if the task is cancelled. func writeWithoutTransaction( - _ updates: @Sendable (Database) throws -> T + _ updates: @Sendable (DatabaseBase) throws -> T ) async throws -> T /// Executes database operations, and returns their result after they have @@ -171,7 +171,7 @@ public protocol DatabaseWriter: DatabaseReader { /// - parameter updates: A closure which accesses the database. /// - throws: The error thrown by `updates`. @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T + func barrierWriteWithoutTransaction(_ updates: (DatabaseBase) throws -> T) throws -> T /// Executes database operations, and returns their result after they have /// finished executing. @@ -213,7 +213,7 @@ public protocol DatabaseWriter: DatabaseReader { /// database access, or the error thrown by `updates`, or /// `CancellationError` if the task is cancelled. func barrierWriteWithoutTransaction( - _ updates: @Sendable (Database) throws -> T + _ updates: @Sendable (DatabaseBase) throws -> T ) async throws -> T /// Schedules database operations for execution, and returns immediately. @@ -256,7 +256,7 @@ public protocol DatabaseWriter: DatabaseReader { /// is a `Result` that provides the database connection, or the failure /// that would prevent establishing the barrier access to the database. func asyncBarrierWriteWithoutTransaction( - _ updates: @escaping @Sendable (Result) -> Void + _ updates: @escaping @Sendable (Result, Error>) -> Void ) /// Schedules database operations for execution, and returns immediately. @@ -290,7 +290,7 @@ public protocol DatabaseWriter: DatabaseReader { /// /// - parameter updates: A closure which accesses the database. func asyncWriteWithoutTransaction( - _ updates: @escaping @Sendable (Database) -> Void + _ updates: @escaping @Sendable (DatabaseBase) -> Void ) /// Executes database operations, and returns their result after they have @@ -325,7 +325,7 @@ public protocol DatabaseWriter: DatabaseReader { /// /// - parameter updates: A closure which accesses the database. /// - throws: The error thrown by `updates`. - func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T + func unsafeReentrantWrite(_ updates: (DatabaseBase) throws -> T) rethrows -> T // MARK: - Reading from Database @@ -374,7 +374,7 @@ public protocol DatabaseWriter: DatabaseReader { /// is a `Result` that provides the database connection, or the failure /// that would prevent establishing the read access to the database. func spawnConcurrentRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: @escaping @Sendable (Result, Error>) -> Void ) } @@ -413,7 +413,7 @@ extension DatabaseWriter { /// would happen while establishing the database access or committing /// the transaction. @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func write(_ updates: (Database) throws -> T) throws -> T { + public func write(_ updates: (DatabaseBase) throws -> T) throws -> T { try writeWithoutTransaction { db in var result: T? try db.inTransaction { @@ -461,7 +461,7 @@ extension DatabaseWriter { /// - parameter updates: A closure which accesses the database. /// - parameter completion: A closure called with the transaction result. public func asyncWrite( - _ updates: @escaping @Sendable (Database) throws -> T, + _ updates: @escaping @Sendable (DatabaseBase) throws -> T, completion: @escaping @Sendable (Database, Result) -> Void ) { asyncWriteWithoutTransaction { db in @@ -502,7 +502,7 @@ extension DatabaseWriter { /// is deallocated). public func add( transactionObserver: some TransactionObserver, - extent: Database.TransactionObservationExtent = .observerLifetime) + extent: DatabaseTransactionObservationExtent = .observerLifetime) { writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) } } @@ -640,7 +640,7 @@ extension DatabaseWriter { /// database access, or the error thrown by `updates`, or /// `CancellationError` if the task is cancelled. public func write( - _ updates: @Sendable (Database) throws -> T + _ updates: @Sendable (DatabaseBase) throws -> T ) async throws -> T { try await writeWithoutTransaction { db in var result: T? @@ -733,7 +733,7 @@ extension DatabaseWriter { /// - parameter updates: A closure which accesses the database. public func writePublisher( receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main, - updates: @escaping @Sendable (Database) throws -> Output + updates: @escaping @Sendable (DatabaseBase) throws -> Output ) -> DatabasePublishers.Write { OnDemandFuture { fulfill in self.asyncWrite(updates, completion: { _, result in @@ -796,7 +796,7 @@ extension DatabaseWriter { /// - parameter value: A closure which reads from the database. public func writePublisher( receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main, - updates: @escaping @Sendable (Database) throws -> T, + updates: @escaping @Sendable (DatabaseBase) throws -> T, thenRead value: @escaping @Sendable (Database, T) throws -> Output ) -> DatabasePublishers.Write { OnDemandFuture { fulfill in @@ -880,40 +880,40 @@ extension AnyDatabaseWriter: DatabaseReader { } @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func read(_ value: (Database) throws -> T) throws -> T { + public func read(_ value: (DatabaseBase) throws -> T) throws -> T { try base.read(value) } public func read( - _ value: @Sendable (Database) throws -> T + _ value: @Sendable (DatabaseBase) throws -> T ) async throws -> T { try await base.read(value) } public func asyncRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: @escaping @Sendable (Result, Error>) -> Void ) { base.asyncRead(value) } @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func unsafeRead(_ value: (Database) throws -> T) throws -> T { + public func unsafeRead(_ value: (DatabaseBase) throws -> T) throws -> T { try base.unsafeRead(value) } public func unsafeRead( - _ value: @Sendable (Database) throws -> T + _ value: @Sendable (DatabaseBase) throws -> T ) async throws -> T { try await base.unsafeRead(value) } public func asyncUnsafeRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: @escaping @Sendable (Result, Error>) -> Void ) { base.asyncUnsafeRead(value) } - public func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T { + public func unsafeReentrantRead(_ value: (DatabaseBase) throws -> T) throws -> T { try base.unsafeReentrantRead(value) } @@ -931,45 +931,45 @@ extension AnyDatabaseWriter: DatabaseReader { extension AnyDatabaseWriter: DatabaseWriter { @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T { + public func writeWithoutTransaction(_ updates: (DatabaseBase) throws -> T) rethrows -> T { try base.writeWithoutTransaction(updates) } public func writeWithoutTransaction( - _ updates: @Sendable (Database) throws -> T + _ updates: @Sendable (DatabaseBase) throws -> T ) async throws -> T { try await base.writeWithoutTransaction(updates) } @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T { + public func barrierWriteWithoutTransaction(_ updates: (DatabaseBase) throws -> T) throws -> T { try base.barrierWriteWithoutTransaction(updates) } public func barrierWriteWithoutTransaction( - _ updates: @Sendable (Database) throws -> T + _ updates: @Sendable (DatabaseBase) throws -> T ) async throws -> T { try await base.barrierWriteWithoutTransaction(updates) } public func asyncBarrierWriteWithoutTransaction( - _ updates: @escaping @Sendable (Result) -> Void + _ updates: @escaping @Sendable (Result, Error>) -> Void ) { base.asyncBarrierWriteWithoutTransaction(updates) } public func asyncWriteWithoutTransaction( - _ updates: @escaping @Sendable (Database) -> Void + _ updates: @escaping @Sendable (DatabaseBase) -> Void ) { base.asyncWriteWithoutTransaction(updates) } - public func unsafeReentrantWrite(_ updates: (Database) throws -> T) rethrows -> T { + public func unsafeReentrantWrite(_ updates: (DatabaseBase) throws -> T) rethrows -> T { try base.unsafeReentrantWrite(updates) } public func spawnConcurrentRead( - _ value: @escaping @Sendable (Result) -> Void + _ value: @escaping @Sendable (Result, Error>) -> Void ) { base.spawnConcurrentRead(value) } diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index c3e24d8ba..84acaecb4 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -87,20 +87,20 @@ public protocol FetchRequest: SQLSubqueryable, DatabaseRegionConvert /// - parameter db: A database connection. /// - parameter singleResult: A hint that a single result row will be /// consumed. - func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest + func makePreparedRequest(_ db: DatabaseBase, forSingleResult singleResult: Bool) throws -> PreparedRequestBase /// Returns the number of rows fetched by the request. /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - func fetchCount(_ db: Database) throws -> Int + func fetchCount(_ db: DatabaseBase) throws -> Int } extension FetchRequest { /// Returns the database region that the request feeds from. /// /// - parameter db: A database connection. - public func databaseRegion(_ db: Database) throws -> DatabaseRegion { + public func databaseRegion(_ db: DatabaseBase) throws -> DatabaseRegion { try makePreparedRequest(db, forSingleResult: false).statement.databaseRegion } } @@ -123,28 +123,28 @@ typealias WillExecuteSupplementaryRequest = (_ request: AnyFetchRequest, _ /// - parameter rows: The rows that are modified by the supplementary fetch. /// - parameter willExecuteSupplementaryRequest: A closure to execute before /// performing supplementary fetches. -typealias SupplementaryFetch = ( - _ db: Database, +typealias SupplementaryFetch = ( + _ db: DatabaseBase, _ rows: [Row], _ willExecuteSupplementaryRequest: WillExecuteSupplementaryRequest?) throws -> Void /// A `PreparedRequest` is a request that is ready to be executed. -public struct PreparedRequest { +public struct PreparedRequestBase { /// A prepared statement with bound parameters. - public var statement: Statement + public var statement: StatementBase /// An eventual adapter for rows fetched by the select statement. public var adapter: (any RowAdapter)? /// A closure that performs supplementary fetches. /// Support for eager loading of hasMany associations. - var supplementaryFetch: SupplementaryFetch? + var supplementaryFetch: SupplementaryFetch? init( - statement: Statement, + statement: StatementBase, adapter: (any RowAdapter)?, - supplementaryFetch: SupplementaryFetch? = nil) + supplementaryFetch: SupplementaryFetch? = nil) { self.statement = statement self.adapter = adapter @@ -172,7 +172,7 @@ extension FetchRequest { /// - parameter adapter: A closure that accepts a database connection and /// returns a row adapter. public func adapted( - _ adapter: @escaping @Sendable (Database) throws -> any RowAdapter + _ adapter: @escaping @Sendable (DatabaseBase) throws -> any RowAdapter ) -> AdaptedFetchRequest { AdaptedFetchRequest(self, adapter) } @@ -183,11 +183,11 @@ extension FetchRequest { /// See ``FetchRequest/adapted(_:)``. public struct AdaptedFetchRequest { let base: Base - let adapter: @Sendable (Database) throws -> any RowAdapter + let adapter: @Sendable (DatabaseBase) 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 @Sendable (Database) throws -> any RowAdapter) { + init(_ base: Base, _ adapter: @escaping @Sendable (DatabaseBase) throws -> any RowAdapter) { self.base = base self.adapter = adapter } @@ -202,14 +202,14 @@ extension AdaptedFetchRequest: SQLSubqueryable { extension AdaptedFetchRequest: FetchRequest { public typealias RowDecoder = Base.RowDecoder - public func fetchCount(_ db: Database) throws -> Int { + public func fetchCount(_ db: DatabaseBase) throws -> Int { try base.fetchCount(db) } - public func makePreparedRequest( - _ db: Database, + public func makePreparedRequest( + _ db: DatabaseBase, forSingleResult singleResult: Bool = false) - throws -> PreparedRequest + throws -> PreparedRequestBase { var preparedRequest = try base.makePreparedRequest(db, forSingleResult: singleResult) @@ -262,14 +262,14 @@ extension AnyFetchRequest: SQLSubqueryable { } extension AnyFetchRequest: FetchRequest { - public func fetchCount(_ db: Database) throws -> Int { + public func fetchCount(_ db: DatabaseBase) throws -> Int { try request.fetchCount(db) } - public func makePreparedRequest( - _ db: Database, + public func makePreparedRequest( + _ db: DatabaseBase, forSingleResult singleResult: Bool = false) - throws -> PreparedRequest + throws -> PreparedRequestBase { try request.makePreparedRequest(db, forSingleResult: singleResult) } @@ -283,11 +283,11 @@ private class FetchRequestEraser: FetchRequest, @unchecked Sendable { fatalError("subclass must override") } - func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + func makePreparedRequest(_ db: DatabaseBase, forSingleResult singleResult: Bool) throws -> PreparedRequestBase { fatalError("subclass must override") } - func fetchCount(_ db: Database) throws -> Int { + func fetchCount(_ db: DatabaseBase) throws -> Int { fatalError("subclass must override") } } @@ -303,11 +303,11 @@ private final class ConcreteFetchRequestEraser: FetchRequ request.sqlSubquery } - override func fetchCount(_ db: Database) throws -> Int { + override func fetchCount(_ db: DatabaseBase) throws -> Int { try request.fetchCount(db) } - override func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + override func makePreparedRequest(_ db: DatabaseBase, forSingleResult singleResult: Bool) throws -> PreparedRequestBase { try request.makePreparedRequest(db, forSingleResult: singleResult) } } diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index c4b639ae7..3f86d8c8f 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import Foundation @@ -234,7 +234,7 @@ public final class Row { /// The row is implemented on top of StatementRowImpl, which grants *direct* /// access to the SQLite statement. Iteration of the statement does modify /// the row. - init(statement: Statement) { + init(statement: StatementBase) { self.statement = statement self.sqliteStatement = statement.sqliteStatement self.impl = StatementRowImpl(sqliteStatement: statement.sqliteStatement, statement: statement) @@ -243,7 +243,7 @@ public final class Row { /// Creates a row that maps an SQLite statement. Further calls to /// sqlite3_step() modify the row. - init(sqliteStatement: SQLiteStatement) { + init(sqliteStatement: SQLiteStatementBase) { self.statement = nil self.sqliteStatement = sqliteStatement self.impl = SQLiteStatementRowImpl(sqliteStatement: sqliteStatement) @@ -257,8 +257,8 @@ public final class Row { /// the values from the SQLite statement so that further iteration of the /// statement does not modify the row. convenience init( - copiedFromSQLiteStatement sqliteStatement: SQLiteStatement, - statement: Statement) + copiedFromSQLiteStatement sqliteStatement: SQLiteStatementBase, + statement: StatementBase) { self.init(impl: StatementCopyRowImpl( sqliteStatement: sqliteStatement, @@ -1736,7 +1736,7 @@ extension Row { /// - returns: A ``RowCursor`` over fetched rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor( - _ statement: Statement, + _ statement: StatementBase, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws -> RowCursor @@ -1764,7 +1764,7 @@ extension Row { /// - returns: An array of rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll( - _ statement: Statement, + _ statement: StatementBase, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws -> [Row] @@ -1793,7 +1793,7 @@ extension Row { /// - returns: A set of rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet( - _ statement: Statement, + _ statement: StatementBase, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws -> Set @@ -1822,7 +1822,7 @@ extension Row { /// - returns: An optional row. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne( - _ statement: Statement, + _ statement: StatementBase, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws -> Row? @@ -1877,7 +1877,7 @@ extension Row { /// - returns: A ``RowCursor`` over fetched rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor( - _ db: Database, + _ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil) @@ -1906,7 +1906,7 @@ extension Row { /// - returns: An array of rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll( - _ db: Database, + _ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil) @@ -1935,7 +1935,7 @@ extension Row { /// - returns: A set of rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet( - _ db: Database, + _ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil) @@ -1964,7 +1964,7 @@ extension Row { /// - returns: An optional row. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne( - _ db: Database, + _ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil) @@ -2027,7 +2027,7 @@ extension Row { /// - request: A fetch request. /// - returns: A ``RowCursor`` over fetched rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: some FetchRequest) throws -> RowCursor { + public static func fetchCursor(_ db: DatabaseBase, _ request: some FetchRequest) throws -> RowCursor { let request = try request.makePreparedRequest(db, forSingleResult: false) precondition(request.supplementaryFetch == nil, "Not implemented: fetchCursor with supplementary fetch") return try fetchCursor(request.statement, adapter: request.adapter) @@ -2064,7 +2064,7 @@ extension Row { /// - request: A fetch request. /// - returns: An array of rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Row] { + public static func fetchAll(_ db: DatabaseBase, _ request: some FetchRequest) throws -> [Row] { let request = try request.makePreparedRequest(db, forSingleResult: false) let rows = try fetchAll(request.statement, adapter: request.adapter) try request.supplementaryFetch?(db, rows, nil) @@ -2102,7 +2102,7 @@ extension Row { /// - request: A fetch request. /// - returns: A set of rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set { + public static func fetchSet(_ db: DatabaseBase, _ request: some FetchRequest) throws -> Set { let request = try request.makePreparedRequest(db, forSingleResult: false) if let supplementaryFetch = request.supplementaryFetch { let rows = try fetchAll(request.statement, adapter: request.adapter) @@ -2144,7 +2144,7 @@ extension Row { /// - request: A fetch request. /// - returns: An optional row. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Row? { + public static func fetchOne(_ db: DatabaseBase, _ request: some FetchRequest) throws -> Row? { let request = try request.makePreparedRequest(db, forSingleResult: true) guard let row = try fetchOne(request.statement, adapter: request.adapter) else { return nil @@ -2193,7 +2193,7 @@ extension FetchRequest { /// - parameter db: A database connection. /// - returns: A ``RowCursor`` over fetched rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> RowCursor { + public func fetchCursor(_ db: DatabaseBase) throws -> RowCursor { try Row.fetchCursor(db, self) } @@ -2214,7 +2214,7 @@ extension FetchRequest { /// - parameter db: A database connection. /// - returns: An array of fetched rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [Row] { + public func fetchAll(_ db: DatabaseBase) throws -> [Row] { try Row.fetchAll(db, self) } @@ -2235,7 +2235,7 @@ extension FetchRequest { /// - parameter db: A database connection. /// - returns: A set of fetched rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchSet(_ db: Database) throws -> Set { + public func fetchSet(_ db: DatabaseBase) throws -> Set { try Row.fetchSet(db, self) } @@ -2256,7 +2256,7 @@ extension FetchRequest { /// - parameter db: A database connection. /// - returns: An optional row. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> Row? { + public func fetchOne(_ db: DatabaseBase) throws -> Row? { try Row.fetchOne(db, self) } } diff --git a/GRDB/Core/RowDecodingError.swift b/GRDB/Core/RowDecodingError.swift index 025bb8035..b462740d9 100644 --- a/GRDB/Core/RowDecodingError.swift +++ b/GRDB/Core/RowDecodingError.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif /// A key that is used to decode a value in a row @usableFromInline diff --git a/GRDB/Core/SQL.swift b/GRDB/Core/SQL.swift index 056ad8abf..a99cf1378 100644 --- a/GRDB/Core/SQL.swift +++ b/GRDB/Core/SQL.swift @@ -181,7 +181,7 @@ public struct SQL: Sendable { /// /// - parameter db: A database connection. /// - returns: A tuple made of a raw SQL string, and statement arguments. - public func build(_ db: Database) throws -> (sql: String, arguments: StatementArguments) { + public func build(_ db: DatabaseBase) throws -> (sql: String, arguments: StatementArguments) { let context = SQLGenerationContext(db) let sql = try self.sql(context) return (sql: sql, arguments: context.arguments) diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index 6ec272c57..5986d46d3 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -191,14 +191,14 @@ extension SQLRequest: FetchRequest { .literal(sqlLiteral) } - public func fetchCount(_ db: Database) throws -> Int { + public func fetchCount(_ db: DatabaseBase) throws -> Int { try SQLRequest("SELECT COUNT(*) FROM (\(self))").fetchOne(db)! } - public func makePreparedRequest( - _ db: Database, + public func makePreparedRequest( + _ db: DatabaseBase, forSingleResult singleResult: Bool = false) - throws -> PreparedRequest + throws -> PreparedRequestBase { let context = SQLGenerationContext(db) let sql = try sqlLiteral.sql(context) diff --git a/GRDB/Core/SQLiteAPI.swift b/GRDB/Core/SQLiteAPI.swift new file mode 100644 index 000000000..56151ce00 --- /dev/null +++ b/GRDB/Core/SQLiteAPI.swift @@ -0,0 +1,20 @@ +public protocol SQLiteAPI { + static var SQLITE_NULL: CInt { get } + static var SQLITE_OK: CInt { get } + + static func sqlite3_bind_double(_: OpaquePointer?, _: CInt, _: CDouble) -> CInt + static func sqlite3_bind_int64(_: OpaquePointer?, _: CInt, _: Int64) -> CInt + static func sqlite3_bind_null(_: OpaquePointer?, _: CInt) -> CInt + static func sqlite3_bind_text(_: OpaquePointer?, _: CInt, _: UnsafePointer?, _: CInt, _: (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt + + static func sqlite3_column_double(_: OpaquePointer?, _ iCol: CInt) -> Double + static func sqlite3_column_int64(_: OpaquePointer?, _ iCol: CInt) -> Int64 + static func sqlite3_column_text(_: OpaquePointer?, _ iCol: CInt) -> UnsafePointer? + static func sqlite3_column_type(_: OpaquePointer?, _ iCol: CInt) -> CInt + + @discardableResult static func sqlite3_commit_hook(_: OpaquePointer?, _: (@convention(c) (UnsafeMutableRawPointer?) -> Int32)?, _: UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer? + @discardableResult static func sqlite3_rollback_hook(_: OpaquePointer?, _: (@convention(c) (UnsafeMutableRawPointer?) -> Void)?, _: UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer? + @discardableResult static func sqlite3_update_hook(_: OpaquePointer?, _: (@convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer?, UnsafePointer?, Int64) -> Void)?, _: UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer? +} + +public typealias sqlite3_destructor_type = @convention(c) (UnsafeMutableRawPointer?) -> Void diff --git a/GRDB/Core/SchedulingWatchdog.swift b/GRDB/Core/SchedulingWatchdog.swift index dfbdfdace..73841d8ec 100644 --- a/GRDB/Core/SchedulingWatchdog.swift +++ b/GRDB/Core/SchedulingWatchdog.swift @@ -59,7 +59,7 @@ final class SchedulingWatchdog: @unchecked Sendable { } static func preconditionValidQueue( - _ db: Database, + _ db: DatabaseBase, _ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) @@ -69,11 +69,11 @@ final class SchedulingWatchdog: @unchecked Sendable { /// Returns whether the database argument can be used in the current /// dispatch queue. - static func allows(_ db: Database) -> Bool { + static func allows(_ db: DatabaseBase) -> Bool { current?.allows(db) ?? false } - func allows(_ db: Database) -> Bool { + func allows(_ db: DatabaseBase) -> Bool { allowedDatabases.contains { $0 === db } } diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 920d279d0..6636637f9 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -1,9 +1,9 @@ import Foundation /// A class that serializes accesses to an SQLite connection. -final class SerializedDatabase { +final class SerializedDatabaseBase { /// The database connection - private let db: Database + private let db: DatabaseBase /// The actor that performs asynchronous accesses private let actor: DispatchQueueActor @@ -92,7 +92,7 @@ final class SerializedDatabase { /// - parameter allowingLongLivedTransaction: When true, the /// ``Configuration/allowsUnsafeTransactions`` configuration flag is /// ignored until this method is called again with false. - func sync(allowingLongLivedTransaction: Bool, _ body: (Database) throws -> T) rethrows -> T { + func sync(allowingLongLivedTransaction: Bool, _ body: (DatabaseBase) throws -> T) rethrows -> T { try sync { db in self.allowsUnsafeTransactions = allowingLongLivedTransaction return try body(db) @@ -103,7 +103,7 @@ final class SerializedDatabase { /// have finished executing. /// /// This method is not reentrant. - func sync(_ block: (Database) throws -> T) rethrows -> T { + func sync(_ block: (DatabaseBase) throws -> T) rethrows -> T { // Three different cases: // // 1. A database is invoked from some queue like the main queue: @@ -153,7 +153,7 @@ final class SerializedDatabase { /// - parameter allowingLongLivedTransaction: When true, the /// ``Configuration/allowsUnsafeTransactions`` configuration flag is /// ignored until this method is called again with false. - func reentrantSync(allowingLongLivedTransaction: Bool, _ body: (Database) throws -> T) rethrows -> T { + func reentrantSync(allowingLongLivedTransaction: Bool, _ body: (DatabaseBase) throws -> T) rethrows -> T { try reentrantSync { db in self.allowsUnsafeTransactions = allowingLongLivedTransaction return try body(db) @@ -164,7 +164,7 @@ final class SerializedDatabase { /// have finished executing. /// /// This method is reentrant. - func reentrantSync(_ block: (Database) throws -> T) rethrows -> T { + func reentrantSync(_ block: (DatabaseBase) throws -> T) rethrows -> T { // Three different cases: // // 1. A database is invoked from some queue like the main queue: @@ -228,7 +228,7 @@ final class SerializedDatabase { } /// Schedules database operations for execution, and returns immediately. - func async(_ block: @escaping @Sendable (Database) -> Void) { + func async(_ block: @escaping @Sendable (DatabaseBase) -> Void) { queue.async { block(self.db) self.preconditionNoUnsafeTransactionLeft(self.db) @@ -243,14 +243,14 @@ final class SerializedDatabase { /// Executes the block in the current queue. /// /// - precondition: the current dispatch queue is valid. - func execute(_ block: (Database) throws -> T) rethrows -> T { + func execute(_ block: (DatabaseBase) throws -> T) rethrows -> T { preconditionValidQueue() return try block(db) } /// Asynchrously executes the block. func execute( - _ block: @Sendable (Database) throws -> T + _ block: @Sendable (DatabaseBase) throws -> T ) async throws -> T { let cancelMutex = Mutex<(@Sendable () -> Void)?>(nil) return try await withTaskCancellationHandler { @@ -295,7 +295,7 @@ final class SerializedDatabase { /// Fatal error if a transaction has been left opened. private func preconditionNoUnsafeTransactionLeft( - _ db: Database, + _ db: DatabaseBase, _ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access", file: StaticString = #file, line: UInt = #line) diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 6bf3a89ad..9750b5fb9 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -1,19 +1,22 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import Foundation /// A raw SQLite statement, suitable for the SQLite C API. -public typealias SQLiteStatement = OpaquePointer +//public typealias SQLiteStatement = OpaquePointer +public struct SQLiteStatementBase { + public let rawValue: OpaquePointer +} extension String { /// SQL statements are separated by semicolons and white spaces. @@ -37,7 +40,7 @@ extension String { } } -public final class Statement { +public final class StatementBase { enum TransactionEffect: Equatable { case beginTransaction case commitTransaction @@ -48,7 +51,7 @@ public final class Statement { } /// The raw SQLite statement, suitable for the SQLite C API. - public let sqliteStatement: SQLiteStatement + public let sqliteStatement: SQLiteStatementBase /// The SQL query. public var sql: String { @@ -839,11 +842,11 @@ public protocol StatementBinding { /// - parameter sqliteStatement: An SQLite statement. /// - parameter index: 1-based index to statement arguments. /// - returns: the code returned by the `sqlite3_bind_xxx` function. - func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt + func bind(to sqliteStatement: SQLiteStatementBase, at index: CInt) -> CInt } /// Helper function for `withBinding(to:at:do:)` methods. -func checkBindingSuccess(code: CInt, sqliteStatement: SQLiteStatement) throws { +func checkBindingSuccess(code: CInt, sqliteStatement: SQLiteStatementBase) throws { if code == SQLITE_OK { return } let message = String(cString: sqlite3_errmsg(sqlite3_db_handle(sqliteStatement))) let sql = String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index a8871726f..3cac89335 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif #if canImport(string_h) import string_h diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 490dffb7f..41134ea64 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif /// A type that can decode itself from the low-level C interface to /// SQLite results. @@ -92,10 +92,10 @@ public protocol StatementColumnConvertible { /// - sqliteStatement: A pointer to an SQLite statement. /// - index: The column index. /// - returns: A decoded value, or, if decoding is impossible, nil. - static func fromStatement( - _ sqliteStatement: SQLiteStatement, - atUncheckedIndex index: CInt) - -> Self? + static func fromStatement( + _ sqliteStatement: SQLiteStatementBase, + atUncheckedIndex index: CInt + ) -> Self? /// Creates an instance from a raw SQLite statement pointer, if possible. /// @@ -107,7 +107,7 @@ public protocol StatementColumnConvertible { /// /// ```swift /// extension Int64: StatementColumnConvertible { - /// public init(sqliteStatement: SQLiteStatement, index: CInt) { + /// public init(sqliteStatement: SQLiteStatementBase, index: CInt) { /// self = sqlite3_column_int64(sqliteStatement, index) /// } /// } @@ -120,7 +120,7 @@ public protocol StatementColumnConvertible { /// - parameters: /// - sqliteStatement: A pointer to an SQLite statement. /// - index: The column index. - init?(sqliteStatement: SQLiteStatement, index: CInt) + init?(sqliteStatement: SQLiteStatementBase, index: CInt) } extension StatementColumnConvertible { @@ -128,7 +128,10 @@ extension StatementColumnConvertible { /// Default implementation fails on decoding NULL. @inline(__always) @inlinable - public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt) -> Self? { + public static func fromStatement( + _ sqliteStatement: SQLiteStatementBase, + atUncheckedIndex index: CInt + ) -> Self? { if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { return nil } @@ -298,7 +301,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - returns: A ``FastDatabaseValueCursor`` over fetched values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor( - _ statement: Statement, + _ statement: StatementBase, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws -> FastDatabaseValueCursor @@ -329,7 +332,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - returns: An array of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll( - _ statement: Statement, + _ statement: StatementBase, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws -> [Self] @@ -363,7 +366,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne( - _ statement: Statement, + _ statement: StatementBase, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws -> Self? @@ -401,7 +404,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash /// - returns: A set of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet( - _ statement: Statement, + _ statement: StatementBase, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws -> Set @@ -446,7 +449,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - returns: A ``FastDatabaseValueCursor`` over fetched values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor( - _ db: Database, + _ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil) @@ -478,7 +481,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - returns: An array of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll( - _ db: Database, + _ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil) @@ -513,7 +516,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne( - _ db: Database, + _ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil) @@ -547,7 +550,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash /// - returns: A set of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet( - _ db: Database, + _ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil) @@ -606,7 +609,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - request: A fetch request. /// - returns: A ``FastDatabaseValueCursor`` over fetched values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: some FetchRequest) + public static func fetchCursor(_ db: DatabaseBase, _ request: some FetchRequest) throws -> FastDatabaseValueCursor { let request = try request.makePreparedRequest(db, forSingleResult: false) @@ -649,7 +652,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - request: A fetch request. /// - returns: An array of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] { + public static func fetchAll(_ db: DatabaseBase, _ request: some FetchRequest) throws -> [Self] { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchAll(request.statement, adapter: request.adapter) } @@ -693,7 +696,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - request: A fetch request. /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? { + public static func fetchOne(_ db: DatabaseBase, _ request: some FetchRequest) throws -> Self? { let request = try request.makePreparedRequest(db, forSingleResult: true) return try fetchOne(request.statement, adapter: request.adapter) } @@ -736,7 +739,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash /// - request: A fetch request. /// - returns: A set of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set { + public static func fetchSet(_ db: DatabaseBase, _ request: some FetchRequest) throws -> Set { let request = try request.makePreparedRequest(db, forSingleResult: false) return try fetchSet(request.statement, adapter: request.adapter) } @@ -789,7 +792,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// - parameter db: A database connection. /// - returns: A ``FastDatabaseValueCursor`` over fetched values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> FastDatabaseValueCursor { + public func fetchCursor(_ db: DatabaseBase) throws -> FastDatabaseValueCursor { try RowDecoder.fetchCursor(db, self) } @@ -827,7 +830,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// - parameter db: A database connection. /// - returns: An array of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder] { + public func fetchAll(_ db: DatabaseBase) throws -> [RowDecoder] { try RowDecoder.fetchAll(db, self) } @@ -868,7 +871,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// - parameter db: A database connection. /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> RowDecoder? { + public func fetchOne(_ db: DatabaseBase) throws -> RowDecoder? { try RowDecoder.fetchOne(db, self) } } @@ -908,7 +911,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// - parameter db: A database connection. /// - returns: A set of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchSet(_ db: Database) throws -> Set { + public func fetchSet(_ db: DatabaseBase) throws -> Set { try RowDecoder.fetchSet(db, self) } } diff --git a/GRDB/Core/Support/Foundation/Data.swift b/GRDB/Core/Support/Foundation/Data.swift index fd7d714a0..8bf050537 100644 --- a/GRDB/Core/Support/Foundation/Data.swift +++ b/GRDB/Core/Support/Foundation/Data.swift @@ -1,20 +1,20 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import Foundation /// Data is convertible to and from DatabaseValue. extension Data: DatabaseValueConvertible, StatementColumnConvertible { - public init(sqliteStatement: SQLiteStatement, index: CInt) { + public init(sqliteStatement: SQLiteStatementBase, index: CInt) { if let bytes = sqlite3_column_blob(sqliteStatement, index) { let count = Int(sqlite3_column_bytes(sqliteStatement, index)) self.init(bytes: bytes, count: count) // copy bytes @@ -49,7 +49,7 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible { } } - public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { + public func bind(to sqliteStatement: SQLiteStatementBase, at index: CInt) -> CInt { withUnsafeBytes { sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT) } diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index d857ecbc2..1625f1959 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import Foundation @@ -81,7 +81,7 @@ extension DatabaseDateComponents: StatementColumnConvertible { /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: CInt) { + public init?(sqliteStatement: SQLiteStatementBase, index: CInt) { guard let cString = sqlite3_column_text(sqliteStatement, index) else { return nil } diff --git a/GRDB/Core/Support/Foundation/Date.swift b/GRDB/Core/Support/Foundation/Date.swift index dadc00fd6..22bafb162 100644 --- a/GRDB/Core/Support/Foundation/Date.swift +++ b/GRDB/Core/Support/Foundation/Date.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import Foundation @@ -136,7 +136,7 @@ extension Date: StatementColumnConvertible { /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: CInt) { + public init?(sqliteStatement: SQLiteStatementBase, index: CInt) { switch sqlite3_column_type(sqliteStatement, index) { case SQLITE_INTEGER, SQLITE_FLOAT: self.init(timeIntervalSince1970: sqlite3_column_double(sqliteStatement, index)) diff --git a/GRDB/Core/Support/Foundation/Decimal.swift b/GRDB/Core/Support/Foundation/Decimal.swift index 70d84f3ab..79c474825 100644 --- a/GRDB/Core/Support/Foundation/Decimal.swift +++ b/GRDB/Core/Support/Foundation/Decimal.swift @@ -1,15 +1,15 @@ #if !os(Linux) -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import Foundation @@ -50,7 +50,7 @@ extension Decimal: DatabaseValueConvertible { extension Decimal: StatementColumnConvertible { @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: CInt) { + public init?(sqliteStatement: SQLiteStatementBase, index: CInt) { switch sqlite3_column_type(sqliteStatement, index) { case SQLITE_INTEGER: self.init(sqlite3_column_int64(sqliteStatement, index)) diff --git a/GRDB/Core/Support/Foundation/UUID.swift b/GRDB/Core/Support/Foundation/UUID.swift index 54b18b2c8..4ea54143f 100644 --- a/GRDB/Core/Support/Foundation/UUID.swift +++ b/GRDB/Core/Support/Foundation/UUID.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import Foundation @@ -81,7 +81,7 @@ extension UUID: DatabaseValueConvertible { extension UUID: StatementColumnConvertible { @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: CInt) { + public init?(sqliteStatement: SQLiteStatementBase, index: CInt) { switch sqlite3_column_type(sqliteStatement, index) { case SQLITE_TEXT: let string = String(cString: sqlite3_column_text(sqliteStatement, index)!) diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift index a8c06371a..15ff8a3d7 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+RawRepresentable.swift @@ -20,7 +20,7 @@ extension SQLExpressible where Self: RawRepresentable, Self.RawValue: SQLExpress } extension StatementBinding where Self: RawRepresentable, Self.RawValue: StatementBinding { - public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { + public func bind(to sqliteStatement: SQLiteStatementBase, at index: CInt) -> CInt { rawValue.bind(to: sqliteStatement, at: index) } } @@ -41,7 +41,7 @@ extension StatementBinding where Self: RawRepresentable, Self.RawValue: Statemen extension StatementColumnConvertible where Self: RawRepresentable, Self.RawValue: StatementColumnConvertible { @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: CInt) { + public init?(sqliteStatement: SQLiteStatementBase, index: CInt) { guard let rawValue = RawValue(sqliteStatement: sqliteStatement, index: index) else { return nil } diff --git a/GRDB/Core/Support/StandardLibrary/Optional.swift b/GRDB/Core/Support/StandardLibrary/Optional.swift index 253b06e53..78fdbf00b 100644 --- a/GRDB/Core/Support/StandardLibrary/Optional.swift +++ b/GRDB/Core/Support/StandardLibrary/Optional.swift @@ -1,20 +1,20 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif extension Optional: StatementBinding where Wrapped: StatementBinding { - public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { + public func bind(to sqliteStatement: SQLiteStatementBase, at index: CInt) -> CInt { switch self { case .none: - return sqlite3_bind_null(sqliteStatement, index) + return API.sqlite3_bind_null(sqliteStatement.rawValue, index) case let .some(value): return value.bind(to: sqliteStatement, at: index) } @@ -87,11 +87,11 @@ extension Optional: DatabaseValueConvertible where Wrapped: DatabaseValueConvert extension Optional: StatementColumnConvertible where Wrapped: StatementColumnConvertible { @inline(__always) @inlinable - public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt) -> Self? { + public static func fromStatement(_ sqliteStatement: SQLiteStatementBase, atUncheckedIndex index: CInt) -> Self? { if let value = Wrapped.fromStatement(sqliteStatement, atUncheckedIndex: index) { // Valid value return value - } else if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { + } else if API.sqlite3_column_type(sqliteStatement.rawValue, index) == API.SQLITE_NULL { // NULL return .some(.none) } else { @@ -100,7 +100,7 @@ extension Optional: StatementColumnConvertible where Wrapped: StatementColumnCon } } - public init?(sqliteStatement: SQLiteStatement, index: CInt) { + public init?(sqliteStatement: SQLiteStatementBase, index: CInt) { guard let value = Wrapped(sqliteStatement: sqliteStatement, index: index) else { return nil } diff --git a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift index f967fb837..1115e0e21 100644 --- a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift +++ b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif // MARK: - Value Types @@ -20,8 +20,8 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible { /// - parameters: /// - sqliteStatement: A pointer to an SQLite statement. /// - index: The column index. - public init(sqliteStatement: SQLiteStatement, index: CInt) { - self = sqlite3_column_int64(sqliteStatement, index) != 0 + public init(sqliteStatement: SQLiteStatementBase, index: CInt) { + self = API.sqlite3_column_int64(sqliteStatement.rawValue, index) != 0 } /// Returns an INTEGER database value. @@ -102,8 +102,8 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible { } } - public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { - sqlite3_bind_int64(sqliteStatement, index, self ? 1 : 0) + public func bind(to sqliteStatement: SQLiteStatementBase, at index: CInt) -> CInt { + API.sqlite3_bind_int64(sqliteStatement.rawValue, index, self ? 1 : 0) } } @@ -117,8 +117,8 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible { /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: CInt) { - let int64 = sqlite3_column_int64(sqliteStatement, index) + public init?(sqliteStatement: SQLiteStatementBase, index: CInt) { + let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index) guard let v = Int(exactly: int64) else { return nil } self = v } @@ -141,8 +141,8 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible { Int64.fromDatabaseValue(dbValue).flatMap { Int(exactly: $0) } } - public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { - sqlite3_bind_int64(sqliteStatement, index, Int64(self)) + public func bind(to sqliteStatement: SQLiteStatementBase, at index: CInt) -> CInt { + API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self)) } } @@ -156,8 +156,8 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible { /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: CInt) { - let int64 = sqlite3_column_int64(sqliteStatement, index) + public init?(sqliteStatement: SQLiteStatementBase, index: CInt) { + let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index) guard let v = Int8(exactly: int64) else { return nil } self = v } @@ -180,8 +180,8 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible { Int64.fromDatabaseValue(dbValue).flatMap { Int8(exactly: $0) } } - public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { - sqlite3_bind_int64(sqliteStatement, index, Int64(self)) + public func bind(to sqliteStatement: SQLiteStatementBase, at index: CInt) -> CInt { + API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self)) } } @@ -195,8 +195,8 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible { /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: CInt) { - let int64 = sqlite3_column_int64(sqliteStatement, index) + public init?(sqliteStatement: SQLiteStatementBase, index: CInt) { + let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index) guard let v = Int16(exactly: int64) else { return nil } self = v } @@ -219,8 +219,8 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible { Int64.fromDatabaseValue(dbValue).flatMap { Int16(exactly: $0) } } - public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { - sqlite3_bind_int64(sqliteStatement, index, Int64(self)) + public func bind(to sqliteStatement: SQLiteStatementBase, at index: CInt) -> CInt { + API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self)) } } @@ -234,8 +234,8 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible { /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: CInt) { - let int64 = sqlite3_column_int64(sqliteStatement, index) + public init?(sqliteStatement: SQLiteStatementBase, index: CInt) { + let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index) guard let v = Int32(exactly: int64) else { return nil } self = v } @@ -258,8 +258,8 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible { Int64.fromDatabaseValue(dbValue).flatMap { Int32(exactly: $0) } } - public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { - sqlite3_bind_int64(sqliteStatement, index, Int64(self)) + public func bind(to sqliteStatement: SQLiteStatementBase, at index: CInt) -> CInt { + API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self)) } } @@ -271,8 +271,8 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible { /// - parameters: /// - sqliteStatement: A pointer to an SQLite statement. /// - index: The column index. - public init(sqliteStatement: SQLiteStatement, index: CInt) { - self = sqlite3_column_int64(sqliteStatement, index) + public init(sqliteStatement: SQLiteStatementBase, index: CInt) { + self = API.sqlite3_column_int64(sqliteStatement.rawValue, index) } /// Returns an INTEGER database value. @@ -301,8 +301,8 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible { } } - public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { - sqlite3_bind_int64(sqliteStatement, index, self) + public func bind(to sqliteStatement: SQLiteStatementBase, at index: CInt) -> CInt { + API.sqlite3_bind_int64(sqliteStatement.rawValue, index, self) } } @@ -316,8 +316,8 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible { /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: CInt) { - let int64 = sqlite3_column_int64(sqliteStatement, index) + public init?(sqliteStatement: SQLiteStatementBase, index: CInt) { + let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index) guard let v = UInt(exactly: int64) else { return nil } self = v } @@ -340,8 +340,8 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible { Int64.fromDatabaseValue(dbValue).flatMap { UInt(exactly: $0) } } - public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { - sqlite3_bind_int64(sqliteStatement, index, Int64(self)) + public func bind(to sqliteStatement: SQLiteStatementBase, at index: CInt) -> CInt { + API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self)) } } @@ -355,8 +355,8 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible { /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: CInt) { - let int64 = sqlite3_column_int64(sqliteStatement, index) + public init?(sqliteStatement: SQLiteStatementBase, index: CInt) { + let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index) guard let v = UInt8(exactly: int64) else { return nil } self = v } @@ -379,8 +379,8 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible { Int64.fromDatabaseValue(dbValue).flatMap { UInt8(exactly: $0) } } - public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { - sqlite3_bind_int64(sqliteStatement, index, Int64(self)) + public func bind(to sqliteStatement: SQLiteStatementBase, at index: CInt) -> CInt { + API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self)) } } @@ -394,8 +394,8 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible { /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: CInt) { - let int64 = sqlite3_column_int64(sqliteStatement, index) + public init?(sqliteStatement: SQLiteStatementBase, index: CInt) { + let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index) guard let v = UInt16(exactly: int64) else { return nil } self = v } @@ -418,8 +418,8 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible { Int64.fromDatabaseValue(dbValue).flatMap { UInt16(exactly: $0) } } - public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { - sqlite3_bind_int64(sqliteStatement, index, Int64(self)) + public func bind(to sqliteStatement: SQLiteStatementBase, at index: CInt) -> CInt { + API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self)) } } @@ -433,8 +433,8 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible { /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: CInt) { - let int64 = sqlite3_column_int64(sqliteStatement, index) + public init?(sqliteStatement: SQLiteStatementBase, index: CInt) { + let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index) guard let v = UInt32(exactly: int64) else { return nil } self = v } @@ -457,8 +457,8 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible { Int64.fromDatabaseValue(dbValue).flatMap { UInt32(exactly: $0) } } - public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { - sqlite3_bind_int64(sqliteStatement, index, Int64(self)) + public func bind(to sqliteStatement: SQLiteStatementBase, at index: CInt) -> CInt { + API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self)) } } @@ -472,8 +472,8 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible { /// - index: The column index. @inline(__always) @inlinable - public init?(sqliteStatement: SQLiteStatement, index: CInt) { - let int64 = sqlite3_column_int64(sqliteStatement, index) + public init?(sqliteStatement: SQLiteStatementBase, index: CInt) { + let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index) guard let v = UInt64(exactly: int64) else { return nil } self = v } @@ -496,8 +496,8 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible { Int64.fromDatabaseValue(dbValue).flatMap { UInt64(exactly: $0) } } - public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { - sqlite3_bind_int64(sqliteStatement, index, Int64(self)) + public func bind(to sqliteStatement: SQLiteStatementBase, at index: CInt) -> CInt { + API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self)) } } @@ -509,8 +509,8 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible { /// - parameters: /// - sqliteStatement: A pointer to an SQLite statement. /// - index: The column index. - public init(sqliteStatement: SQLiteStatement, index: CInt) { - self = sqlite3_column_double(sqliteStatement, index) + public init(sqliteStatement: SQLiteStatementBase, index: CInt) { + self = API.sqlite3_column_double(sqliteStatement.rawValue, index) } /// Returns a REAL database value. @@ -536,8 +536,8 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible { } } - public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { - sqlite3_bind_double(sqliteStatement, index, self) + public func bind(to sqliteStatement: SQLiteStatementBase, at index: CInt) -> CInt { + API.sqlite3_bind_double(sqliteStatement.rawValue, index, self) } } @@ -549,8 +549,8 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible { /// - parameters: /// - sqliteStatement: A pointer to an SQLite statement. /// - index: The column index. - public init(sqliteStatement: SQLiteStatement, index: CInt) { - self = Float(sqlite3_column_double(sqliteStatement, index)) + public init(sqliteStatement: SQLiteStatementBase, index: CInt) { + self = Float(API.sqlite3_column_double(sqliteStatement.rawValue, index)) } /// Returns a REAL database value. @@ -576,8 +576,8 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible { } } - public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { - sqlite3_bind_double(sqliteStatement, index, Double(self)) + public func bind(to sqliteStatement: SQLiteStatementBase, at index: CInt) -> CInt { + API.sqlite3_bind_double(sqliteStatement.rawValue, index, Double(self)) } } @@ -589,8 +589,8 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible { /// - parameters: /// - sqliteStatement: A pointer to an SQLite statement. /// - index: The column index. - public init(sqliteStatement: SQLiteStatement, index: CInt) { - self = String(cString: sqlite3_column_text(sqliteStatement, index)!) + public init(sqliteStatement: SQLiteStatementBase, index: CInt) { + self = String(cString: API.sqlite3_column_text(sqliteStatement.rawValue, index)!) } /// Returns a TEXT database value. @@ -619,8 +619,8 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible { } } - public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { - sqlite3_bind_text(sqliteStatement, index, self, -1, SQLITE_TRANSIENT) + public func bind(to sqliteStatement: SQLiteStatementBase, at index: CInt) -> CInt { + API.sqlite3_bind_text(sqliteStatement.rawValue, index, self, -1, SQLITE_TRANSIENT) } /// Calls the given closure after binding a statement argument. @@ -630,9 +630,9 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible { /// - parameter sqliteStatement: An SQLite statement. /// - parameter index: 1-based index to statement arguments. /// - parameter body: The closure to execute when argument is bound. - func withBinding(to sqliteStatement: SQLiteStatement, at index: CInt, do body: () throws -> T) throws -> T { + func withBinding(to sqliteStatement: SQLiteStatementBase, at index: CInt, do body: () throws -> T) throws -> T { try withCString { - let code = sqlite3_bind_text(sqliteStatement, index, $0, -1, nil /* SQLITE_STATIC */) + let code = API.sqlite3_bind_text(sqliteStatement.rawValue, index, $0, -1, nil /* SQLITE_STATIC */) try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement) return try body() } diff --git a/GRDB/Core/TransactionClock.swift b/GRDB/Core/TransactionClock.swift index b467ce724..d7e5911f8 100644 --- a/GRDB/Core/TransactionClock.swift +++ b/GRDB/Core/TransactionClock.swift @@ -10,7 +10,9 @@ import Foundation /// /// - ``DefaultTransactionClock`` /// - ``CustomTransactionClock`` -public protocol TransactionClock: Sendable { +public protocol TransactionClock: Sendable { + associatedtype API: SQLiteAPI + /// Returns the date of the current transaction. /// /// This function is called whenever a transaction starts - precisely @@ -20,31 +22,33 @@ public protocol TransactionClock: Sendable { /// called, and the database connection is not in a transaction. /// /// Related SQLite documentation: - func now(_ db: Database) throws -> Date + func now(_ db: DatabaseBase) throws -> Date } -extension TransactionClock where Self == DefaultTransactionClock { - /// Returns the default clock. - public static var `default`: Self { DefaultTransactionClock() } -} +#warning("TODO: expose a version with default api") +//extension TransactionClock where Self == DefaultTransactionClock { +// /// Returns the default clock. +// public static var `default`: Self { DefaultTransactionClock() } +//} -extension TransactionClock where Self == CustomTransactionClock { - /// Returns a custom clock. - /// - /// The provided closure is called whenever a transaction starts - precisely - /// speaking, whenever the database connection leaves the auto-commit mode. - /// - /// It is also called when the ``Database/transactionDate`` property is - /// called, and the database connection is not in a transaction. - public static func custom(_ now: @escaping @Sendable (Database) throws -> Date) -> Self { - CustomTransactionClock(now) - } -} +#warning("TODO: expose a version with default api") +//extension TransactionClock where Self == CustomTransactionClock { +// /// Returns a custom clock. +// /// +// /// The provided closure is called whenever a transaction starts - precisely +// /// speaking, whenever the database connection leaves the auto-commit mode. +// /// +// /// It is also called when the ``Database/transactionDate`` property is +// /// called, and the database connection is not in a transaction. +// public static func custom(_ now: @escaping @Sendable (Database) throws -> Date) -> Self { +// CustomTransactionClock(now) +// } +//} /// The default transaction clock. -public struct DefaultTransactionClock: TransactionClock { +public struct DefaultTransactionClock: TransactionClock { /// Returns the start date of the current transaction. - public func now(_ db: Database) throws -> Date { + public func now(_ db: DatabaseBase) throws -> Date { // An opportunity to fetch transaction time from the database when // SQLite supports the feature. Date() @@ -52,14 +56,14 @@ public struct DefaultTransactionClock: TransactionClock { } /// A custom transaction clock. -public struct CustomTransactionClock: TransactionClock { - let _now: @Sendable (Database) throws -> Date +public struct CustomTransactionClock: TransactionClock { + let _now: @Sendable (DatabaseBase) throws -> Date - public init(_ now: @escaping @Sendable (Database) throws -> Date) { + public init(_ now: @escaping @Sendable (DatabaseBase) throws -> Date) { self._now = now } - public func now(_ db: Database) throws -> Date { + public func now(_ db: DatabaseBase) throws -> Date { try _now(db) } } diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 67212aad6..dafe18bf1 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -1,16 +1,16 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif -extension Database { +extension DatabaseBase { // MARK: - Database Observation @@ -33,8 +33,8 @@ extension Database { /// the observer lifetime (observation lasts until observer /// is deallocated). public func add( - transactionObserver: some TransactionObserver, - extent: TransactionObservationExtent = .observerLifetime) + transactionObserver: some TransactionObserverBase, + extent: DatabaseTransactionObservationExtent = .observerLifetime) { SchedulingWatchdog.preconditionValidQueue(self) guard let observationBroker else { return } @@ -57,7 +57,7 @@ extension Database { /// db.remove(transactionObserver: myObserver) /// } /// ``` - public func remove(transactionObserver: some TransactionObserver) { + public func remove(transactionObserver: some TransactionObserverBase) { SchedulingWatchdog.preconditionValidQueue(self) guard let observationBroker else { return } @@ -82,7 +82,7 @@ extension Database { /// ```swift /// /// Inserts a region in the database, and start monitoring upon /// /// successful insertion. - /// func startMonitoring(_ db: Database, region: CLRegion) throws { + /// func startMonitoring(_ db: DatabaseBase, region: CLRegion) throws { /// // Make sure database is inside a transaction /// try db.inSavepoint { /// @@ -113,34 +113,9 @@ extension Database { /// - parameter onCommit: A closure executed on transaction commit. /// - parameter onRollback: A closure executed on transaction rollback. public func afterNextTransaction( - onCommit: @escaping @Sendable (Database) -> Void, - onRollback: @escaping @Sendable (Database) -> Void = { _ in }) + onCommit: @escaping @Sendable (DatabaseBase) -> Void, + onRollback: @escaping @Sendable (DatabaseBase) -> Void = { _ in }) { - class TransactionHandler: TransactionObserver { - let onCommit: @Sendable (Database) -> Void - let onRollback: @Sendable (Database) -> Void - - init( - onCommit: @escaping @Sendable (Database) -> Void, - onRollback: @escaping @Sendable (Database) -> Void - ) { - self.onCommit = onCommit - self.onRollback = onRollback - } - - // Ignore changes - func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false } - func databaseDidChange(with event: DatabaseEvent) { } - - func databaseDidCommit(_ db: Database) { - onCommit(db) - } - - func databaseDidRollback(_ db: Database) { - onRollback(db) - } - } - // We don't notify read-only transactions to transaction observers GRDBPrecondition(!isReadOnly, "Read-only transactions are not notified") @@ -148,16 +123,42 @@ extension Database { transactionObserver: TransactionHandler(onCommit: onCommit, onRollback: onRollback), extent: .nextTransaction) } - - /// The extent of the observation performed by a ``TransactionObserver``. - public enum TransactionObservationExtent: Sendable { - /// Observation lasts until observer is deallocated. - case observerLifetime - /// Observation lasts until the next transaction. - case nextTransaction - /// Observation lasts until the database is closed. - case databaseLifetime +} + +fileprivate class TransactionHandler: TransactionObserverBase { + let onCommit: @Sendable (DatabaseBase) -> Void + let onRollback: @Sendable (DatabaseBase) -> Void + + init( + onCommit: @escaping @Sendable (DatabaseBase) -> Void, + onRollback: @escaping @Sendable (DatabaseBase) -> Void + ) { + self.onCommit = onCommit + self.onRollback = onRollback } + + // Ignore changes + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false } + func databaseDidChange(with event: DatabaseEvent) { } + + func databaseDidCommit(_ db: DatabaseBase) { + onCommit(db) + } + + func databaseDidRollback(_ db: DatabaseBase) { + onRollback(db) + } +} + +#warning("TODO: export as Database.TransactionObservationExtent") +/// The extent of the observation performed by a ``TransactionObserver``. +public enum DatabaseTransactionObservationExtent: Sendable { + /// Observation lasts until observer is deallocated. + case observerLifetime + /// Observation lasts until the next transaction. + case nextTransaction + /// Observation lasts until the database is closed. + case databaseLifetime } // MARK: - DatabaseObservationBroker @@ -170,8 +171,8 @@ extension Database { /// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool /// func databaseDidChange(with event: DatabaseEvent) /// func databaseWillCommit() throws -/// func databaseDidCommit(_ db: Database) -/// func databaseDidRollback(_ db: Database) +/// func databaseDidCommit(_ db: DatabaseBase) +/// func databaseDidRollback(_ db: DatabaseBase) /// } /// /// First observer is added, and a transaction is started. At this point, @@ -244,8 +245,8 @@ extension Database { /// /// After the statement *has been executed*, the broker calls /// observer.databaseDidCommit(). -class DatabaseObservationBroker { - private unowned let database: Database +class DatabaseObservationBroker { + private unowned let database: DatabaseBase /// The savepoint stack allows us to hold database event notifications until /// all savepoints are released. The goal is to only tell transaction @@ -258,10 +259,10 @@ class DatabaseObservationBroker { private var transactionCompletion = TransactionCompletion.none /// The registered transaction observers. - private var transactionObservations: [TransactionObservation] = [] + private var transactionObservations: [TransactionObservation] = [] /// The observers for an individual statement execution. - private var statementObservations: [StatementObservation] = [] { + private var statementObservations: [StatementObservation] = [] { didSet { let isEmpty = statementObservations.isEmpty if isEmpty != oldValue.isEmpty { @@ -275,22 +276,22 @@ class DatabaseObservationBroker { } } - init(_ database: Database) { + init(_ database: DatabaseBase) { self.database = database } // MARK: - Transaction observers - func add(transactionObserver: some TransactionObserver, extent: Database.TransactionObservationExtent) { + func add(transactionObserver: some TransactionObserverBase, extent: DatabaseTransactionObservationExtent) { transactionObservations.append(TransactionObservation(observer: transactionObserver, extent: extent)) } - func remove(transactionObserver: some TransactionObserver) { + func remove(transactionObserver: some TransactionObserverBase) { transactionObservations.removeFirst { $0.isWrapping(transactionObserver) } } /// Called from ``TransactionObserver/stopObservingDatabaseChangesUntilNextTransaction()``. - func disableUntilNextTransaction(transactionObserver: some TransactionObserver) { + func disableUntilNextTransaction(transactionObserver: some TransactionObserverBase) { if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver) }) { observation.isEnabled = false statementObservations.removeFirst { $0.transactionObservation === observation } @@ -322,7 +323,7 @@ class DatabaseObservationBroker { } /// Prepares observation of changes that are about to be performed by the statement. - func statementWillExecute(_ statement: Statement) { + func statementWillExecute(_ statement: StatementBase) { if !database.isReadOnly && !transactionObservations.isEmpty { // As statement executes, it may trigger database changes that will // be notified to transaction observers. As a consequence, observers @@ -398,7 +399,7 @@ class DatabaseObservationBroker { /// May throw the user-provided cancelled commit error, if a transaction /// observer has cancelled a transaction. - func statementDidFail(_ statement: Statement) throws { + func statementDidFail(_ statement: StatementBase) throws { // Undo statementWillExecute statementObservations = [] SchedulingWatchdog.current!.databaseObservationBroker = nil @@ -425,7 +426,7 @@ class DatabaseObservationBroker { /// May throw the user-provided cancelled commit error, if the statement /// commits an empty transaction, and a transaction observer cancels this /// empty transaction. - func statementDidExecute(_ statement: Statement) throws { + func statementDidExecute(_ statement: StatementBase) throws { // Undo statementWillExecute if transactionObservations.isEmpty == false { statementObservations = [] @@ -711,7 +712,7 @@ class DatabaseObservationBroker { func installCommitAndRollbackHooks() { let brokerPointer = Unmanaged.passUnretained(self).toOpaque() - sqlite3_commit_hook(database.sqliteConnection, { brokerPointer in + API.sqlite3_commit_hook(database.sqliteConnection, { brokerPointer in let broker = Unmanaged.fromOpaque(brokerPointer!).takeUnretainedValue() do { try broker.databaseWillCommit() @@ -725,7 +726,7 @@ class DatabaseObservationBroker { } }, brokerPointer) - sqlite3_rollback_hook(database.sqliteConnection, { brokerPointer in + API.sqlite3_rollback_hook(database.sqliteConnection, { brokerPointer in let broker = Unmanaged.fromOpaque(brokerPointer!).takeUnretainedValue() switch broker.transactionCompletion { case .cancelledCommit: @@ -741,7 +742,7 @@ class DatabaseObservationBroker { private func installUpdateHook() { let brokerPointer = Unmanaged.passUnretained(self).toOpaque() - sqlite3_update_hook( + API.sqlite3_update_hook( database.sqliteConnection, { (brokerPointer, updateKind, databaseNameCString, tableNameCString, rowID) in let broker = Unmanaged.fromOpaque(brokerPointer!).takeUnretainedValue() @@ -774,7 +775,7 @@ class DatabaseObservationBroker { } private func uninstallUpdateHook() { - sqlite3_update_hook(database.sqliteConnection, nil, nil) + API.sqlite3_update_hook(database.sqliteConnection, nil, nil) #if SQLITE_ENABLE_PREUPDATE_HOOK sqlite3_preupdate_hook(database.sqliteConnection, nil, nil) #endif @@ -800,7 +801,8 @@ class DatabaseObservationBroker { // MARK: - TransactionObserver -public protocol TransactionObserver: AnyObject { +public protocol TransactionObserverBase: AnyObject { + associatedtype API: SQLiteAPI /// Returns whether specific kinds of database changes should be notified /// to the observer. @@ -864,10 +866,10 @@ public protocol TransactionObserver: AnyObject { func databaseWillCommit() throws /// Called when a transaction has been committed on disk. - func databaseDidCommit(_ db: Database) + func databaseDidCommit(_ db: DatabaseBase) /// Called when a transaction has been rollbacked. - func databaseDidRollback(_ db: Database) + func databaseDidRollback(_ db: DatabaseBase) #if SQLITE_ENABLE_PREUPDATE_HOOK /// Called when the database is changed by an insert, update, or @@ -901,7 +903,7 @@ public protocol TransactionObserver: AnyObject { #endif } -extension TransactionObserver { +extension TransactionObserverBase { /// The default implementation does nothing. public func databaseWillCommit() throws { } @@ -963,22 +965,25 @@ extension TransactionObserver { // MARK: - TransactionObservation /// This class manages the observation extent of a transaction observer -final class TransactionObservation { - let extent: Database.TransactionObservationExtent +final class TransactionObservation { + let extent: DatabaseTransactionObservationExtent /// A disabled observation is not interested in individual database changes. /// It is still interested in transactions commits & rollbacks. var isEnabled = true - private weak var weakObserver: (any TransactionObserver)? - private var strongObserver: (any TransactionObserver)? - private var observer: (any TransactionObserver)? { strongObserver ?? weakObserver } + private weak var weakObserver: (any TransactionObserverBase)? + private var strongObserver: (any TransactionObserverBase)? + private var observer: (any TransactionObserverBase)? { + if let strongObserver { return strongObserver } + return weakObserver + } fileprivate var isObserving: Bool { observer != nil } - init(observer: some TransactionObserver, extent: Database.TransactionObservationExtent) { + init(observer: some TransactionObserverBase, extent: DatabaseTransactionObservationExtent) { self.extent = extent switch extent { case .observerLifetime: @@ -991,7 +996,7 @@ final class TransactionObservation { } } - func isWrapping(_ observer: some TransactionObserver) -> Bool { + func isWrapping(_ observer: some TransactionObserverBase) -> Bool { self.observer === observer } @@ -1020,7 +1025,7 @@ final class TransactionObservation { try observer?.databaseWillCommit() } - func databaseDidCommit(_ db: Database) { + func databaseDidCommit(_ db: DatabaseBase) { switch extent { case .observerLifetime, .databaseLifetime: observer?.databaseDidCommit(db) @@ -1036,7 +1041,7 @@ final class TransactionObservation { } } - func databaseDidRollback(_ db: Database) { + func databaseDidRollback(_ db: DatabaseBase) { switch extent { case .observerLifetime, .databaseLifetime: observer?.databaseDidRollback(db) @@ -1055,8 +1060,8 @@ final class TransactionObservation { /// The observation of one particular statement, by a particular /// transaction observer. -struct StatementObservation { - var transactionObservation: TransactionObservation +struct StatementObservation { + var transactionObservation: TransactionObservation /// A predicate that filters database events that should be notified. /// @@ -1067,7 +1072,7 @@ struct StatementObservation { /// ``` var tracksEvent: DatabaseEventPredicate - init(transactionObservation: TransactionObservation, trackingEvents predicate: DatabaseEventPredicate) { + init(transactionObservation: TransactionObservation, trackingEvents predicate: DatabaseEventPredicate) { self.transactionObservation = transactionObservation self.tracksEvent = predicate } diff --git a/GRDB/Core/WALSnapshot.swift b/GRDB/Core/WALSnapshot.swift index 729a8ac80..378860ade 100644 --- a/GRDB/Core/WALSnapshot.swift +++ b/GRDB/Core/WALSnapshot.swift @@ -1,15 +1,15 @@ #if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif /// An instance of WALSnapshot records the state of a WAL mode database for some /// specific point in history. @@ -25,12 +25,12 @@ final class WALSnapshot: @unchecked Sendable { // let sqliteSnapshot: UnsafeMutablePointer - init(_ db: Database) throws { + init(_ db: DatabaseBase) throws { var sqliteSnapshot: UnsafeMutablePointer? let code = withUnsafeMutablePointer(to: &sqliteSnapshot) { return sqlite3_snapshot_get(db.sqliteConnection, "main", $0) } - guard code == SQLITE_OK else { + guard code == API.SQLITE_OK else { // // // > The following must be true for sqlite3_snapshot_get() to succeed. [...] diff --git a/GRDB/Core/WALSnapshotTransaction.swift b/GRDB/Core/WALSnapshotTransaction.swift index 22f6c90a7..733118b7c 100644 --- a/GRDB/Core/WALSnapshotTransaction.swift +++ b/GRDB/Core/WALSnapshotTransaction.swift @@ -3,11 +3,11 @@ /// /// `WALSnapshotTransaction` **takes ownership** of its reader /// `SerializedDatabase` (TODO: make it a move-only type eventually). -final class WALSnapshotTransaction: @unchecked Sendable { +final class WALSnapshotTransactionBase: @unchecked Sendable { // @unchecked because `databaseAccess` is protected by a mutex. private struct DatabaseAccess { - let reader: SerializedDatabase + let reader: SerializedDatabaseBase let release: @Sendable (_ isInsideTransaction: Bool) -> Void // MUST be called only once @@ -60,7 +60,7 @@ final class WALSnapshotTransaction: @unchecked Sendable { /// - parameter release: A closure to call when the read-only connection /// is no longer used. init( - onReader reader: SerializedDatabase, + onReader reader: SerializedDatabaseBase, release: @escaping @Sendable (_ isInsideTransaction: Bool) -> Void) throws { @@ -90,7 +90,7 @@ final class WALSnapshotTransaction: @unchecked Sendable { /// Executes database operations in the snapshot transaction, and /// returns their result after they have finished executing. - func read(_ value: (Database) throws -> T) throws -> T { + func read(_ value: (DatabaseBase) throws -> T) throws -> T { try databaseAccessMutex.withLock { databaseAccess in guard let databaseAccess else { throw DatabaseError.snapshotIsLost() @@ -103,7 +103,7 @@ final class WALSnapshotTransaction: @unchecked Sendable { /// Schedules database operations for execution, and /// returns immediately. - func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { + func asyncRead(_ value: @escaping @Sendable (Result, Error>) -> Void) { databaseAccessMutex.withLock { databaseAccess in guard let databaseAccess else { value(.failure(DatabaseError.snapshotIsLost())) diff --git a/GRDB/Documentation.docc/Extension/DatabaseValueConvertible.md b/GRDB/Documentation.docc/Extension/DatabaseValueConvertible.md index e450d9fbd..00903b822 100644 --- a/GRDB/Documentation.docc/Extension/DatabaseValueConvertible.md +++ b/GRDB/Documentation.docc/Extension/DatabaseValueConvertible.md @@ -128,7 +128,7 @@ For example: ```swift extension EvenInteger: StatementColumnConvertible { - init?(sqliteStatement: SQLiteStatement, index: CInt) { + init?(sqliteStatement: SQLiteStatementBase, index: CInt) { let int64 = sqlite3_column_int64(sqliteStatement, index) guard let value = Int(exactly: int64) else { return nil // Does not fit Int (probably a 32-bit architecture) diff --git a/GRDB/Documentation.docc/RecordTimestamps.md b/GRDB/Documentation.docc/RecordTimestamps.md index 32689234d..fefc6b1f1 100644 --- a/GRDB/Documentation.docc/RecordTimestamps.md +++ b/GRDB/Documentation.docc/RecordTimestamps.md @@ -69,7 +69,7 @@ On insertion, the `Player` record should get fresh `creationDate` and `modificat extension Player: Encodable, MutablePersistableRecord { /// Sets both `creationDate` and `modificationDate` to the /// transaction date, if they are not set yet. - mutating func willInsert(_ db: Database) throws { + mutating func willInsert(_ db: DatabaseBase) throws { if creationDate == nil { creationDate = try db.transactionDate } @@ -182,7 +182,7 @@ extension Player: Encodable, MutablePersistableRecord { /// Sets both `creationDate` and `modificationDate` to the /// transaction date, if they are not set yet. - mutating func willInsert(_ db: Database) throws { + mutating func willInsert(_ db: DatabaseBase) throws { if creationDate == nil { creationDate = try db.transactionDate } @@ -311,7 +311,7 @@ You can copy it in your application, or use it as an inspiration. Not all apps h extension Player { /// If the player has a non-nil primary key and a matching row in /// the database, the player is updated. Otherwise, it is inserted. - mutating func saveWithTimestamp(_ db: Database) throws { + mutating func saveWithTimestamp(_ db: DatabaseBase) throws { // Test the presence of id first, so that we don't perform an // update that would surely throw RecordError.recordNotFound. if id == nil { @@ -346,7 +346,7 @@ extension TimestampedRecord { /// `TimestampedRecord` types that customize the `willInsert` /// persistence callback should call `initializeTimestamps` from /// their implementation. - mutating func willInsert(_ db: Database) throws { + mutating func willInsert(_ db: DatabaseBase) throws { try initializeTimestamps(db) } @@ -356,7 +356,7 @@ extension TimestampedRecord { /// It is called automatically before insertion, if your type does not /// customize the `willInsert` persistence callback. If you customize /// this callback, call `initializeTimestamps` from your implementation. - mutating func initializeTimestamps(_ db: Database) throws { + mutating func initializeTimestamps(_ db: DatabaseBase) throws { if creationDate == nil { creationDate = try db.transactionDate } @@ -370,7 +370,7 @@ extension TimestampedRecord { /// /// - parameter modificationDate: The modification date. If nil, the /// transaction date is used. - mutating func updateWithTimestamp(_ db: Database, modificationDate: Date? = nil) throws { + mutating func updateWithTimestamp(_ db: DatabaseBase, modificationDate: Date? = nil) throws { self.modificationDate = try modificationDate ?? db.transactionDate try update(db) } @@ -403,7 +403,7 @@ extension TimestampedRecord { /// - returns: Whether the record was changed and updated. @discardableResult mutating func updateChangesWithTimestamp( - _ db: Database, + _ db: DatabaseBase, modificationDate: Date? = nil, modify: (inout Self) -> Void) throws -> Bool @@ -431,7 +431,7 @@ extension TimestampedRecord { /// /// - parameter modificationDate: The modification date. If nil, the /// transaction date is used. - mutating func touch(_ db: Database, modificationDate: Date? = nil) throws { + mutating func touch(_ db: DatabaseBase, modificationDate: Date? = nil) throws { try updateChanges(db) { $0.modificationDate = try modificationDate ?? db.transactionDate } diff --git a/GRDB/Documentation.docc/SingleRowTables.md b/GRDB/Documentation.docc/SingleRowTables.md index b3c842fcf..84399efdf 100644 --- a/GRDB/Documentation.docc/SingleRowTables.md +++ b/GRDB/Documentation.docc/SingleRowTables.md @@ -128,7 +128,7 @@ We have seen in the section that by d ```swift // Customize the default PersistableRecord behavior - func willUpdate(_ db: Database, columns: Set) throws { + func willUpdate(_ db: DatabaseBase, columns: Set) throws { // Insert the default configuration if it does not exist yet. if try !exists(db) { try AppConfiguration.default.insert(db) @@ -141,7 +141,7 @@ The standard GRDB method ``FetchableRecord/fetchOne(_:)`` returns an optional wh ```swift /// Returns the persisted configuration, or the default one if the /// database table is empty. - static func find(_ db: Database) throws -> AppConfiguration { + static func find(_ db: DatabaseBase) throws -> AppConfiguration { try fetchOne(db) ?? .default } } @@ -233,7 +233,7 @@ extension AppConfiguration { // Database Access extension AppConfiguration: FetchableRecord, PersistableRecord { // Customize the default PersistableRecord behavior - func willUpdate(_ db: Database, columns: Set) throws { + func willUpdate(_ db: DatabaseBase, columns: Set) throws { // Insert the default configuration if it does not exist yet. if try !exists(db) { try AppConfiguration.default.insert(db) @@ -242,7 +242,7 @@ extension AppConfiguration: FetchableRecord, PersistableRecord { /// Returns the persisted configuration, or the default one if the /// database table is empty. - static func find(_ db: Database) throws -> AppConfiguration { + static func find(_ db: DatabaseBase) throws -> AppConfiguration { try fetchOne(db) ?? .default } } diff --git a/GRDB/Documentation.docc/SwiftConcurrency.md b/GRDB/Documentation.docc/SwiftConcurrency.md index 35ce83c57..e15246b9a 100644 --- a/GRDB/Documentation.docc/SwiftConcurrency.md +++ b/GRDB/Documentation.docc/SwiftConcurrency.md @@ -55,7 +55,7 @@ let count = try await writer.read { db in } // Shorthand notation: -// ⚠️ Converting non-sendable function value to '@Sendable (Database) +// ⚠️ Converting non-sendable function value to '@Sendable (DatabaseBase) // throws -> Int' may introduce data races. let count = try await writer.read(Player.fetchCount) ``` diff --git a/GRDB/Documentation.docc/Transactions.md b/GRDB/Documentation.docc/Transactions.md index 469ffd953..36394bf60 100644 --- a/GRDB/Documentation.docc/Transactions.md +++ b/GRDB/Documentation.docc/Transactions.md @@ -160,7 +160,7 @@ This restriction can be left with the ``Configuration/allowsUnsafeTransactions`` It is possible to ask if a transaction is currently opened: ```swift -func myCriticalMethod(_ db: Database) throws { +func myCriticalMethod(_ db: DatabaseBase) throws { precondition(db.isInsideTransaction, "This method requires a transaction") try ... } @@ -169,7 +169,7 @@ func myCriticalMethod(_ db: Database) throws { Yet, there is a better option than checking for transactions. Critical database sections should use savepoints, described below: ```swift -func myCriticalMethod(_ db: Database) throws { +func myCriticalMethod(_ db: DatabaseBase) throws { try db.inSavepoint { // Here the database is guaranteed to be inside a transaction. try ... diff --git a/GRDB/Documentation.docc/ViewRecords.md b/GRDB/Documentation.docc/ViewRecords.md index 5b256e264..714c7ea96 100644 --- a/GRDB/Documentation.docc/ViewRecords.md +++ b/GRDB/Documentation.docc/ViewRecords.md @@ -125,7 +125,7 @@ To instruct GRDB about the primary key, define a **schema source**, a type that struct GameSchemaSource: DatabaseSchemaSource { /// Returns the names of the columns for the primary key in the /// provided database view. - func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + func columnsForPrimaryKey(_ db: DatabaseBase, inView view: DatabaseObjectID) throws -> [String]? { ["id"] } } diff --git a/GRDB/Dump/Database+Dump.swift b/GRDB/Dump/Database+Dump.swift index 43d8bae20..afb1af475 100644 --- a/GRDB/Dump/Database+Dump.swift +++ b/GRDB/Dump/Database+Dump.swift @@ -2,7 +2,7 @@ import Foundation // MARK: - Dump -extension Database { +extension DatabaseBase { /// Prints the results of all statements in the provided SQL. /// /// For example: @@ -183,7 +183,7 @@ extension Database { // MARK: - -extension Database { +extension DatabaseBase { func _dumpStatements( _ statements: some Cursor, format: some DumpFormat, @@ -317,8 +317,8 @@ extension Database { } private func ignoresObject(named name: String) throws -> Bool { - if Database.isSQLiteInternalTable(name) { return true } - if Database.isGRDBInternalTable(name) { return true } + if Self.isSQLiteInternalTable(name) { return true } + if Self.isGRDBInternalTable(name) { return true } if try isShadowTable(name) { return true } return false } diff --git a/GRDB/Dump/DatabaseReader+dump.swift b/GRDB/Dump/DatabaseReader+dump.swift index cbe3e922d..7864fe4d0 100644 --- a/GRDB/Dump/DatabaseReader+dump.swift +++ b/GRDB/Dump/DatabaseReader+dump.swift @@ -1,4 +1,4 @@ -extension DatabaseReader { +extension DatabaseReaderBase { /// Prints the results of all statements in the provided SQL. /// /// For example: diff --git a/GRDB/Dump/DumpFormat.swift b/GRDB/Dump/DumpFormat.swift index 8157fc0ca..02f32f338 100644 --- a/GRDB/Dump/DumpFormat.swift +++ b/GRDB/Dump/DumpFormat.swift @@ -33,26 +33,28 @@ /// - ``writeRow(_:statement:to:)`` /// - ``finalize(_:statement:to:)`` public protocol DumpFormat { +#warning("TODO: incompatible with GRDB 7") /// Writes a row from the given statement. /// /// - Parameters: /// - db: A connection to the database /// - statement: The iterated statement /// - stream: A stream for text output. - mutating func writeRow( - _ db: Database, - statement: Statement, + mutating func writeRow( + _ db: DatabaseBase, + statement: StatementBase, to stream: inout DumpStream) throws +#warning("TODO: incompatible with GRDB 7") /// All rows from the statement have been printed. /// /// - Parameters: /// - db: A connection to the database /// - statement: The statement that was iterated. /// - stream: A stream for text output. - mutating func finalize( - _ db: Database, - statement: Statement, + mutating func finalize( + _ db: DatabaseBase, + statement: StatementBase, to stream: inout DumpStream) } diff --git a/GRDB/Dump/DumpFormats/DebugDumpFormat.swift b/GRDB/Dump/DumpFormats/DebugDumpFormat.swift index f957b1936..546efb735 100644 --- a/GRDB/Dump/DumpFormats/DebugDumpFormat.swift +++ b/GRDB/Dump/DumpFormats/DebugDumpFormat.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import Foundation @@ -61,9 +61,9 @@ public struct DebugDumpFormat: Sendable { } extension DebugDumpFormat: DumpFormat { - public mutating func writeRow( - _ db: Database, - statement: Statement, + public mutating func writeRow( + _ db: DatabaseBase, + statement: StatementBase, to stream: inout DumpStream) { if firstRow { @@ -91,15 +91,15 @@ extension DebugDumpFormat: DumpFormat { stream.write("\n") } - public mutating func finalize( - _ db: Database, - statement: Statement, + public mutating func finalize( + _ db: DatabaseBase, + statement: StatementBase, to stream: inout DumpStream) { firstRow = true } - private func formattedValue(_ db: Database, in sqliteStatement: SQLiteStatement, at index: CInt) -> String { + private func formattedValue(_ db: DatabaseBase, in sqliteStatement: SQLiteStatement, at index: CInt) -> String { switch sqlite3_column_type(sqliteStatement, index) { case SQLITE_NULL: return nullValue diff --git a/GRDB/Dump/DumpFormats/JSONDumpFormat.swift b/GRDB/Dump/DumpFormats/JSONDumpFormat.swift index 42dd67dba..9531966c8 100644 --- a/GRDB/Dump/DumpFormats/JSONDumpFormat.swift +++ b/GRDB/Dump/DumpFormats/JSONDumpFormat.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import Foundation @@ -80,9 +80,9 @@ public struct JSONDumpFormat: Sendable { } extension JSONDumpFormat: DumpFormat { - public mutating func writeRow( - _ db: Database, - statement: Statement, + public mutating func writeRow( + _ db: DatabaseBase, + statement: StatementBase, to stream: inout DumpStream) throws { if firstRow { @@ -127,9 +127,9 @@ extension JSONDumpFormat: DumpFormat { stream.write("}") } - public mutating func finalize( - _ db: Database, - statement: Statement, + public mutating func finalize( + _ db: DatabaseBase, + statement: StatementBase, to stream: inout DumpStream) { if firstRow { @@ -145,7 +145,7 @@ extension JSONDumpFormat: DumpFormat { firstRow = true } - private func formattedValue(_ db: Database, in sqliteStatement: SQLiteStatement, at index: CInt) throws -> String { + private func formattedValue(_ db: DatabaseBase, in sqliteStatement: SQLiteStatement, at index: CInt) throws -> String { switch sqlite3_column_type(sqliteStatement, index) { case SQLITE_NULL: return "null" diff --git a/GRDB/Dump/DumpFormats/LineDumpFormat.swift b/GRDB/Dump/DumpFormats/LineDumpFormat.swift index 5111090e5..b7cc5d444 100644 --- a/GRDB/Dump/DumpFormats/LineDumpFormat.swift +++ b/GRDB/Dump/DumpFormats/LineDumpFormat.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import Foundation @@ -43,9 +43,9 @@ public struct LineDumpFormat: Sendable { } extension LineDumpFormat: DumpFormat { - public mutating func writeRow( - _ db: Database, - statement: Statement, + public mutating func writeRow( + _ db: DatabaseBase, + statement: StatementBase, to stream: inout DumpStream) { var lines: [(column: String, value: String)] = [] @@ -76,9 +76,9 @@ extension LineDumpFormat: DumpFormat { } } - public mutating func finalize( - _ db: Database, - statement: Statement, + public mutating func finalize( + _ db: DatabaseBase, + statement: StatementBase, to stream: inout DumpStream) { if firstRow == false { @@ -88,7 +88,7 @@ extension LineDumpFormat: DumpFormat { } func formattedValue( - _ db: Database, + _ db: DatabaseBase, in sqliteStatement: SQLiteStatement, at index: CInt) -> String diff --git a/GRDB/Dump/DumpFormats/ListDumpFormat.swift b/GRDB/Dump/DumpFormats/ListDumpFormat.swift index f5536641a..b58bd01d4 100644 --- a/GRDB/Dump/DumpFormats/ListDumpFormat.swift +++ b/GRDB/Dump/DumpFormats/ListDumpFormat.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import Foundation @@ -58,9 +58,9 @@ public struct ListDumpFormat: Sendable { } extension ListDumpFormat: DumpFormat { - public mutating func writeRow( - _ db: Database, - statement: Statement, + public mutating func writeRow( + _ db: DatabaseBase, + statement: StatementBase, to stream: inout DumpStream) { if firstRow { @@ -88,16 +88,16 @@ extension ListDumpFormat: DumpFormat { stream.write("\n") } - public mutating func finalize( - _ db: Database, - statement: Statement, + public mutating func finalize( + _ db: DatabaseBase, + statement: StatementBase, to stream: inout DumpStream) { firstRow = true } func formattedValue( - _ db: Database, + _ db: DatabaseBase, in sqliteStatement: SQLiteStatement, at index: CInt) -> String diff --git a/GRDB/Dump/DumpFormats/QuoteDumpFormat.swift b/GRDB/Dump/DumpFormats/QuoteDumpFormat.swift index c605ae171..ddb4afc2f 100644 --- a/GRDB/Dump/DumpFormats/QuoteDumpFormat.swift +++ b/GRDB/Dump/DumpFormats/QuoteDumpFormat.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif /// A format that prints one line per database row, formatting values /// as SQL literals. @@ -47,9 +47,9 @@ public struct QuoteDumpFormat: Sendable { } extension QuoteDumpFormat: DumpFormat { - public mutating func writeRow( - _ db: Database, - statement: Statement, + public mutating func writeRow( + _ db: DatabaseBase, + statement: StatementBase, to stream: inout DumpStream) { if firstRow { @@ -81,9 +81,9 @@ extension QuoteDumpFormat: DumpFormat { stream.write("\n") } - public mutating func finalize( - _ db: Database, - statement: Statement, + public mutating func finalize( + _ db: DatabaseBase, + statement: StatementBase, to stream: inout DumpStream) { firstRow = true diff --git a/GRDB/FTS/FTS3.swift b/GRDB/FTS/FTS3.swift index 815000551..d26038f41 100644 --- a/GRDB/FTS/FTS3.swift +++ b/GRDB/FTS/FTS3.swift @@ -66,6 +66,7 @@ public struct FTS3 { /// See ``Database/create(virtualTable:options:using:_:)`` public init() { } + #warning("TODO: expose a version with default api") /// Returns an array of tokens found in the string argument. /// /// For example: @@ -94,12 +95,13 @@ public struct FTS3 { /// - /// /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func tokenize( + public static func tokenize( _ string: String, - withTokenizer tokenizer: FTS3TokenizerDescriptor = .simple) + withTokenizer tokenizer: FTS3TokenizerDescriptor = .simple, + api: API.Type) throws -> [String] { - try DatabaseQueue().inDatabase { db in + try DatabaseQueueBase().inDatabase { db in var tokenizerChunks: [String] = [] tokenizerChunks.append(tokenizer.name) for option in tokenizer.arguments { @@ -121,7 +123,7 @@ extension FTS3: VirtualTableModule { FTS3TableDefinition() } - public func moduleArguments(for definition: FTS3TableDefinition, in db: Database) -> [String] { + public func moduleArguments(for definition: FTS3TableDefinition, in db: DatabaseBase) -> [String] { var arguments = definition.columns if let tokenizer = definition.tokenizer { if tokenizer.arguments.isEmpty { @@ -136,7 +138,7 @@ extension FTS3: VirtualTableModule { return arguments } - public func database(_ db: Database, didCreate tableName: String, using definition: FTS3TableDefinition) { } + public func database(_ db: DatabaseBase, didCreate tableName: String, using definition: FTS3TableDefinition) { } } /// A `FTS3TableDefinition` lets you define the components of an FTS3 diff --git a/GRDB/FTS/FTS3Pattern.swift b/GRDB/FTS/FTS3Pattern.swift index af6e82170..d2f24d61a 100644 --- a/GRDB/FTS/FTS3Pattern.swift +++ b/GRDB/FTS/FTS3Pattern.swift @@ -22,6 +22,7 @@ public struct FTS3Pattern: Sendable { /// It is guaranteed to be a valid FTS3/4 pattern. public let rawPattern: String +#warning("TODO: expose a version with default api") /// Creates a pattern from a raw pattern string. /// /// The pattern syntax is documented at @@ -37,14 +38,17 @@ public struct FTS3Pattern: Sendable { /// ``` /// /// - throws: A ``DatabaseError`` if the pattern has an invalid syntax. - public init(rawPattern: String) throws { + public init( + rawPattern: String, + api: API.Type + ) throws { // Correctness above all: use SQLite to validate the pattern. // // Invalid patterns have SQLite return an error on the first // call to sqlite3_step() on a statement that matches against // that pattern. do { - try DatabaseQueue().inDatabase { db in + try DatabaseQueueBase().inDatabase { db in try db.execute(literal: """ CREATE VIRTUAL TABLE documents USING fts3(); SELECT * FROM documents WHERE content MATCH \(rawPattern); @@ -59,6 +63,7 @@ public struct FTS3Pattern: Sendable { self.rawPattern = rawPattern } +#warning("TODO: expose a version with default api") /// Creates a pattern that matches any token found in the input string. /// /// The result is nil if no pattern could be built. @@ -71,13 +76,17 @@ public struct FTS3Pattern: Sendable { /// ``` /// /// - parameter string: The string to turn into an FTS3 pattern. - public init?(matchingAnyTokenIn string: String) { - guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple), + public init?( + matchingAnyTokenIn string: String, + api: API.Type + ) { + guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple, api: api), !tokens.isEmpty else { return nil } - try? self.init(rawPattern: tokens.joined(separator: " OR ")) + try? self.init(rawPattern: tokens.joined(separator: " OR "), api: api) } +#warning("TODO: expose a version with default api") /// Creates a pattern that matches all tokens found in the input string. /// /// The result is nil if no pattern could be built. @@ -90,13 +99,17 @@ public struct FTS3Pattern: Sendable { /// ``` /// /// - parameter string: The string to turn into an FTS3 pattern. - public init?(matchingAllTokensIn string: String) { - guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple), + public init?( + matchingAllTokensIn string: String, + api: API.Type + ) { + guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple, api: api), !tokens.isEmpty else { return nil } - try? self.init(rawPattern: tokens.joined(separator: " ")) + try? self.init(rawPattern: tokens.joined(separator: " "), api: api) } +#warning("TODO: expose a version with default api") /// Creates a pattern that matches all token prefixes found in the input /// string. /// @@ -110,13 +123,17 @@ public struct FTS3Pattern: Sendable { /// ``` /// /// - parameter string: The string to turn into an FTS3 pattern. - public init?(matchingAllPrefixesIn string: String) { - guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple), + public init?( + matchingAllPrefixesIn string: String, + api: API.Type + ) { + guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple, api: api), !tokens.isEmpty else { return nil } - try? self.init(rawPattern: tokens.map { "\($0)*" }.joined(separator: " ")) + try? self.init(rawPattern: tokens.map { "\($0)*" }.joined(separator: " "), api: api) } +#warning("TODO: expose a version with default api") /// Creates a pattern that matches a contiguous string. /// /// The result is nil if no pattern could be built. @@ -129,11 +146,14 @@ public struct FTS3Pattern: Sendable { /// ``` /// /// - parameter string: The string to turn into an FTS3 pattern. - public init?(matchingPhrase string: String) { - guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple), + public init?( + matchingPhrase string: String, + api: API.Type + ) { + guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple, api: api), !tokens.isEmpty else { return nil } - try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"") + try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"", api: api) } } diff --git a/GRDB/FTS/FTS4.swift b/GRDB/FTS/FTS4.swift index 2848cb8f2..01d0d08cc 100644 --- a/GRDB/FTS/FTS4.swift +++ b/GRDB/FTS/FTS4.swift @@ -42,7 +42,10 @@ extension FTS4: VirtualTableModule { FTS4TableDefinition(configuration: configuration) } - public func moduleArguments(for definition: FTS4TableDefinition, in db: Database) -> [String] { + public func moduleArguments( + for definition: FTS4TableDefinition, + in db: DatabaseBase + ) -> [String] { var arguments: [String] = [] for column in definition.columns { @@ -95,7 +98,7 @@ extension FTS4: VirtualTableModule { return arguments } - public func database(_ db: Database, didCreate tableName: String, using definition: FTS4TableDefinition) throws { + public func database(_ db: DatabaseBase, didCreate tableName: String, using definition: FTS4TableDefinition) throws { switch definition.contentMode { case .raw: break @@ -397,7 +400,7 @@ public final class FTS4ColumnDefinition { @available(*, unavailable) extension FTS4ColumnDefinition: Sendable { } -extension Database { +extension DatabaseBase { /// Deletes the synchronization triggers for a synchronized FTS4 table. /// /// See ``FTS4TableDefinition/synchronize(withTable:)``. diff --git a/GRDB/FTS/FTS5.swift b/GRDB/FTS/FTS5.swift index 127a43fef..972c9c24e 100644 --- a/GRDB/FTS/FTS5.swift +++ b/GRDB/FTS/FTS5.swift @@ -1,15 +1,15 @@ #if SQLITE_ENABLE_FTS5 -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import Foundation @@ -119,7 +119,7 @@ public struct FTS5 { /// Returns a pointer to the `fts5_api` structure. /// /// Related SQLite documentation: - public static func api(_ db: Database) -> UnsafePointer { + public static func api(_ db: DatabaseBase) -> UnsafePointer { var statement: SQLiteStatement? var api: UnsafePointer? let type: StaticString = "fts5_api_ptr" @@ -152,7 +152,10 @@ extension FTS5: VirtualTableModule { } /// Don't use this method. - public func moduleArguments(for definition: FTS5TableDefinition, in db: Database) throws -> [String] { + public func moduleArguments( + for definition: FTS5TableDefinition, + in db: DatabaseBase + ) throws -> [String] { var arguments: [String] = [] if definition.columns.isEmpty { @@ -223,7 +226,7 @@ extension FTS5: VirtualTableModule { /// Reserved; part of the VirtualTableModule protocol. /// /// See Database.create(virtualTable:options:using:_:) - public func database(_ db: Database, didCreate tableName: String, using definition: FTS5TableDefinition) throws { + public func database(_ db: DatabaseBase, didCreate tableName: String, using definition: FTS5TableDefinition) throws { switch definition.contentMode { case .raw: break @@ -531,7 +534,7 @@ extension Column { public static let rank = Column("rank") } -extension Database { +extension DatabaseBase { /// Deletes the synchronization triggers for a synchronized FTS5 table. public func dropFTS5SynchronizationTriggers(forTable tableName: String) throws { try execute(sql: """ diff --git a/GRDB/FTS/FTS5CustomTokenizer.swift b/GRDB/FTS/FTS5CustomTokenizer.swift index a209337a6..720505e35 100644 --- a/GRDB/FTS/FTS5CustomTokenizer.swift +++ b/GRDB/FTS/FTS5CustomTokenizer.swift @@ -1,15 +1,15 @@ #if SQLITE_ENABLE_FTS5 -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif /// A type that implements a custom tokenizer for the ``FTS5`` full-text engine. /// @@ -34,7 +34,7 @@ public protocol FTS5CustomTokenizer: FTS5Tokenizer { /// /// - parameter db: A Database connection /// - parameter arguments: An array of string arguments - init(db: Database, arguments: [String]) throws + init(db: DatabaseBase, arguments: [String]) throws } extension FTS5CustomTokenizer { @@ -52,12 +52,12 @@ extension FTS5CustomTokenizer { } } -extension Database { +extension DatabaseBase { // MARK: - FTS5 private class FTS5TokenizerConstructor { - let db: Database + let db: DatabaseBase let constructor: (Database, [String], UnsafeMutablePointer?) -> CInt init( diff --git a/GRDB/FTS/FTS5Pattern.swift b/GRDB/FTS/FTS5Pattern.swift index 79c91c322..a9547c457 100644 --- a/GRDB/FTS/FTS5Pattern.swift +++ b/GRDB/FTS/FTS5Pattern.swift @@ -173,7 +173,7 @@ public struct FTS5Pattern: Sendable { } } -extension Database { +extension DatabaseBase { // MARK: - FTS5 diff --git a/GRDB/FTS/FTS5Tokenizer.swift b/GRDB/FTS/FTS5Tokenizer.swift index 35f3ae267..7ae283953 100644 --- a/GRDB/FTS/FTS5Tokenizer.swift +++ b/GRDB/FTS/FTS5Tokenizer.swift @@ -1,15 +1,15 @@ #if SQLITE_ENABLE_FTS5 -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import Foundation @@ -194,7 +194,7 @@ extension FTS5Tokenizer { } } -extension Database { +extension DatabaseBase { // MARK: - FTS5 diff --git a/GRDB/FTS/FTS5WrapperTokenizer.swift b/GRDB/FTS/FTS5WrapperTokenizer.swift index bda4ed181..668b6a66c 100644 --- a/GRDB/FTS/FTS5WrapperTokenizer.swift +++ b/GRDB/FTS/FTS5WrapperTokenizer.swift @@ -1,15 +1,15 @@ #if SQLITE_ENABLE_FTS5 -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import Foundation diff --git a/GRDB/Fixits.swift b/GRDB/Fixits.swift index 174a5ce7e..41d6b943e 100644 --- a/GRDB/Fixits.swift +++ b/GRDB/Fixits.swift @@ -14,7 +14,7 @@ public class DatabaseFuture { } extension DatabasePool { @available(*, unavailable, message: "concurrentRead has been removed. Use `asyncConcurrentRead` instead.") - public func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture { preconditionFailure() } + public func concurrentRead(_ value: @escaping (DatabaseBase) throws -> T) -> DatabaseFuture { preconditionFailure() } } // swiftlint:enable all diff --git a/GRDB/JSON/SQLJSONFunctions.swift b/GRDB/JSON/SQLJSONFunctions.swift index e82f930ce..a6545c6f4 100644 --- a/GRDB/JSON/SQLJSONFunctions.swift +++ b/GRDB/JSON/SQLJSONFunctions.swift @@ -1,7 +1,7 @@ #if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC // MARK: - JSON -extension Database { +extension DatabaseBase { /// Validates and minifies a JSON string, with the `JSON` SQL function. /// /// For example: @@ -453,7 +453,7 @@ extension Database { // MARK: - JSONB -extension Database { +extension DatabaseBase { public struct JSONValidationOptions: OptionSet, Sendable { public let rawValue: Int @@ -791,7 +791,7 @@ extension Database { #else // MARK: - JSON -extension Database { +extension DatabaseBase { /// Validates and minifies a JSON string, with the `JSON` SQL function. /// /// For example: diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index f90ebb902..cb6387532 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -213,7 +213,7 @@ public struct DatabaseMigrator: Sendable { public mutating func registerMigration( _ identifier: String, foreignKeyChecks: ForeignKeyChecks = .deferred, - migrate: @escaping @Sendable (Database) throws -> Void) + migrate: @escaping @Sendable (DatabaseBase) throws -> Void) { registerMigration(identifier, foreignKeyChecks: foreignKeyChecks, merging: []) { db, ids in precondition(ids.isEmpty) @@ -314,7 +314,7 @@ public struct DatabaseMigrator: Sendable { _ identifier: String, foreignKeyChecks: ForeignKeyChecks = .deferred, merging mergedIdentifiers: Set = [], - migrate: @escaping @Sendable (_ db: Database, _ appliedIdentifiers: Set) throws -> Void) + migrate: @escaping @Sendable (_ db: DatabaseBase, _ appliedIdentifiers: Set) throws -> Void) { let migrationChecks: Migration.ForeignKeyChecks switch foreignKeyChecks { @@ -382,7 +382,7 @@ public struct DatabaseMigrator: Sendable { /// from succeeding. public func asyncMigrate( _ writer: any DatabaseWriter, - completion: @escaping @Sendable (Result) -> Void) + completion: @escaping @Sendable (Result, Error>) -> Void) { writer.asyncBarrierWriteWithoutTransaction { dbResult in do { @@ -424,7 +424,7 @@ public struct DatabaseMigrator: Sendable { /// try migrator.migrate(dbQueue) /// ``` /// - public func hasSchemaChanges(_ db: Database) throws -> Bool { + public func hasSchemaChanges(_ db: DatabaseBase) throws -> Bool { let appliedIdentifiers = try appliedIdentifiers(db) let knownIdentifiers = Set(_migrations.map { $0.identifier }) if !appliedIdentifiers.isSubset(of: knownIdentifiers) { @@ -500,7 +500,7 @@ public struct DatabaseMigrator: Sendable { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func appliedMigrations(_ db: Database) throws -> [String] { + public func appliedMigrations(_ db: DatabaseBase) throws -> [String] { let appliedIdentifiers = try self.appliedIdentifiers(db) return _migrations.map { $0.identifier }.filter { appliedIdentifiers.contains($0) } } @@ -509,7 +509,7 @@ public struct DatabaseMigrator: Sendable { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func appliedIdentifiers(_ db: Database) throws -> Set { + public func appliedIdentifiers(_ db: DatabaseBase) throws -> Set { do { return try String.fetchSet(db, sql: "SELECT identifier FROM grdb_migrations") } catch { @@ -529,7 +529,7 @@ public struct DatabaseMigrator: Sendable { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func completedMigrations(_ db: Database) throws -> [String] { + public func completedMigrations(_ db: DatabaseBase) throws -> [String] { let appliedIdentifiers = try appliedMigrations(db) let knownIdentifiers = _migrations.map(\.identifier) return zip(appliedIdentifiers, knownIdentifiers) @@ -542,7 +542,7 @@ public struct DatabaseMigrator: Sendable { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func hasCompletedMigrations(_ db: Database) throws -> Bool { + public func hasCompletedMigrations(_ db: DatabaseBase) throws -> Bool { try completedMigrations(db).last == _migrations.last?.identifier } @@ -554,7 +554,7 @@ public struct DatabaseMigrator: Sendable { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func hasBeenSuperseded(_ db: Database) throws -> Bool { + public func hasBeenSuperseded(_ db: DatabaseBase) throws -> Bool { let appliedIdentifiers = try self.appliedIdentifiers(db) let knownIdentifiers = _migrations.map(\.identifier) return appliedIdentifiers.contains { !knownIdentifiers.contains($0) } @@ -611,7 +611,7 @@ public struct DatabaseMigrator: Sendable { } } - private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws { + private func runMigrations(_ db: DatabaseBase, upTo targetIdentifier: String) throws { try db.execute(sql: "CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)") // Subsequent migration must not be applied @@ -643,7 +643,7 @@ public struct DatabaseMigrator: Sendable { } } - private func migrate(_ db: Database, upTo targetIdentifier: String) throws { + private func migrate(_ db: DatabaseBase, upTo targetIdentifier: String) throws { if eraseDatabaseOnSchemaChange { var needsErase = false try db.inTransaction(.deferred) { diff --git a/GRDB/Migration/Migration.swift b/GRDB/Migration/Migration.swift index accc18ba8..e1d3e6d6b 100644 --- a/GRDB/Migration/Migration.swift +++ b/GRDB/Migration/Migration.swift @@ -6,7 +6,7 @@ struct Migration: Sendable { case disabled } - typealias Migrate = @Sendable (_ db: Database, _ mergedIdentifiers: Set) throws -> Void + typealias Migrate = @Sendable (_ db: DatabaseBase, _ mergedIdentifiers: Set) throws -> Void let identifier: String let mergedIdentifiers: Set @@ -26,7 +26,7 @@ struct Migration: Sendable { self.migrate = migrate } - func run(_ db: Database, mergedIdentifiers: Set) throws { + func run(_ db: DatabaseBase, mergedIdentifiers: Set) throws { // Migrations access the raw SQLite schema, without alteration due // to the schemaSource. The goal is to ensure that migrations are // immutable, immune from spooky actions at a distance. @@ -47,13 +47,13 @@ struct Migration: Sendable { } - func deleteMergedIdentifiers(_ db: Database) throws { + func deleteMergedIdentifiers(_ db: DatabaseBase) throws { if mergedIdentifiers.isEmpty == false { try db.execute(literal: "DELETE FROM grdb_migrations WHERE identifier IN \(mergedIdentifiers)") } } - private func runWithImmediateForeignKeysChecks(_ db: Database, mergedIdentifiers: Set) throws { + private func runWithImmediateForeignKeysChecks(_ db: DatabaseBase, mergedIdentifiers: Set) throws { try db.inTransaction(.immediate) { try migrate(db, mergedIdentifiers) try updateAppliedIdentifier(db) @@ -61,7 +61,7 @@ struct Migration: Sendable { } } - private func runWithDisabledForeignKeysChecks(_ db: Database, mergedIdentifiers: Set) throws { + private func runWithDisabledForeignKeysChecks(_ db: DatabaseBase, mergedIdentifiers: Set) throws { try db.execute(sql: "PRAGMA foreign_keys = OFF") try throwingFirstError( execute: { @@ -76,7 +76,7 @@ struct Migration: Sendable { }) } - private func runWithDeferredForeignKeysChecks(_ db: Database, mergedIdentifiers: Set) throws { + private func runWithDeferredForeignKeysChecks(_ db: DatabaseBase, mergedIdentifiers: Set) throws { // Support for database alterations described at // https://www.sqlite.org/lang_altertable.html#otheralter // @@ -108,7 +108,7 @@ struct Migration: Sendable { }) } - private func updateAppliedIdentifier(_ db: Database) throws { + private func updateAppliedIdentifier(_ db: DatabaseBase) throws { try deleteMergedIdentifiers(db) try db.execute(literal: "INSERT INTO grdb_migrations (identifier) VALUES (\(identifier))") } diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index 86a234c8d..0f73165ff 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -173,8 +173,10 @@ extension Association { // SelectionRequest conformance extension Association { - public func selectWhenConnected( - _ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable] +#warning("TODO: expose a version with default api") + public func selectWhenConnected( + api: API.Type, + _ selection: @escaping @Sendable (DatabaseBase) throws -> [any SQLSelectable] ) -> Self { withDestinationRelation { relation in relation = relation.selectWhenConnected { db in @@ -183,8 +185,10 @@ extension Association { } } - public func annotatedWhenConnected( - with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable] +#warning("TODO: expose a version with default api") + public func annotatedWhenConnected( + api: API.Type, + with selection: @escaping @Sendable (DatabaseBase) throws -> [any SQLSelectable] ) -> Self { withDestinationRelation { relation in relation = relation.annotatedWhenConnected { db in @@ -196,8 +200,10 @@ extension Association { // FilteredRequest conformance extension Association { - public func filterWhenConnected( - _ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible +#warning("TODO: expose a version with default api") + public func filterWhenConnected( + api: API.Type, + _ predicate: @escaping @Sendable (DatabaseBase) throws -> any SQLExpressible ) -> Self { withDestinationRelation { relation in relation = relation.filterWhenConnected { db in @@ -209,8 +215,10 @@ extension Association { // OrderedRequest conformance extension Association { - public func orderWhenConnected( - _ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm] +#warning("TODO: expose a version with default api") + public func orderWhenConnected( + api: API.Type, + _ orderings: @escaping @Sendable (DatabaseBase) throws -> [any SQLOrderingTerm] ) -> Self { withDestinationRelation { relation in relation = relation.orderWhenConnected { db in @@ -247,8 +255,10 @@ extension Association { // AggregatingRequest conformance extension Association { - public func groupWhenConnected( - _ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible] +#warning("TODO: expose a version with default api") + public func groupWhenConnected( + api: API.Type, + _ expressions: @escaping @Sendable (DatabaseBase) throws -> [any SQLExpressible] ) -> Self { withDestinationRelation { relation in relation = relation.groupWhenConnected { db in @@ -257,8 +267,10 @@ extension Association { } } - public func havingWhenConnected( - _ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible +#warning("TODO: expose a version with default api") + public func havingWhenConnected( + api: API.Type, + _ predicate: @escaping @Sendable (DatabaseBase) throws -> any SQLExpressible ) -> Self { withDestinationRelation { relation in relation = relation.havingWhenConnected { db in diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index b39439671..4ab3a46ba 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -1131,7 +1131,7 @@ public func abs(_ aggregate: AssociationAggregate) /// Related SQLite documentation: public func cast( _ aggregate: AssociationAggregate, - as storageClass: Database.StorageClass) + as storageClass: DatabaseStorageClass) -> AssociationAggregate { aggregate diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index ceef01931..72b6a1229 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -333,7 +333,7 @@ struct SQLCTE { var isRecursive: Bool /// The number of columns in the common table expression. - func columnCount(_ db: Database) throws -> Int { + func columnCount(_ db: DatabaseBase) throws -> Int { if let columns { // No need to hit the database return columns.count diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 2f3dda460..b028badb9 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -106,14 +106,14 @@ extension QueryInterfaceRequest: FetchRequest { .relation(relation) } - public func fetchCount(_ db: Database) throws -> Int { + public func fetchCount(_ db: DatabaseBase) throws -> Int { try relation.fetchCount(db) } - public func makePreparedRequest( - _ db: Database, + public func makePreparedRequest( + _ db: DatabaseBase, forSingleResult singleResult: Bool = false) - throws -> PreparedRequest + throws -> PreparedRequestBase { let generator = SQLQueryGenerator(relation: relation, forSingleResult: singleResult) var preparedRequest = try generator.makePreparedRequest(db) @@ -136,8 +136,10 @@ extension QueryInterfaceRequest: FetchRequest { // MARK: - Request Derivation extension QueryInterfaceRequest: SelectionRequest { - public func selectWhenConnected( - _ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]) +#warning("TODO: expose a version with default api") + public func selectWhenConnected( + api: API.Type, + _ selection: @escaping @Sendable (DatabaseBase) throws -> [any SQLSelectable]) -> Self { with { @@ -373,8 +375,10 @@ extension QueryInterfaceRequest: SelectionRequest { }.asRequest(of: RowDecoder.ID.self) } - public func annotatedWhenConnected( - with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]) +#warning("TODO: expose a version with default api") + public func annotatedWhenConnected( + api: API.Type, + with selection: @escaping @Sendable (DatabaseBase) throws -> [any SQLSelectable]) -> Self { with { @@ -386,8 +390,10 @@ extension QueryInterfaceRequest: SelectionRequest { } extension QueryInterfaceRequest: FilteredRequest { - public func filterWhenConnected( - _ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible) +#warning("TODO: expose a version with default api") + public func filterWhenConnected( + api: API.Type, + _ predicate: @escaping @Sendable (DatabaseBase) throws -> any SQLExpressible) -> Self { with { @@ -399,8 +405,10 @@ extension QueryInterfaceRequest: FilteredRequest { } extension QueryInterfaceRequest: OrderedRequest { - public func orderWhenConnected( - _ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm]) +#warning("TODO: expose a version with default api") + public func orderWhenConnected( + api: API.Type, + _ orderings: @escaping @Sendable (DatabaseBase) throws -> [any SQLOrderingTerm]) -> Self { with { @@ -467,8 +475,10 @@ extension QueryInterfaceRequest: OrderedRequest { } extension QueryInterfaceRequest: AggregatingRequest { - public func groupWhenConnected( - _ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible]) +#warning("TODO: expose a version with default api") + public func groupWhenConnected( + api: API.Type, + _ expressions: @escaping @Sendable (DatabaseBase) throws -> [any SQLExpressible]) -> Self { with { @@ -478,8 +488,10 @@ extension QueryInterfaceRequest: AggregatingRequest { } } - public func havingWhenConnected( - _ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible) +#warning("TODO: expose a version with default api") + public func havingWhenConnected( + api: API.Type, + _ predicate: @escaping @Sendable (DatabaseBase) throws -> any SQLExpressible) -> Self { with { @@ -619,7 +631,7 @@ extension QueryInterfaceRequest { /// ``` /// /// - parameter db: A database connection. - public func isEmpty(_ db: Database) throws -> Bool { + public func isEmpty(_ db: DatabaseBase) throws -> Bool { try !SQLRequest("SELECT \(exists())").fetchOne(db)! } } @@ -633,7 +645,7 @@ extension QueryInterfaceRequest { /// - returns: The number of deleted rows /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult - public func deleteAll(_ db: Database) throws -> Int { + public func deleteAll(_ db: DatabaseBase) throws -> Int { let statement = try SQLQueryGenerator(relation: relation).makeDeleteStatement(db) var changesCount = 0 try db.countChanges(&changesCount, forTable: relation.source.tableName) { @@ -668,11 +680,10 @@ extension QueryInterfaceRequest { /// - returns: A prepared statement. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: `selection` is not empty. - public func deleteAndFetchStatement( - _ db: Database, - selection: [any SQLSelectable]) - throws -> Statement - { + public func deleteAndFetchStatement( + _ db: DatabaseBase, + selection: [any SQLSelectable] + ) throws -> StatementBase { GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection) } @@ -706,7 +717,7 @@ extension QueryInterfaceRequest { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: The result of `select` is not empty. public func deleteAndFetchStatement( - _ db: Database, + _ db: DatabaseBase, select: (DatabaseComponents) throws -> [any SQLSelectable] ) throws -> Statement where RowDecoder: TableRecord @@ -736,7 +747,7 @@ extension QueryInterfaceRequest { /// - parameter db: A database connection. /// - returns: A ``RecordCursor`` over the deleted records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func deleteAndFetchCursor(_ db: Database) + public func deleteAndFetchCursor(_ db: DatabaseBase) throws -> RecordCursor where RowDecoder: FetchableRecord & TableRecord { @@ -763,7 +774,7 @@ extension QueryInterfaceRequest { /// - parameter db: A database connection. /// - returns: An array of deleted records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func deleteAndFetchAll(_ db: Database) + public func deleteAndFetchAll(_ db: DatabaseBase) throws -> [RowDecoder] where RowDecoder: FetchableRecord & TableRecord { @@ -789,7 +800,7 @@ extension QueryInterfaceRequest { /// - parameter db: A database connection. /// - returns: A set of deleted records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func deleteAndFetchSet(_ db: Database) + public func deleteAndFetchSet(_ db: DatabaseBase) throws -> Set where RowDecoder: FetchableRecord & TableRecord & Hashable { @@ -815,7 +826,7 @@ extension QueryInterfaceRequest { /// - parameter db: A database connection. /// - returns: A set of deleted ids. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func deleteAndFetchIds(_ db: Database) + public func deleteAndFetchIds(_ db: DatabaseBase) throws -> Set where RowDecoder: TableRecord & Identifiable, RowDecoder.ID: Hashable & DatabaseValueConvertible & StatementColumnConvertible @@ -852,11 +863,10 @@ extension QueryInterfaceRequest { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: `selection` is not empty. @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ - public func deleteAndFetchStatement( - _ db: Database, - selection: [any SQLSelectable]) - throws -> Statement - { + public func deleteAndFetchStatement( + _ db: DatabaseBase, + selection: [any SQLSelectable] + ) throws -> StatementBase { GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection) } @@ -891,7 +901,7 @@ extension QueryInterfaceRequest { /// - precondition: The result of `select` is not empty. @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func deleteAndFetchStatement( - _ db: Database, + _ db: DatabaseBase, select: (DatabaseComponents) throws -> [any SQLSelectable] ) throws -> Statement where RowDecoder: TableRecord @@ -922,7 +932,7 @@ extension QueryInterfaceRequest { /// - returns: A ``RecordCursor`` over the deleted records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ - public func deleteAndFetchCursor(_ db: Database) + public func deleteAndFetchCursor(_ db: DatabaseBase) throws -> RecordCursor where RowDecoder: FetchableRecord & TableRecord { @@ -950,7 +960,7 @@ extension QueryInterfaceRequest { /// - returns: An array of deleted records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ - public func deleteAndFetchAll(_ db: Database) + public func deleteAndFetchAll(_ db: DatabaseBase) throws -> [RowDecoder] where RowDecoder: FetchableRecord & TableRecord { @@ -977,7 +987,7 @@ extension QueryInterfaceRequest { /// - returns: A set of deleted records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ - public func deleteAndFetchSet(_ db: Database) + public func deleteAndFetchSet(_ db: DatabaseBase) throws -> Set where RowDecoder: FetchableRecord & TableRecord & Hashable { @@ -1004,7 +1014,7 @@ extension QueryInterfaceRequest { /// - returns: A set of deleted ids. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ - public func deleteAndFetchIds(_ db: Database) + public func deleteAndFetchIds(_ db: DatabaseBase) throws -> Set where RowDecoder: TableRecord & Identifiable, RowDecoder.ID: Hashable & DatabaseValueConvertible & StatementColumnConvertible @@ -1025,7 +1035,7 @@ extension QueryInterfaceRequest { extension QueryInterfaceRequest { /// The conflict resolution to use for batch updates - private var defaultConflictResolutionForUpdate: Database.ConflictResolution { + private var defaultConflictResolutionForUpdate: DatabaseConflictResolution { // In order to look for the default conflict resolution, we perform a // runtime check for MutablePersistableRecord, and look for a // user-defined default. Such dynamic dispatch is unusual in GRDB, but @@ -1062,8 +1072,8 @@ extension QueryInterfaceRequest { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public func updateAll( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, assignment: (DatabaseComponents) throws -> ColumnAssignment ) throws -> Int where RowDecoder: TableRecord @@ -1097,8 +1107,8 @@ extension QueryInterfaceRequest { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public func updateAll( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, assignments: (DatabaseComponents) throws -> [ColumnAssignment] ) throws -> Int where RowDecoder: TableRecord @@ -1125,8 +1135,8 @@ extension QueryInterfaceRequest { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public func updateAll( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, _ assignments: [ColumnAssignment]) throws -> Int { let conflictResolution = conflictResolution ?? defaultConflictResolutionForUpdate @@ -1164,8 +1174,8 @@ extension QueryInterfaceRequest { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public func updateAll( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, _ assignments: ColumnAssignment...) throws -> Int { @@ -1214,8 +1224,8 @@ extension QueryInterfaceRequest { /// - precondition: The results of `select` and `assignments` results /// are not empty. public func updateAndFetchStatement( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, assignments: (DatabaseComponents) throws -> [ColumnAssignment], select: (DatabaseComponents) -> [any SQLSelectable] ) throws -> Statement @@ -1255,8 +1265,8 @@ extension QueryInterfaceRequest { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: `selection` and `assignments` are not empty. public func updateAndFetchStatement( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, _ assignments: [ColumnAssignment], selection: [any SQLSelectable]) throws -> Statement @@ -1309,8 +1319,8 @@ extension QueryInterfaceRequest { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: The result of `assignments` is not empty. public func updateAndFetchCursor( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, assignments: (DatabaseComponents) throws -> [ColumnAssignment] ) throws -> RecordCursor where RowDecoder: FetchableRecord & TableRecord @@ -1344,8 +1354,8 @@ extension QueryInterfaceRequest { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: `assignments` is not empty. public func updateAndFetchCursor( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, _ assignments: [ColumnAssignment]) throws -> RecordCursor where RowDecoder: FetchableRecord & TableRecord @@ -1388,8 +1398,8 @@ extension QueryInterfaceRequest { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: The result of `assignments` is not empty. public func updateAndFetchAll( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, assignments: (DatabaseComponents) throws -> [ColumnAssignment] ) throws -> [RowDecoder] where RowDecoder: FetchableRecord & TableRecord @@ -1420,8 +1430,8 @@ extension QueryInterfaceRequest { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: `assignments` is not empty. public func updateAndFetchAll( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, _ assignments: [ColumnAssignment]) throws -> [RowDecoder] where RowDecoder: FetchableRecord & TableRecord @@ -1459,8 +1469,8 @@ extension QueryInterfaceRequest { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: The result of `assignments` is not empty. public func updateAndFetchSet( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, assignments: (DatabaseComponents) throws -> [ColumnAssignment] ) throws -> Set where RowDecoder: FetchableRecord & TableRecord & Hashable @@ -1491,8 +1501,8 @@ extension QueryInterfaceRequest { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. /// - precondition: `assignments` is not empty. public func updateAndFetchSet( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, _ assignments: [ColumnAssignment]) throws -> Set where RowDecoder: FetchableRecord & TableRecord & Hashable @@ -1538,8 +1548,8 @@ extension QueryInterfaceRequest { /// are not empty. @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func updateAndFetchStatement( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, assignments: (DatabaseComponents) throws -> [ColumnAssignment], select: (DatabaseComponents) throws -> [any SQLSelectable] ) throws -> Statement @@ -1580,8 +1590,8 @@ extension QueryInterfaceRequest { /// - precondition: `selection` and `assignments` are not empty. @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func updateAndFetchStatement( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, _ assignments: [ColumnAssignment], selection: [any SQLSelectable]) throws -> Statement @@ -1635,8 +1645,8 @@ extension QueryInterfaceRequest { /// - precondition: The result of `assignments` is not empty. @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func updateAndFetchCursor( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, assignments: (DatabaseComponents) throws -> [ColumnAssignment] ) throws -> RecordCursor where RowDecoder: FetchableRecord & TableRecord @@ -1671,8 +1681,8 @@ extension QueryInterfaceRequest { /// - precondition: `assignments` is not empty. @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func updateAndFetchCursor( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, _ assignments: [ColumnAssignment]) throws -> RecordCursor where RowDecoder: FetchableRecord & TableRecord @@ -1716,8 +1726,8 @@ extension QueryInterfaceRequest { /// - precondition: The result of `assignments` is not empty. @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func updateAndFetchAll( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, assignments: (DatabaseComponents) throws -> [ColumnAssignment] ) throws -> [RowDecoder] where RowDecoder: FetchableRecord & TableRecord @@ -1749,8 +1759,8 @@ extension QueryInterfaceRequest { /// - precondition: `assignments` is not empty. @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func updateAndFetchAll( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, _ assignments: [ColumnAssignment]) throws -> [RowDecoder] where RowDecoder: FetchableRecord & TableRecord @@ -1789,8 +1799,8 @@ extension QueryInterfaceRequest { /// - precondition: The result of `assignments` is not empty. @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func updateAndFetchSet( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, assignments: (DatabaseComponents) throws -> [ColumnAssignment] ) throws -> Set where RowDecoder: FetchableRecord & TableRecord & Hashable @@ -1822,8 +1832,8 @@ extension QueryInterfaceRequest { /// - precondition: `assignments` is not empty. @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func updateAndFetchSet( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, _ assignments: [ColumnAssignment]) throws -> Set where RowDecoder: FetchableRecord & TableRecord & Hashable @@ -2144,7 +2154,7 @@ extension ColumnExpression { /// - parameter willExecuteSupplementaryRequest: A closure executed before a /// supplementary fetch is performed. private func prefetch( - _ db: Database, + _ db: DatabaseBase, associations: [_SQLAssociation], from originRelation: SQLRelation, into originRows: [Row], @@ -2311,7 +2321,7 @@ func makePrefetchRequest( // CAUTION: Keep this code in sync with prefetch(_:associations:in:) /// Returns the region of prefetched associations func prefetchedRegion( - _ db: Database, + _ db: DatabaseBase, associations: [_SQLAssociation], from originTable: String) throws -> DatabaseRegion @@ -2333,7 +2343,7 @@ throws -> DatabaseRegion // CAUTION: Keep this code in sync with prefetch(_:associations:in:) func prefetchedRegion( - _ db: Database, + _ db: DatabaseBase, association: _SQLAssociation, pivotMapping: JoinMapping) throws -> DatabaseRegion diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index e2b366d57..05cad0a86 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -40,6 +40,7 @@ public protocol TypedRequest { /// - ``select(_:)-30yzl`` /// - ``select(_:)-7e2y5`` public protocol SelectionRequest { +#warning("TODO: expose a version with default api") /// Defines the result columns. /// /// The `selection` parameter is a closure that accepts a database @@ -67,10 +68,12 @@ public protocol SelectionRequest { /// /// - parameter selection: A closure that accepts a database connection and /// returns an array of result columns. - func selectWhenConnected( - _ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable] + func selectWhenConnected( + api: API.Type, + _ selection: @escaping @Sendable (DatabaseBase) throws -> [any SQLSelectable] ) -> Self +#warning("TODO: expose a version with default api") /// Appends result columns to the selected columns. /// /// The `selection` parameter is a closure that accepts a database @@ -89,8 +92,9 @@ public protocol SelectionRequest { /// /// - parameter selection: A closure that accepts a database connection and /// returns an array of result columns. - func annotatedWhenConnected( - with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable] + func annotatedWhenConnected( + api: API.Type, + with selection: @escaping @Sendable (DatabaseBase) throws -> [any SQLSelectable] ) -> Self } @@ -358,6 +362,7 @@ extension SelectionRequest where Self: TypedRequest, Self.RowDecoder: TableRecor /// /// - ``filter(_:)-48a4t`` public protocol FilteredRequest { +#warning("TODO: expose a version with default api") /// Filters the fetched rows with a boolean SQL expression. /// /// The `predicate` parameter is a closure that accepts a database @@ -377,8 +382,9 @@ public protocol FilteredRequest { /// /// - parameter predicate: A closure that accepts a database connection and /// returns a boolean SQL expression. - func filterWhenConnected( - _ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible + func filterWhenConnected( + api: API.Type, + _ predicate: @escaping @Sendable (DatabaseBase<$API>) throws -> any SQLExpressible ) -> Self } @@ -747,7 +753,10 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { /// let request = try Player...filterWhenConnected(keys: { db in [1, 2, 3] }) /// /// - parameter keys: A collection of primary keys - fileprivate func filterWhenConnected(keys: @escaping @Sendable (Database) throws -> [SQLExpression]) -> Self { + fileprivate func filterWhenConnected( + api: API.Type, + keys: @escaping @Sendable (DatabaseBase) throws -> [SQLExpression] + ) -> Self { let databaseTableName = self.databaseTableName return filterWhenConnected { db in // Don't bother removing NULLs. We'd lose CPU cycles, and this does not @@ -992,6 +1001,7 @@ extension TableRequest where Self: AggregatingRequest { /// - ``group(_:)-4216o`` /// - ``having(_:)-2ssg9`` public protocol AggregatingRequest { +#warning("TODO: expose a version with default api") /// Returns an aggregate request grouped on the given SQL expressions. /// /// The `expressions` parameter is a closure that accepts a database @@ -1014,10 +1024,12 @@ public protocol AggregatingRequest { /// /// - parameter expressions: A closure that accepts a database connection /// and returns an array of SQL expressions. - func groupWhenConnected( - _ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible] + func groupWhenConnected( + api: API.Type, + _ expressions: @escaping @Sendable (DatabaseBase) throws -> [any SQLExpressible] ) -> Self +#warning("TODO: expose a version with default api") /// Filters the aggregated groups with a boolean SQL expression. /// /// The `predicate` parameter is a closure that accepts a database @@ -1040,8 +1052,9 @@ public protocol AggregatingRequest { /// /// - parameter predicate: A closure that accepts a database connection and /// returns a boolean SQL expression. - func havingWhenConnected( - _ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible + func havingWhenConnected( + api: API.Type, + _ predicate: @escaping @Sendable (DatabaseBase) throws -> any SQLExpressible ) -> Self } @@ -1270,6 +1283,7 @@ extension AggregatingRequest where Self: TypedRequest, Self.RowDecoder: TableRec /// - ``order(_:)-63rzl`` /// - ``order(_:)-6co0m`` public protocol OrderedRequest { +#warning("TODO: expose a version with default api") /// Sorts the fetched rows according to the given SQL ordering terms. /// /// The `orderings` parameter is a closure that accepts a database @@ -1297,8 +1311,9 @@ public protocol OrderedRequest { /// /// - parameter orderings: A closure that accepts a database connection and /// returns an array of SQL ordering terms. - func orderWhenConnected( - _ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm] + func orderWhenConnected( + api: API.Type, + _ orderings: @escaping @Sendable (DatabaseBase) throws -> [any SQLOrderingTerm] ) -> Self /// Returns a request with reversed ordering. diff --git a/GRDB/QueryInterface/SQL/DatabasePromise.swift b/GRDB/QueryInterface/SQL/DatabasePromise.swift index 7fb7c3ede..9c0d2f1de 100644 --- a/GRDB/QueryInterface/SQL/DatabasePromise.swift +++ b/GRDB/QueryInterface/SQL/DatabasePromise.swift @@ -23,7 +23,7 @@ /// see SQLRelation.filterPromise. struct DatabasePromise { /// Returns the resolved value. - let resolve: @Sendable (Database) throws -> T + let resolve: @Sendable (DatabaseBase) throws -> T /// Creates a promise that resolves to a value. init(value: T) where T: Sendable { @@ -31,7 +31,7 @@ struct DatabasePromise { } /// Creates a promise from a closure. - init(_ resolve: @escaping @Sendable (Database) throws -> T) { + init(_ resolve: @escaping @Sendable (DatabaseBase) throws -> T) { self.resolve = resolve } diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 337f688b5..56f9fa2fb 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -99,7 +99,7 @@ public struct SQLExpression: Sendable { /// The `CAST(expr AS storage-class)` expression. /// /// See . - indirect case cast(SQLExpression, Database.StorageClass) + indirect case cast(SQLExpression, DatabaseStorageClass) /// The `BETWEEN` and `NOT BETWEEN` operators. /// @@ -1135,7 +1135,7 @@ extension SQLExpression { /// The `CAST(expr AS storage-class)` expression. /// /// See . - static func cast(_ expression: SQLExpression, as storageClass: Database.StorageClass) -> Self { + static func cast(_ expression: SQLExpression, as storageClass: DatabaseStorageClass) -> Self { self.init(impl: .cast(expression, storageClass)) } @@ -1193,7 +1193,7 @@ extension SQLExpression { /// The expression as a quoted SQL literal (not public in order to avoid abuses) /// /// try "foo'bar".databaseValue.quotedSQL(db) // "'foo''bar'"" - func quotedSQL(_ db: Database) throws -> String { + func quotedSQL(_ db: DatabaseBase) throws -> String { let context = SQLGenerationContext(db, argumentsSink: .literalValues) return try sql(context) } @@ -1223,7 +1223,7 @@ extension SQLExpression { /// - parameter acceptsBijection: If true, expressions that define a /// bijection on a column return this column. For example: `-score` /// returns `score`. - func column(_ db: Database, for alias: TableAliasBase, acceptsBijection: Bool = false) throws -> String? { + func column(_ db: DatabaseBase, for alias: TableAliasBase, acceptsBijection: Bool = false) throws -> String? { switch impl { case let .qualifiedColumn(name, a): if alias == a { @@ -1510,7 +1510,7 @@ extension SQLExpression { /// /// // SELECT * FROM "player" WHERE "name" = 'Arthur' LIMIT 1 /// try Player.filter(Column("name") == "Arthur").fetchOne(db) - func identifyingColums(_ db: Database, for alias: TableAliasBase) throws -> Set { + func identifyingColums(_ db: DatabaseBase, for alias: TableAliasBase) throws -> Set { switch impl { case let .rowValue(expressions): assert(!expressions.isEmpty) @@ -1578,7 +1578,7 @@ extension SQLExpression { /// let request = Player.filter(keys: [1, 2, 3]) /// let regionObservation = DatabaseRegionObservation(tracking: request) /// let valueObservation = ValueObservation.tracking(request.fetchAll) - func identifyingRowIDs(_ db: Database, for alias: TableAliasBase) throws -> Set? { + func identifyingRowIDs(_ db: DatabaseBase, for alias: TableAliasBase) throws -> Set? { switch impl { case let .databaseValue(dbValue): if dbValue.isNull || dbValue == false.databaseValue { @@ -1993,7 +1993,7 @@ struct SQLSimpleFunctionInvocation { isJSONValue: isJSONValue) } - func column(_ db: Database, for alias: TableAliasBase) throws -> String? { + func column(_ db: DatabaseBase, for alias: TableAliasBase) throws -> String? { let name = name.uppercased() if ["HEX", "QUOTE"].contains(name) && arguments.count == 1 { return try arguments[0].column(db, for: alias, acceptsBijection: true) diff --git a/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift b/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift index a3c5bfe37..0dbbe40ca 100644 --- a/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift +++ b/GRDB/QueryInterface/SQL/SQLForeignKeyRequest.swift @@ -21,7 +21,7 @@ struct SQLForeignKeyRequest { } /// The (origin, destination) column pairs that join a left table to a right table. - func fetchForeignKeyMapping(_ db: Database) throws -> ForeignKeyMapping { + func fetchForeignKeyMapping(_ db: DatabaseBase) throws -> ForeignKeyMapping { if let originColumns, let destinationColumns { // Total information: no need to query the database schema. GRDBPrecondition(originColumns.count == destinationColumns.count, "Number of columns don't match") @@ -122,7 +122,7 @@ struct SQLForeignKeyRequest { var isView: Bool } - private func tableType(_ db: Database, for name: String) throws -> TableType? { + private func tableType(_ db: DatabaseBase, for name: String) throws -> TableType? { for schemaID in try db.fetchSchemaIdentifiers() { if try db.schema(schemaID).containsObjectNamed(name, ofType: .table) { return TableType(isView: false) diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index 3755e4255..476082bdb 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -67,7 +67,7 @@ public func average(_ value: some SQLSpecificExpressible) -> SQLExpression { /// ``` /// /// Related SQLite documentation: -public func cast(_ expression: some SQLSpecificExpressible, as storageClass: Database.StorageClass) -> SQLExpression { +public func cast(_ expression: some SQLSpecificExpressible, as storageClass: DatabaseStorageClass) -> SQLExpression { .cast(expression.sqlExpression, as: storageClass) } diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 6fdf125db..7a14681da 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -187,7 +187,7 @@ extension SQLRelation { /// Convenience factory methods which selects all rows from a table. static func all( fromTable tableName: String, - selection: @escaping @Sendable (Database) -> [SQLSelection] = { _ in [.allColumns] }) + selection: @escaping @Sendable (DatabaseBase) -> [SQLSelection] = { _ in [.allColumns] }) -> Self { SQLRelation( @@ -197,7 +197,7 @@ extension SQLRelation { } extension SQLRelation: Refinable { - func selectWhenConnected(_ selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self { + func selectWhenConnected(_ selection: @escaping @Sendable (DatabaseBase) throws -> [SQLSelection]) -> Self { with { $0.selectionPromise = DatabasePromise(selection) } @@ -228,7 +228,7 @@ extension SQLRelation: Refinable { } } - func annotatedWhenConnected(with selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self { + func annotatedWhenConnected(with selection: @escaping @Sendable (DatabaseBase) throws -> [SQLSelection]) -> Self { with { let old = $0.selectionPromise $0.selectionPromise = DatabasePromise { db in @@ -242,7 +242,7 @@ extension SQLRelation: Refinable { annotatedWhenConnected(with: { _ in selection }) } - func filterWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self { + func filterWhenConnected(_ predicate: @escaping @Sendable (DatabaseBase) throws -> SQLExpression) -> Self { with { if let old = $0.filterPromise { $0.filterPromise = DatabasePromise { db in @@ -259,7 +259,7 @@ extension SQLRelation: Refinable { filterWhenConnected { _ in predicate } } - func orderWhenConnected(_ orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) -> Self { + func orderWhenConnected(_ orderings: @escaping @Sendable (DatabaseBase) throws -> [SQLOrdering]) -> Self { with { $0.ordering = SQLRelation.Ordering(orderings: orderings) } @@ -315,13 +315,13 @@ extension SQLRelation: Refinable { } } - func groupWhenConnected(_ expressions: @escaping @Sendable (Database) throws -> [SQLExpression]) -> Self { + func groupWhenConnected(_ expressions: @escaping @Sendable (DatabaseBase) throws -> [SQLExpression]) -> Self { with { $0.groupPromise = DatabasePromise(expressions) } } - func havingWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self { + func havingWhenConnected(_ predicate: @escaping @Sendable (DatabaseBase) throws -> SQLExpression) -> Self { with { if let old = $0.havingExpressionPromise { $0.havingExpressionPromise = DatabasePromise { db in @@ -602,7 +602,7 @@ extension SQLRelation { } extension SQLRelation { - func fetchCount(_ db: Database) throws -> Int { + func fetchCount(_ db: DatabaseBase) throws -> Int { guard groupPromise == nil && limit == nil && ctes.isEmpty else { // SELECT ... GROUP BY ... // SELECT ... LIMIT ... @@ -651,7 +651,7 @@ extension SQLRelation { } // SELECT COUNT(*) FROM (self) - private func fetchTrivialCount(_ db: Database) throws -> Int { + private func fetchTrivialCount(_ db: DatabaseBase) throws -> Int { let countRequest: SQLRequest = "SELECT COUNT(*) FROM (\(SQLSubquery.relation(unordered())))" return try countRequest.fetchOne(db)! } @@ -716,7 +716,7 @@ extension SQLRelation { } } - func resolve(_ db: Database) throws -> [SQLOrdering] { + func resolve(_ db: DatabaseBase) throws -> [SQLOrdering] { switch self { case .terms(let terms): return try terms.resolve(db) @@ -742,7 +742,7 @@ extension SQLRelation { isReversed: false) } - init(orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) { + init(orderings: @escaping @Sendable (DatabaseBase) throws -> [SQLOrdering]) { self.init( elements: [.terms(DatabasePromise(orderings))], isReversed: false) @@ -766,7 +766,7 @@ extension SQLRelation { isReversed: isReversed) } - func resolve(_ db: Database) throws -> [SQLOrdering] { + func resolve(_ db: DatabaseBase) throws -> [SQLOrdering] { if isReversed { return try elements.flatMap { try $0.reversed.resolve(db) } } else { @@ -832,7 +832,7 @@ enum SQLAssociationCondition: Sendable { } func joinExpression( - _ db: Database, + _ db: DatabaseBase, leftAlias: TableAliasBase, rightAlias: TableAliasBase) throws -> SQLExpression? @@ -891,7 +891,7 @@ struct SQLForeignKeyCondition: Equatable { /// Turns the foreign key condition into a `JoinMapping` that can feed an /// SQL JOIN clause. - func joinMapping(_ db: Database, from originTable: String) throws -> JoinMapping { + func joinMapping(_ db: DatabaseBase, from originTable: String) throws -> JoinMapping { try foreignKeyRequest(from: originTable) .fetchForeignKeyMapping(db) .joinMapping(originIsLeft: originIsLeft) diff --git a/GRDB/QueryInterface/SQL/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift index 4a414109d..2aefd9390 100644 --- a/GRDB/QueryInterface/SQL/SQLSelection.swift +++ b/GRDB/QueryInterface/SQL/SQLSelection.swift @@ -314,7 +314,7 @@ extension [SQLSelection] { /// This method raises a fatal error if the selection contains a literal, /// /// See `SQLSelection.columnCount(_:)` for testability. - func columnCount(_ context: SQLGenerationContext) throws -> Int { + func columnCount(_ context: SQLGenerationContext) throws -> Int { try reduce(0) { acc, selection in guard let count = try selection.columnCount(context) else { // Found an SQL literal: diff --git a/GRDB/QueryInterface/SQL/SQLSubquery.swift b/GRDB/QueryInterface/SQL/SQLSubquery.swift index fdc9c3a3a..698e89f28 100644 --- a/GRDB/QueryInterface/SQL/SQLSubquery.swift +++ b/GRDB/QueryInterface/SQL/SQLSubquery.swift @@ -40,7 +40,7 @@ extension SQLSubquery { /// // We know that "SELECT 1 AS a, 2 AS b" selects two columns, /// // so we can find cte columns in the row: /// row.scopes["cte"] // [a:1, b:2] - func columnCount(_ db: Database) throws -> Int { + func columnCount(_ db: DatabaseBase) throws -> Int { switch impl { case let .literal(sqlLiteral): // Compile request. We can freely use the statement cache because we diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index b60c05291..541604b58 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -177,7 +177,7 @@ extension Table where RowDecoder == Row { } extension Table: DatabaseRegionConvertible { - public func databaseRegion(_ db: Database) throws -> DatabaseRegion { + public func databaseRegion(_ db: DatabaseBase) throws -> DatabaseRegion { DatabaseRegion(table: tableName) } } @@ -848,7 +848,7 @@ extension Table { /// ``` /// /// - parameter db: A database connection. - public func fetchCount(_ db: Database) throws -> Int { + public func fetchCount(_ db: DatabaseBase) throws -> Int { try all().fetchCount(db) } } @@ -885,7 +885,7 @@ extension Table where RowDecoder: FetchableRecord { /// - parameter db: A database connection. /// - returns: A ``RecordCursor`` over fetched records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> RecordCursor { + public func fetchCursor(_ db: DatabaseBase) throws -> RecordCursor { try all().fetchCursor(db) } @@ -908,7 +908,7 @@ extension Table where RowDecoder: FetchableRecord { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder] { + public func fetchAll(_ db: DatabaseBase) throws -> [RowDecoder] { try all().fetchAll(db) } @@ -928,7 +928,7 @@ extension Table where RowDecoder: FetchableRecord { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> RowDecoder? { + public func fetchOne(_ db: DatabaseBase) throws -> RowDecoder? { try all().fetchOne(db) } } @@ -950,7 +950,7 @@ extension Table where RowDecoder: FetchableRecord & Hashable { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchSet(_ db: Database) throws -> Set { + public func fetchSet(_ db: DatabaseBase) throws -> Set { try all().fetchSet(db) } } @@ -987,7 +987,7 @@ extension Table where RowDecoder == Row { /// - parameter db: A database connection. /// - returns: A ``RowCursor`` over fetched rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> RowCursor { + public func fetchCursor(_ db: DatabaseBase) throws -> RowCursor { try all().fetchCursor(db) } @@ -1009,7 +1009,7 @@ extension Table where RowDecoder == Row { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [Row] { + public func fetchAll(_ db: DatabaseBase) throws -> [Row] { try all().fetchAll(db) } @@ -1028,7 +1028,7 @@ extension Table where RowDecoder == Row { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> Row? { + public func fetchOne(_ db: DatabaseBase) throws -> Row? { try all().fetchOne(db) } @@ -1047,7 +1047,7 @@ extension Table where RowDecoder == Row { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchSet(_ db: Database) throws -> Set { + public func fetchSet(_ db: DatabaseBase) throws -> Set { try all().fetchSet(db) } } @@ -1071,7 +1071,7 @@ extension Table where RowDecoder: DatabaseValueConvertible { /// - parameter db: A database connection. /// - returns: A ``DatabaseValueCursor`` over fetched values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor { + public func fetchCursor(_ db: DatabaseBase) throws -> DatabaseValueCursor { try all().fetchCursor(db) } @@ -1082,7 +1082,7 @@ extension Table where RowDecoder: DatabaseValueConvertible { /// - parameter db: A database connection. /// - returns: An array of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder] { + public func fetchAll(_ db: DatabaseBase) throws -> [RowDecoder] { try all().fetchAll(db) } @@ -1096,7 +1096,7 @@ extension Table where RowDecoder: DatabaseValueConvertible { /// - parameter db: A database connection. /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> RowDecoder? { + public func fetchOne(_ db: DatabaseBase) throws -> RowDecoder? { try all().fetchOne(db) } } @@ -1109,7 +1109,7 @@ extension Table where RowDecoder: DatabaseValueConvertible & Hashable { /// - parameter db: A database connection. /// - returns: A set of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchSet(_ db: Database) throws -> Set { + public func fetchSet(_ db: DatabaseBase) throws -> Set { try all().fetchSet(db) } } @@ -1133,7 +1133,7 @@ extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConv /// - parameter db: A database connection. /// - returns: A ``FastDatabaseValueCursor`` over fetched values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> FastDatabaseValueCursor { + public func fetchCursor(_ db: DatabaseBase) throws -> FastDatabaseValueCursor { try all().fetchCursor(db) } @@ -1144,7 +1144,7 @@ extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConv /// - parameter db: A database connection. /// - returns: An array of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder] { + public func fetchAll(_ db: DatabaseBase) throws -> [RowDecoder] { try all().fetchAll(db) } @@ -1158,7 +1158,7 @@ extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConv /// - parameter db: A database connection. /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> RowDecoder? { + public func fetchOne(_ db: DatabaseBase) throws -> RowDecoder? { try all().fetchOne(db) } } @@ -1171,7 +1171,7 @@ extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConv /// - parameter db: A database connection. /// - returns: A set of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchSet(_ db: Database) throws -> Set { + public func fetchSet(_ db: DatabaseBase) throws -> Set { try all().fetchSet(db) } } @@ -1568,7 +1568,7 @@ extension Table { /// - returns: The number of deleted rows /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult - public func deleteAll(_ db: Database) throws -> Int { + public func deleteAll(_ db: DatabaseBase) throws -> Int { try all().deleteAll(db) } } @@ -1594,7 +1594,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: some DatabaseValueConvertible) throws -> Bool { + public func exists(_ db: DatabaseBase, key: some DatabaseValueConvertible) throws -> Bool { try !filter(key: key).isEmpty(db) } } @@ -1628,7 +1628,7 @@ where RowDecoder: Identifiable, /// - db: A database connection. /// - id: A primary key value. /// - returns: Whether a row exists for this primary key. - public func exists(_ db: Database, id: RowDecoder.ID) throws -> Bool { + public func exists(_ db: DatabaseBase, id: RowDecoder.ID) throws -> Bool { if id.databaseValue.isNull { // Don't hit the database return false @@ -1665,7 +1665,7 @@ extension Table { /// - db: A database connection. /// - key: A key dictionary. /// - returns: Whether a row exists for this key. - public func exists(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { + public func exists(_ db: DatabaseBase, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { try !filter(key: key).isEmpty(db) } } @@ -1697,7 +1697,7 @@ extension Table { /// - returns: The number of deleted rows. @discardableResult public func deleteAll( - _ db: Database, + _ db: DatabaseBase, keys: some Collection ) throws -> Int { if keys.isEmpty { @@ -1730,7 +1730,7 @@ extension Table { /// - key: A primary key value. /// - returns: Whether a row was deleted. @discardableResult - public func deleteOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Bool { + public func deleteOne(_ db: DatabaseBase, key: some DatabaseValueConvertible) throws -> Bool { if key.databaseValue.isNull { // Don't hit the database return false @@ -1774,7 +1774,7 @@ where RowDecoder: Identifiable, /// - returns: The number of deleted rows. @discardableResult public func deleteAll( - _ db: Database, + _ db: DatabaseBase, ids: some Collection ) throws -> Int { if ids.isEmpty { @@ -1814,7 +1814,7 @@ where RowDecoder: Identifiable, /// - id: A primary key value. /// - returns: Whether a row was deleted. @discardableResult - public func deleteOne(_ db: Database, id: RowDecoder.ID) throws -> Bool { + public func deleteOne(_ db: DatabaseBase, id: RowDecoder.ID) throws -> Bool { if id.databaseValue.isNull { // Don't hit the database return false @@ -1857,7 +1857,7 @@ extension Table { /// - keys: An array of key dictionaries. /// - returns: The number of deleted rows. @discardableResult - public func deleteAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Int { + public func deleteAll(_ db: DatabaseBase, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Int { if keys.isEmpty { // Avoid hitting the database return 0 @@ -1896,7 +1896,7 @@ extension Table { /// - key: A key dictionary. /// - returns: Whether a row was deleted. @discardableResult - public func deleteOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { + public func deleteOne(_ db: DatabaseBase, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { try deleteAll(db, keys: [key]) > 0 } } @@ -1930,8 +1930,8 @@ extension Table { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public func updateAll( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, assignment: (DatabaseComponents) throws -> ColumnAssignment ) throws -> Int where RowDecoder: TableRecord @@ -1966,8 +1966,8 @@ extension Table { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public func updateAll( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, assignments: (DatabaseComponents) throws -> [ColumnAssignment] ) throws -> Int where RowDecoder: TableRecord @@ -1995,8 +1995,8 @@ extension Table { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public func updateAll( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, _ assignments: [ColumnAssignment]) throws -> Int { @@ -2023,8 +2023,8 @@ extension Table { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public func updateAll( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, _ assignments: ColumnAssignment...) throws -> Int { diff --git a/GRDB/QueryInterface/SQLGeneration/SQLColumnGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLColumnGenerator.swift index d8754514c..6377fbe90 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLColumnGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLColumnGenerator.swift @@ -8,7 +8,7 @@ enum SQLColumnGenerator { /// primary key columns in the table that contains the column. If /// the result is nil, the primary key is the hidden rowID. func sql( - _ db: Database, + _ db: DatabaseBase, tableName: String, primaryKeyColumns: () throws -> [SQLColumnDescriptor]?) throws -> String @@ -27,7 +27,7 @@ enum SQLColumnGenerator { } private func columnSQL( - _ db: Database, + _ db: DatabaseBase, column: ColumnDefinition, tableName: String, primaryKeyColumns: () throws -> [SQLColumnDescriptor]?) diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index d4fac3f8d..c8c2ebae8 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -7,14 +7,14 @@ /// and columns. /// /// - It gathers SQL arguments in order to prevent SQL injection. -final class SQLGenerationContext { +final class SQLGenerationContext { private enum Parent { - case none(db: Database, argumentsSink: StatementArgumentsSink) + case none(db: DatabaseBase, argumentsSink: StatementArgumentsSink) case context(SQLGenerationContext) } /// A database connection. - var db: Database { + var db: DatabaseBase { switch parent { case let .none(db: db, argumentsSink: _): return db case let .context(context): return context.db @@ -48,7 +48,7 @@ final class SQLGenerationContext { /// - parameter aliases: An array of table aliases to disambiguate. /// - parameter ctes: An dictionary of available CTEs. init( - _ db: Database, + _ db: DatabaseBase, argumentsSink: StatementArgumentsSink = StatementArgumentsSink(), aliases: [TableAliasBase] = [], ctes: OrderedDictionary = [:]) diff --git a/GRDB/QueryInterface/SQLGeneration/SQLIndexGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLIndexGenerator.swift index 81e63a3de..b250e3b0f 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLIndexGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLIndexGenerator.swift @@ -5,7 +5,7 @@ struct SQLIndexGenerator { let options: IndexOptions let condition: SQLExpression? - func sql(_ db: Database) throws -> String { + func sql(_ db: DatabaseBase) throws -> String { var sql: SQL = "CREATE" if options.contains(.unique) { diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index f4b8fdccf..cda1dbfcc 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -91,14 +91,14 @@ struct SQLQueryGenerator: Refinable { return sql } - func makePreparedRequest(_ db: Database) throws -> PreparedRequest { - try PreparedRequest( + func makePreparedRequest(_ db: DatabaseBase) throws -> PreparedRequestBase { + try PreparedRequestBase( statement: makeStatement(db), adapter: rowAdapter(SQLGenerationContext(db, ctes: relation.ctes))) } /// The number of fetched columns. - func columnCount(_ db: Database) throws -> Int { + func columnCount(_ db: DatabaseBase) throws -> Int { try relation .selectionPromise .resolve(db) @@ -106,7 +106,7 @@ struct SQLQueryGenerator: Refinable { } /// Returns a prepared statement - func makeStatement(_ db: Database) throws -> Statement { + func makeStatement(_ db: DatabaseBase) throws -> StatementBase { // Build let context = SQLGenerationContext(db) let sql = try requestSQL(context) @@ -149,7 +149,7 @@ struct SQLQueryGenerator: Refinable { /// /// The optimized region allows us to track individual rowids, and also /// discard some provably empty requests such as `Player.none()`. - private func optimizedSelectedRegion(_ db: Database, _ selectedRegion: DatabaseRegion) throws -> DatabaseRegion { + private func optimizedSelectedRegion(_ db: DatabaseBase, _ selectedRegion: DatabaseRegion) throws -> DatabaseRegion { var optimizedRegion = selectedRegion // Give up unless request feeds from a database table @@ -175,7 +175,7 @@ struct SQLQueryGenerator: Refinable { /// If true, executing this query yields at most one row. /// If false, we don't know how many rows this query returns. private func expectsSingleResult( - _ db: Database, + _ db: DatabaseBase, selection: [SQLSelection], filter: SQLExpression?, groupExpressions: [SQLExpression]) @@ -207,7 +207,7 @@ struct SQLQueryGenerator: Refinable { /// Returns a `DELETE` statement, with `RETURNING` clause if `selection` /// is not empty. - func makeDeleteStatement(_ db: Database, selection: [any SQLSelectable] = []) throws -> Statement { + func makeDeleteStatement(_ db: DatabaseBase, selection: [any SQLSelectable] = []) throws -> Statement { switch try grouping(db) { case .none: guard relation.joins.isEmpty else { @@ -252,7 +252,7 @@ struct SQLQueryGenerator: Refinable { /// DELETE FROM table WHERE id IN (SELECT id FROM table ...) /// DELETE FROM table WHERE id IN (SELECT id FROM table ...) RETURNING ... - private func makeTrivialDeleteStatement(_ db: Database, selection: [any SQLSelectable]) throws -> Statement { + private func makeTrivialDeleteStatement(_ db: DatabaseBase, selection: [any SQLSelectable]) throws -> Statement { let tableName = relation.source.tableName let alias = TableAlias(tableName: tableName) let context = SQLGenerationContext(db, aliases: [alias]) @@ -280,8 +280,8 @@ struct SQLQueryGenerator: Refinable { /// /// Returns nil if assignments is empty. func makeUpdateStatement( - _ db: Database, - conflictResolution: Database.ConflictResolution, + _ db: DatabaseBase, + conflictResolution: DatabaseConflictResolution, assignments: [ColumnAssignment], selection: [any SQLSelectable] = []) throws -> Statement? @@ -354,8 +354,8 @@ struct SQLQueryGenerator: Refinable { /// UPDATE table SET ... WHERE id IN (SELECT id FROM table ...) RETURNING ... /// Returns nil if assignments is empty private func makeTrivialUpdateStatement( - _ db: Database, - conflictResolution: Database.ConflictResolution, + _ db: DatabaseBase, + conflictResolution: DatabaseConflictResolution, assignments: [ColumnAssignment], selection: [any SQLSelectable]) throws -> Statement? @@ -401,7 +401,7 @@ struct SQLQueryGenerator: Refinable { // Support for the RETURNING clause private func makeStatement( - _ db: Database, + _ db: DatabaseBase, sql: String, arguments: StatementArguments, returning selection: [any SQLSelectable], @@ -471,7 +471,7 @@ struct SQLQueryGenerator: Refinable { } /// Informs about the query grouping - private func grouping(_ db: Database) throws -> GroupingInfo { + private func grouping(_ db: DatabaseBase) throws -> GroupingInfo { // Empty group clause: no grouping // SELECT * FROM player guard let groupExpressions = try relation.groupPromise?.resolve(db), groupExpressions.isEmpty == false else { diff --git a/GRDB/QueryInterface/SQLGeneration/SQLTableAlterationGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLTableAlterationGenerator.swift index 030dfddb4..5eddec3b1 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLTableAlterationGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLTableAlterationGenerator.swift @@ -9,7 +9,7 @@ struct SQLTableAlterationGenerator { private var name: String private var alterations: [TableAlterationKind] = [] - func sql(_ db: Database) throws -> String { + func sql(_ db: DatabaseBase) throws -> String { var statements: [String] = [] for alteration in alterations { diff --git a/GRDB/QueryInterface/SQLGeneration/SQLTableGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLTableGenerator.swift index 29d72d96a..c46b2acaa 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLTableGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLTableGenerator.swift @@ -17,10 +17,10 @@ struct SQLTableGenerator { struct KeyConstraint { var columns: [String] - var conflictResolution: Database.ConflictResolution? + var conflictResolution: DatabaseConflictResolution? } - func sql(_ db: Database) throws -> String { + func sql(_ db: DatabaseBase) throws -> String { var statements: [String] = [] do { @@ -156,12 +156,12 @@ struct SQLTableGenerator { } extension SQLTableGenerator { - init(_ db: Database, table: TableDefinition) throws { + init(_ db: DatabaseBase, table: TableDefinition) throws { var indexOptions: IndexOptions = [] if table.options.contains(.ifNotExists) { indexOptions.insert(.ifNotExists) } func makeKeyConstraint( - _ db: Database, + _ db: DatabaseBase, constraint: TableDefinition.KeyConstraint, forwardPrimaryKey: SQLPrimaryKeyDescriptor) throws -> SQLTableGenerator.KeyConstraint @@ -258,7 +258,7 @@ extension SQLTableGenerator { } private static func forwardPrimaryKeyColumns( - _ db: Database, + _ db: DatabaseBase, primaryKeyConstraint: TableDefinition.KeyConstraint, originTable: String) throws -> [SQLColumnDescriptor]? @@ -291,7 +291,7 @@ extension SQLTableGenerator { } private static func makeForeignKeyGenerator( - _ db: Database, + _ db: DatabaseBase, foreignKey: ForeignKeyDefinition, originTable: String, forwardPrimaryKey: SQLPrimaryKeyDescriptor?, @@ -464,7 +464,7 @@ struct SQLPrimaryKeyDescriptor { } extension SQLPrimaryKeyDescriptor { - static func find(_ db: Database, table: String) throws -> Self { + static func find(_ db: DatabaseBase, table: String) throws -> Self { let columnInfos = try db.primaryKey(table).columnInfos return SQLPrimaryKeyDescriptor( tableName: table, diff --git a/GRDB/QueryInterface/Schema/ColumnDefinition.swift b/GRDB/QueryInterface/Schema/ColumnDefinition.swift index f179a3b84..37daf999b 100644 --- a/GRDB/QueryInterface/Schema/ColumnDefinition.swift +++ b/GRDB/QueryInterface/Schema/ColumnDefinition.swift @@ -62,7 +62,7 @@ public final class ColumnDefinition { enum Indexing { case index - case unique(Database.ConflictResolution) + case unique(DatabaseConflictResolution) } struct ForeignKeyConstraint { @@ -90,9 +90,9 @@ public final class ColumnDefinition { let name: String let type: Database.ColumnType? - var primaryKey: (conflictResolution: Database.ConflictResolution?, autoincrement: Bool)? + var primaryKey: (conflictResolution: DatabaseConflictResolution?, autoincrement: Bool)? var indexing: Indexing? - var notNullConflictResolution: Database.ConflictResolution? + var notNullConflictResolution: DatabaseConflictResolution? var checkConstraints: [SQLExpression] = [] var foreignKeyConstraints: [ForeignKeyConstraint] = [] var defaultExpression: SQLExpression? @@ -133,7 +133,7 @@ public final class ColumnDefinition { /// - returns: `self` so that you can further refine the column definition. @discardableResult public func primaryKey( - onConflict conflictResolution: Database.ConflictResolution? = nil, + onConflict conflictResolution: DatabaseConflictResolution? = nil, autoincrement: Bool = false) -> Self { @@ -159,7 +159,7 @@ public final class ColumnDefinition { /// - parameter conflictResolution: An optional ``Database/ConflictResolution``. /// - returns: `self` so that you can further refine the column definition. @discardableResult - public func notNull(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self { + public func notNull(onConflict conflictResolution: DatabaseConflictResolution? = nil) -> Self { notNullConflictResolution = conflictResolution ?? .abort return self } @@ -182,7 +182,7 @@ public final class ColumnDefinition { /// - parameter conflictResolution: An optional ``Database/ConflictResolution``. /// - returns: `self` so that you can further refine the column definition. @discardableResult - public func unique(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self { + public func unique(onConflict conflictResolution: DatabaseConflictResolution? = nil) -> Self { indexing = .unique(conflictResolution ?? .abort) return self } diff --git a/GRDB/QueryInterface/Schema/Database+SchemaDefinition.swift b/GRDB/QueryInterface/Schema/Database+SchemaDefinition.swift index eb8b4b64c..6dae8088f 100644 --- a/GRDB/QueryInterface/Schema/Database+SchemaDefinition.swift +++ b/GRDB/QueryInterface/Schema/Database+SchemaDefinition.swift @@ -1,4 +1,4 @@ -extension Database { +extension DatabaseBase { // MARK: - Database Schema diff --git a/GRDB/QueryInterface/Schema/ForeignKeyDefinition.swift b/GRDB/QueryInterface/Schema/ForeignKeyDefinition.swift index e7754a052..37aa937a1 100644 --- a/GRDB/QueryInterface/Schema/ForeignKeyDefinition.swift +++ b/GRDB/QueryInterface/Schema/ForeignKeyDefinition.swift @@ -22,7 +22,7 @@ public final class ForeignKeyDefinition { var updateAction: Database.ForeignKeyAction? var indexing: Indexing? var isDeferred: Bool - var notNullConflictResolution: Database.ConflictResolution? + var notNullConflictResolution: DatabaseConflictResolution? init( name: String, @@ -59,7 +59,7 @@ public final class ForeignKeyDefinition { /// - returns: `self` so that you can further refine the definition of /// the association. @discardableResult - public func notNull(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self { + public func notNull(onConflict conflictResolution: DatabaseConflictResolution? = nil) -> Self { notNullConflictResolution = conflictResolution ?? .abort return self } @@ -87,7 +87,7 @@ public final class ForeignKeyDefinition { return self } - func primaryKey(_ db: Database) throws -> SQLPrimaryKeyDescriptor { + func primaryKey(_ db: DatabaseBase) throws -> SQLPrimaryKeyDescriptor { if let table { return try SQLPrimaryKeyDescriptor.find(db, table: table) } diff --git a/GRDB/QueryInterface/Schema/IndexDefinition.swift b/GRDB/QueryInterface/Schema/IndexDefinition.swift index 567c4beff..505bfa09d 100644 --- a/GRDB/QueryInterface/Schema/IndexDefinition.swift +++ b/GRDB/QueryInterface/Schema/IndexDefinition.swift @@ -19,7 +19,7 @@ public struct IndexOptions: OptionSet, Sendable { public static let unique = IndexOptions(rawValue: 1 << 1) } -extension Database { +extension DatabaseBase { static func defaultIndexName(on table: String, columns: [String]) -> String { "index_\(table)_on_\(columns.joined(separator: "_"))" } diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 1e1be731c..52fea8bc6 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -78,14 +78,14 @@ public final class TableDefinition { case foreignKeyDefinition(ForeignKeyDefinition) } var components: [Component] - var conflictResolution: Database.ConflictResolution? + var conflictResolution: DatabaseConflictResolution? - init(components: [Component], conflictResolution: Database.ConflictResolution?) { + init(components: [Component], conflictResolution: DatabaseConflictResolution?) { self.components = components self.conflictResolution = conflictResolution } - init(columns: [String], conflictResolution: Database.ConflictResolution?) { + init(columns: [String], conflictResolution: DatabaseConflictResolution?) { let components = columns.map { name in Component.columnName(name) } @@ -143,7 +143,7 @@ public final class TableDefinition { @discardableResult public func autoIncrementedPrimaryKey( _ name: String, - onConflict conflictResolution: Database.ConflictResolution? = nil) + onConflict conflictResolution: DatabaseConflictResolution? = nil) -> ColumnDefinition { column(name, .integer).primaryKey(onConflict: conflictResolution, autoincrement: true) @@ -172,7 +172,7 @@ public final class TableDefinition { public func primaryKey( _ name: String, _ type: Database.ColumnType, - onConflict conflictResolution: Database.ConflictResolution? = nil) + onConflict conflictResolution: DatabaseConflictResolution? = nil) -> ColumnDefinition { let pk = column(name, type).primaryKey(onConflict: conflictResolution) @@ -208,7 +208,7 @@ public final class TableDefinition { /// /// A NOT NULL constraint is always added to the wrapped primary key columns. public func primaryKey( - onConflict conflictResolution: Database.ConflictResolution? = nil, + onConflict conflictResolution: DatabaseConflictResolution? = nil, body: () throws -> Void) rethrows { @@ -318,7 +318,7 @@ public final class TableDefinition { /// - parameter columns: The primary key columns. /// - parameter conflictResolution: An optional conflict resolution /// (see ). - public func primaryKey(_ columns: [String], onConflict conflictResolution: Database.ConflictResolution? = nil) { + public func primaryKey(_ columns: [String], onConflict conflictResolution: DatabaseConflictResolution? = nil) { guard primaryKeyConstraint == nil else { // Programmer error fatalError("can't define several primary keys") @@ -360,7 +360,7 @@ public final class TableDefinition { /// - parameter columns: The unique key columns. /// - parameter conflictResolution: An optional conflict resolution /// (see ). - public func uniqueKey(_ columns: [String], onConflict conflictResolution: Database.ConflictResolution? = nil) { + public func uniqueKey(_ columns: [String], onConflict conflictResolution: DatabaseConflictResolution? = nil) { uniqueKeyConstraints.append(KeyConstraint(columns: columns, conflictResolution: conflictResolution)) } diff --git a/GRDB/QueryInterface/Schema/VirtualTableModule.swift b/GRDB/QueryInterface/Schema/VirtualTableModule.swift index 5af956f02..13b2181da 100644 --- a/GRDB/QueryInterface/Schema/VirtualTableModule.swift +++ b/GRDB/QueryInterface/Schema/VirtualTableModule.swift @@ -51,7 +51,7 @@ public protocol VirtualTableModule { /// Execute any relevant database statement after the virtual table has /// been created. - func database(_ db: Database, didCreate tableName: String, using definition: TableDefinition) throws + func database(_ db: DatabaseBase, didCreate tableName: String, using definition: TableDefinition) throws } // TODO: Question the existence of this API. VirtualTableConfiguration was @@ -79,7 +79,7 @@ public struct VirtualTableOptions: OptionSet, Sendable { public static let temporary = VirtualTableOptions(rawValue: 1 << 1) } -extension Database { +extension DatabaseBase { // MARK: - Database Schema diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index 98261bc94..a02cba76e 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -402,7 +402,7 @@ public struct PersistenceContainer: Sendable { /// Convenience initializer from a database connection and a record @usableFromInline - init(_ db: Database, _ record: some EncodableRecord & TableRecord) throws { + init(_ db: DatabaseBase, _ record: some EncodableRecord & TableRecord) throws { let databaseTableName = type(of: record).databaseTableName let columnCount = try db.columns(in: databaseTableName).count self.init(minimumCapacity: columnCount) // Optimization diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index c54ab06bc..ca9d9be31 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import Foundation diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift index b75511064..dbf5683a6 100644 --- a/GRDB/Record/FetchableRecord+TableRecord.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -30,7 +30,7 @@ extension FetchableRecord where Self: TableRecord { /// - parameter db: A database connection. /// - returns: A ``RecordCursor`` over fetched records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database) throws -> RecordCursor { + public static func fetchCursor(_ db: DatabaseBase) throws -> RecordCursor { try all().fetchCursor(db) } @@ -52,7 +52,7 @@ extension FetchableRecord where Self: TableRecord { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll(_ db: Database) throws -> [Self] { + public static func fetchAll(_ db: DatabaseBase) throws -> [Self] { try all().fetchAll(db) } @@ -71,7 +71,7 @@ extension FetchableRecord where Self: TableRecord { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne(_ db: Database) throws -> Self? { + public static func fetchOne(_ db: DatabaseBase) throws -> Self? { try all().fetchOne(db) } } @@ -92,7 +92,7 @@ extension FetchableRecord where Self: TableRecord & Hashable { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet(_ db: Database) throws -> Set { + public static func fetchSet(_ db: DatabaseBase) throws -> Set { try all().fetchSet(db) } } @@ -129,7 +129,7 @@ extension FetchableRecord where Self: TableRecord { /// - returns: A ``RecordCursor`` over fetched records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor( - _ db: Database, + _ db: DatabaseBase, keys: some Collection ) throws -> RecordCursor { try filter(keys: keys).fetchCursor(db) @@ -155,7 +155,7 @@ extension FetchableRecord where Self: TableRecord { /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll( - _ db: Database, + _ db: DatabaseBase, keys: some Collection ) throws -> [Self] { if keys.isEmpty { @@ -181,7 +181,7 @@ extension FetchableRecord where Self: TableRecord { /// - key: A primary key value. /// - returns: An optional record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Self? { + public static func fetchOne(_ db: DatabaseBase, key: some DatabaseValueConvertible) throws -> Self? { if key.databaseValue.isNull { // Don't hit the database return nil @@ -208,7 +208,7 @@ extension FetchableRecord where Self: TableRecord { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or a /// ``RecordError/recordNotFound(databaseTableName:key:)`` if the record /// does not exist in the database. - public static func find(_ db: Database, key: some DatabaseValueConvertible) throws -> Self { + public static func find(_ db: DatabaseBase, key: some DatabaseValueConvertible) throws -> Self { guard let record = try fetchOne(db, key: key) else { throw recordNotFound(db, key: key) } @@ -248,7 +248,7 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa /// - returns: A ``RecordCursor`` over fetched records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor( - _ db: Database, + _ db: DatabaseBase, ids: some Collection ) throws -> RecordCursor { try filter(ids: ids).fetchCursor(db) @@ -274,7 +274,7 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll( - _ db: Database, + _ db: DatabaseBase, ids: some Collection ) throws -> [Self] { if ids.isEmpty { @@ -300,7 +300,7 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa /// - id: A primary key value. /// - returns: An optional record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, id: ID) throws -> Self? { + public static func fetchOne(_ db: DatabaseBase, id: ID) throws -> Self? { try filter(id: id).fetchOne(db) } @@ -323,7 +323,7 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or a /// ``RecordError/recordNotFound(databaseTableName:key:)`` if the record /// does not exist in the database. - public static func find(_ db: Database, id: ID) throws -> Self { + public static func find(_ db: DatabaseBase, id: ID) throws -> Self { try find(db, key: id) } } @@ -346,7 +346,7 @@ extension FetchableRecord where Self: TableRecord & Hashable { /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet( - _ db: Database, + _ db: DatabaseBase, keys: some Collection ) throws -> Set { if keys.isEmpty { @@ -375,7 +375,7 @@ extension FetchableRecord where Self: TableRecord & Hashable & Identifiable, ID: /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet( - _ db: Database, + _ db: DatabaseBase, ids: some Collection ) throws -> Set { if ids.isEmpty { @@ -420,7 +420,7 @@ extension FetchableRecord where Self: TableRecord { /// - keys: An array of key dictionaries. /// - returns: A ``RecordCursor`` over fetched records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) + public static func fetchCursor(_ db: DatabaseBase, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> RecordCursor { try filter(keys: keys).fetchCursor(db) @@ -447,7 +447,7 @@ extension FetchableRecord where Self: TableRecord { /// - keys: An array of key dictionaries. /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> [Self] { + public static func fetchAll(_ db: DatabaseBase, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> [Self] { if keys.isEmpty { // Avoid hitting the database return [] @@ -471,7 +471,7 @@ extension FetchableRecord where Self: TableRecord { /// - key: A key dictionary. /// - returns: An optional record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]?) throws -> Self? { + public static func fetchOne(_ db: DatabaseBase, key: [String: (any DatabaseValueConvertible)?]?) throws -> Self? { guard let key else { // Avoid hitting the database return nil @@ -498,7 +498,7 @@ extension FetchableRecord where Self: TableRecord { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or a /// ``RecordError/recordNotFound(databaseTableName:key:)`` if the record /// does not exist in the database. - public static func find(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Self { + public static func find(_ db: DatabaseBase, key: [String: (any DatabaseValueConvertible)?]) throws -> Self { guard let record = try filter(key: key).fetchOne(db) else { throw recordNotFound(key: key) } @@ -525,7 +525,7 @@ extension FetchableRecord where Self: TableRecord & Hashable { /// - keys: An array of key dictionaries. /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Set { + public static func fetchSet(_ db: DatabaseBase, 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 5cb2b0b58..84df06475 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -322,7 +322,7 @@ extension FetchableRecord { /// - returns: A ``RecordCursor`` over fetched records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor( - _ statement: Statement, + _ statement: StatementBase, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws -> RecordCursor @@ -350,7 +350,7 @@ extension FetchableRecord { /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll( - _ statement: Statement, + _ statement: StatementBase, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws -> [Self] @@ -378,7 +378,7 @@ extension FetchableRecord { /// - returns: An optional record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne( - _ statement: Statement, + _ statement: StatementBase, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws -> Self? @@ -408,7 +408,7 @@ extension FetchableRecord where Self: Hashable { /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet( - _ statement: Statement, + _ statement: StatementBase, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws -> Set @@ -450,7 +450,7 @@ extension FetchableRecord { /// - returns: A ``RecordCursor`` over fetched records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor( - _ db: Database, + _ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil) @@ -479,7 +479,7 @@ extension FetchableRecord { /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll( - _ db: Database, + _ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil) @@ -508,7 +508,7 @@ extension FetchableRecord { /// - returns: An optional record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne( - _ db: Database, + _ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil) @@ -539,7 +539,7 @@ extension FetchableRecord where Self: Hashable { /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet( - _ db: Database, + _ db: DatabaseBase, sql: String, arguments: StatementArguments = StatementArguments(), adapter: (any RowAdapter)? = nil) @@ -599,7 +599,7 @@ extension FetchableRecord { /// - request: a fetch request. /// - returns: A ``RecordCursor`` over fetched records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: some FetchRequest) throws -> RecordCursor { + public static func fetchCursor(_ db: DatabaseBase, _ request: some FetchRequest) throws -> RecordCursor { let request = try request.makePreparedRequest(db, forSingleResult: false) precondition(request.supplementaryFetch == nil, "Not implemented: fetchCursor with supplementary fetch") return try fetchCursor(request.statement, adapter: request.adapter) @@ -642,7 +642,7 @@ extension FetchableRecord { /// - request: a fetch request. /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] { + public static func fetchAll(_ db: DatabaseBase, _ request: some FetchRequest) throws -> [Self] { let request = try request.makePreparedRequest(db, forSingleResult: false) if let supplementaryFetch = request.supplementaryFetch { let rows = try Row.fetchAll(request.statement, adapter: request.adapter) @@ -689,7 +689,7 @@ extension FetchableRecord { /// - request: a fetch request. /// - returns: An optional record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? { + public static func fetchOne(_ db: DatabaseBase, _ request: some FetchRequest) throws -> Self? { let request = try request.makePreparedRequest(db, forSingleResult: true) if let supplementaryFetch = request.supplementaryFetch { guard let row = try Row.fetchOne(request.statement, adapter: request.adapter) else { @@ -741,7 +741,7 @@ extension FetchableRecord where Self: Hashable { /// - request: a fetch request. /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set { + public static func fetchSet(_ db: DatabaseBase, _ request: some FetchRequest) throws -> Set { let request = try request.makePreparedRequest(db, forSingleResult: false) if let supplementaryFetch = request.supplementaryFetch { let rows = try Row.fetchAll(request.statement, adapter: request.adapter) @@ -805,7 +805,7 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// - db: A database connection. /// - returns: A ``RecordCursor`` over fetched records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> RecordCursor { + public func fetchCursor(_ db: DatabaseBase) throws -> RecordCursor { try RowDecoder.fetchCursor(db, self) } @@ -845,7 +845,7 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// - db: A database connection. /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder] { + public func fetchAll(_ db: DatabaseBase) throws -> [RowDecoder] { try RowDecoder.fetchAll(db, self) } @@ -884,7 +884,7 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// - db: A database connection. /// - returns: An optional record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> RowDecoder? { + public func fetchOne(_ db: DatabaseBase) throws -> RowDecoder? { try RowDecoder.fetchOne(db, self) } } @@ -926,7 +926,7 @@ extension FetchRequest where RowDecoder: FetchableRecord & Hashable { /// - db: A database connection. /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func fetchSet(_ db: Database) throws -> Set { + public func fetchSet(_ db: DatabaseBase) throws -> Set { try RowDecoder.fetchSet(db, self) } } diff --git a/GRDB/Record/MutablePersistableRecord+DAO.swift b/GRDB/Record/MutablePersistableRecord+DAO.swift index de15f6e87..3f44d699f 100644 --- a/GRDB/Record/MutablePersistableRecord+DAO.swift +++ b/GRDB/Record/MutablePersistableRecord+DAO.swift @@ -1,7 +1,7 @@ /// DAO takes care of MutablePersistableRecord CRUD -final class DAO { +final class DAO { /// The database - let db: Database + let db: DatabaseBase /// DAO keeps a copy the record's persistenceContainer, so that this /// dictionary is built once whatever the database operation. It is @@ -14,7 +14,7 @@ final class DAO { /// The table primary key info let primaryKey: PrimaryKeyInfo - init(_ db: Database, _ record: Record) throws { + init(_ db: DatabaseBase, _ record: Record) throws { self.db = db databaseTableName = type(of: record).databaseTableName primaryKey = try db.primaryKey(databaseTableName) @@ -23,10 +23,10 @@ final class DAO { } func insertStatement( - _ db: Database, - onConflict: Database.ConflictResolution, + _ db: DatabaseBase, + onConflict: DatabaseConflictResolution, returning selection: [any SQLSelectable]) - throws -> Statement + throws -> StatementBase { let query = InsertQuery( onConflict: onConflict, @@ -40,7 +40,7 @@ final class DAO { } func upsertStatement( - _ db: Database, + _ db: DatabaseBase, onConflict conflictTargetColumns: [String], doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?, updateCondition: (( @@ -48,7 +48,7 @@ final class DAO { _ excluded: TableAlias ) -> any SQLExpressible)? = nil, returning selection: [any SQLSelectable]) - throws -> Statement + throws -> StatementBase { // INSERT let insertedColumns = persistenceContainer.columns @@ -138,9 +138,9 @@ final class DAO { /// Returns nil if and only if primary key is nil func updateStatement( columns: Set, - onConflict: Database.ConflictResolution, + onConflict: DatabaseConflictResolution, returning selection: [any SQLSelectable]) - throws -> Statement? + throws -> StatementBase? { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns @@ -192,7 +192,7 @@ final class DAO { } /// Returns nil if and only if primary key is nil - func deleteStatement() throws -> Statement? { + func deleteStatement() throws -> StatementBase? { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns let primaryKeyValues = primaryKeyColumns.map { @@ -211,7 +211,7 @@ final class DAO { } /// Returns nil if and only if primary key is nil - func existsStatement() throws -> Statement? { + func existsStatement() throws -> StatementBase? { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns let primaryKeyValues = primaryKeyColumns.map { @@ -244,7 +244,7 @@ final class DAO { sql: String, checkedArguments arguments: StatementArguments, returning selection: [any SQLSelectable]) - throws -> Statement + throws -> StatementBase { if selection.isEmpty { let statement = try db.internalCachedStatement(sql: sql) @@ -275,7 +275,7 @@ final class DAO { // MARK: - InsertQuery private struct InsertQuery: Hashable { - let onConflict: Database.ConflictResolution + let onConflict: DatabaseConflictResolution let tableName: String let insertedColumns: [String] } @@ -314,7 +314,7 @@ extension InsertQuery { // MARK: - UpdateQuery private struct UpdateQuery: Hashable { - let onConflict: Database.ConflictResolution + let onConflict: DatabaseConflictResolution let tableName: String let updatedColumns: [String] let conditionColumns: [String] diff --git a/GRDB/Record/MutablePersistableRecord+Delete.swift b/GRDB/Record/MutablePersistableRecord+Delete.swift index 0009970bf..9e6fd6c6d 100644 --- a/GRDB/Record/MutablePersistableRecord+Delete.swift +++ b/GRDB/Record/MutablePersistableRecord+Delete.swift @@ -3,11 +3,11 @@ extension MutablePersistableRecord { @inline(__always) @inlinable - public func willDelete(_ db: Database) throws { } + public func willDelete(_ db: DatabaseBase) throws { } @inline(__always) @inlinable - public func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + public func aroundDelete(_ db: DatabaseBase, delete: () throws -> Bool) throws { _ = try delete() } @@ -26,7 +26,7 @@ extension MutablePersistableRecord { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult @inlinable // allow specialization so that empty callbacks are removed - public func delete(_ db: Database) throws -> Bool { + public func delete(_ db: DatabaseBase) throws -> Bool { try willDelete(db) var deleted: Bool? @@ -48,7 +48,7 @@ extension MutablePersistableRecord { extension MutablePersistableRecord { /// Executes an `DELETE` statement, and DOES NOT run deletion callbacks. @usableFromInline - func deleteWithoutCallbacks(_ db: Database) throws -> Bool { + func deleteWithoutCallbacks(_ db: DatabaseBase) throws -> Bool { guard let statement = try DAO(db, self).deleteStatement() else { // Nil primary key return false diff --git a/GRDB/Record/MutablePersistableRecord+Insert.swift b/GRDB/Record/MutablePersistableRecord+Insert.swift index 3859f51e9..79888d4ee 100644 --- a/GRDB/Record/MutablePersistableRecord+Insert.swift +++ b/GRDB/Record/MutablePersistableRecord+Insert.swift @@ -3,11 +3,11 @@ extension MutablePersistableRecord { @inline(__always) @inlinable - public mutating func willInsert(_ db: Database) throws { } + public mutating func willInsert(_ db: DatabaseBase) throws { } @inline(__always) @inlinable - public func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + public func aroundInsert(_ db: DatabaseBase, insert: () throws -> InsertionSuccess) throws { _ = try insert() } @@ -38,8 +38,8 @@ extension MutablePersistableRecord { /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public mutating func insert( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil) + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil) throws { try willSave(db) @@ -77,8 +77,8 @@ extension MutablePersistableRecord { /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public func inserted( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil) + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil) throws -> Self { var result = self @@ -114,8 +114,8 @@ extension MutablePersistableRecord { /// thrown if the insertion failed due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed public func insertAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil) + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil) throws -> Self where Self: FetchableRecord { @@ -179,8 +179,8 @@ extension MutablePersistableRecord { /// thrown if the insertion failed due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed public mutating func insertAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, as returnedType: T.Type) throws -> T { @@ -242,11 +242,11 @@ extension MutablePersistableRecord { /// error thrown by the persistence callbacks defined by the record type. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed - public mutating func insertAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + public mutating func insertAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) + fetch: (StatementBase) throws -> T) throws -> T { GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") @@ -325,10 +325,10 @@ extension MutablePersistableRecord { /// error thrown by the persistence callbacks defined by the record type. /// - precondition: The result of `select` is not empty. @inlinable // allow specialization so that empty callbacks are removed - public mutating func insertAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, - fetch: (Statement) throws -> T, + public mutating func insertAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, + fetch: (StatementBase) throws -> T, select: (DatabaseComponents) throws -> [any SQLSelectable] ) throws -> T where Self: TableRecord @@ -360,8 +360,8 @@ extension MutablePersistableRecord { @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func insertAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil) + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil) throws -> Self where Self: FetchableRecord { @@ -426,8 +426,8 @@ extension MutablePersistableRecord { @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public mutating func insertAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, as returnedType: T.Type) throws -> T { @@ -490,11 +490,11 @@ extension MutablePersistableRecord { /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ - public mutating func insertAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + public mutating func insertAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) + fetch: (StatementBase) throws -> T) throws -> T { GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") @@ -574,10 +574,10 @@ extension MutablePersistableRecord { /// - precondition: The result of `select` is not empty. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ - public mutating func insertAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, - fetch: (Statement) throws -> T, + public mutating func insertAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, + fetch: (StatementBase) throws -> T, select: (DatabaseComponents) throws -> [any SQLSelectable] ) throws -> T where Self: TableRecord @@ -597,8 +597,8 @@ extension MutablePersistableRecord { /// Executes an `INSERT` statement, and runs insertion callbacks. @inlinable // allow specialization so that empty callbacks are removed mutating func insertWithCallbacks( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution?) + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution?) throws -> InsertionSuccess { let (inserted, _) = try insertAndFetchWithCallbacks(db, onConflict: conflictResolution, selection: []) { @@ -611,11 +611,11 @@ extension MutablePersistableRecord { /// Executes an `INSERT` statement, with `RETURNING` clause if `selection` /// is not empty, and runs insertion callbacks. @inlinable // allow specialization so that empty callbacks are removed - mutating func insertAndFetchWithCallbacks( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution?, + mutating func insertAndFetchWithCallbacks( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution?, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) + fetch: (StatementBase) throws -> T) throws -> (InsertionSuccess, T) { try willInsert(db) @@ -640,10 +640,10 @@ extension MutablePersistableRecord { /// is not empty, and DOES NOT run insertion callbacks. @usableFromInline func insertAndFetchWithoutCallbacks( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution?, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution?, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) + fetch: (StatementBase) throws -> T) throws -> (InsertionSuccess, T) { let conflictResolution = conflictResolution ?? type(of: self) diff --git a/GRDB/Record/MutablePersistableRecord+Save.swift b/GRDB/Record/MutablePersistableRecord+Save.swift index 1489f48e6..0a23b294a 100644 --- a/GRDB/Record/MutablePersistableRecord+Save.swift +++ b/GRDB/Record/MutablePersistableRecord+Save.swift @@ -3,11 +3,11 @@ extension MutablePersistableRecord { @inline(__always) @inlinable - public func willSave(_ db: Database) throws { } + public func willSave(_ db: DatabaseBase) throws { } @inline(__always) @inlinable - public func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + public func aroundSave(_ db: DatabaseBase, save: () throws -> PersistenceSuccess) throws { _ = try save() } @@ -34,8 +34,8 @@ extension MutablePersistableRecord { /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public mutating func save( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil) + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil) throws { try willSave(db) @@ -73,8 +73,8 @@ extension MutablePersistableRecord { /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public func saved( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil) + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil) throws -> Self { var result = self @@ -113,8 +113,8 @@ extension MutablePersistableRecord { /// thrown if the database changes fail due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed public func saveAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil) + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil) throws -> Self where Self: FetchableRecord { @@ -141,8 +141,8 @@ extension MutablePersistableRecord { /// thrown if the database changes fail due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed public mutating func saveAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, as returnedType: T.Type) throws -> T { @@ -188,11 +188,11 @@ extension MutablePersistableRecord { /// error thrown by the persistence callbacks defined by the record type. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed - public mutating func saveAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + public mutating func saveAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) + fetch: (StatementBase) throws -> T) throws -> T { GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") @@ -242,8 +242,8 @@ extension MutablePersistableRecord { @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func saveAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil) + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil) throws -> Self where Self: FetchableRecord { @@ -271,8 +271,8 @@ extension MutablePersistableRecord { @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public mutating func saveAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, as returnedType: T.Type) throws -> T { @@ -319,11 +319,11 @@ extension MutablePersistableRecord { /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ - public mutating func saveAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + public mutating func saveAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) + fetch: (StatementBase) throws -> T) throws -> T { GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") @@ -355,8 +355,8 @@ extension MutablePersistableRecord { /// update callbacks. @inlinable // allow specialization so that empty callbacks are removed mutating func updateOrInsertWithCallbacks( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution?) + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution?) throws -> PersistenceSuccess { let (saved, _) = try updateOrInsertAndFetchWithCallbacks( @@ -372,11 +372,11 @@ extension MutablePersistableRecord { /// Executes an `UPDATE` or `INSERT` statement, with `RETURNING` clause /// if `selection` is not empty, and runs insertion or update callbacks. @inlinable // allow specialization so that empty callbacks are removed - mutating func updateOrInsertAndFetchWithCallbacks( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution?, + mutating func updateOrInsertAndFetchWithCallbacks( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution?, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) + fetch: (StatementBase) throws -> T) throws -> (PersistenceSuccess, T) { // Attempt at updating if the record has a primary key @@ -404,7 +404,7 @@ extension MutablePersistableRecord { /// Return a non-nil dictionary if record has a non-null primary key @usableFromInline - func primaryKey(_ db: Database) throws -> [String: DatabaseValue]? { + func primaryKey(_ db: DatabaseBase) throws -> [String: DatabaseValue]? { let databaseTableName = type(of: self).databaseTableName let primaryKeyInfo = try db.primaryKey(databaseTableName) let container = try PersistenceContainer(db, self) diff --git a/GRDB/Record/MutablePersistableRecord+Update.swift b/GRDB/Record/MutablePersistableRecord+Update.swift index e19387070..0d06aef0c 100644 --- a/GRDB/Record/MutablePersistableRecord+Update.swift +++ b/GRDB/Record/MutablePersistableRecord+Update.swift @@ -3,11 +3,11 @@ extension MutablePersistableRecord { @inline(__always) @inlinable - public func willUpdate(_ db: Database, columns: Set) throws { } + public func willUpdate(_ db: DatabaseBase, columns: Set) throws { } @inline(__always) @inlinable - public func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + public func aroundUpdate(_ db: DatabaseBase, columns: Set, update: () throws -> PersistenceSuccess) throws { _ = try update() } @@ -42,8 +42,8 @@ extension MutablePersistableRecord { /// primary key does not match any row in the database. @inlinable // allow specialization so that empty callbacks are removed public func update( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, columns: some Collection ) throws { try willSave(db) @@ -83,8 +83,8 @@ extension MutablePersistableRecord { /// primary key does not match any row in the database. @inlinable // allow specialization so that empty callbacks are removed public func update( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, columns: some Collection ) throws { try update(db, onConflict: conflictResolution, columns: columns.map(\.name)) @@ -112,8 +112,8 @@ extension MutablePersistableRecord { /// primary key does not match any row in the database. @inlinable // allow specialization so that empty callbacks are removed public func update( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil) + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil) throws { let databaseTableName = type(of: self).databaseTableName @@ -157,8 +157,8 @@ extension MutablePersistableRecord { @discardableResult @inlinable // allow specialization so that empty callbacks are removed public func updateChanges( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, from record: Record) throws -> Bool { @@ -199,8 +199,8 @@ extension MutablePersistableRecord { @discardableResult @inlinable // allow specialization so that empty callbacks are removed public mutating func updateChanges( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, modify: (inout Self) throws -> Void) throws -> Bool { @@ -230,8 +230,8 @@ extension MutablePersistableRecord { /// thrown if the update fails due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed public func updateAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil) + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil) throws -> Self where Self: FetchableRecord { @@ -255,8 +255,8 @@ extension MutablePersistableRecord { /// thrown if the update fails due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed public func updateAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, as returnedType: T.Type) throws -> T { @@ -287,8 +287,8 @@ extension MutablePersistableRecord { /// thrown if the update fails due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed public mutating func updateChangesAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, modify: (inout Self) throws -> Void) throws -> Self? where Self: FetchableRecord @@ -317,8 +317,8 @@ extension MutablePersistableRecord { /// thrown if the update fails due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed public mutating func updateChangesAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, as returnedType: T.Type, modify: (inout Self) throws -> Void) throws -> T? @@ -367,12 +367,12 @@ extension MutablePersistableRecord { /// primary key does not match any row in the database. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed - public func updateAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + public func updateAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, columns: some Collection, selection: [any SQLSelectable], - fetch: (Statement) throws -> T + fetch: (StatementBase) throws -> T ) throws -> T { GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") @@ -426,12 +426,12 @@ extension MutablePersistableRecord { /// primary key does not match any row in the database. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed - public func updateAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + public func updateAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, columns: some Collection, selection: [any SQLSelectable], - fetch: (Statement) throws -> T + fetch: (StatementBase) throws -> T ) throws -> T { try updateAndFetch( db, onConflict: conflictResolution, @@ -467,11 +467,11 @@ extension MutablePersistableRecord { /// primary key does not match any row in the database. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed - public func updateAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + public func updateAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) + fetch: (StatementBase) throws -> T) throws -> T { let databaseTableName = type(of: self).databaseTableName @@ -503,11 +503,11 @@ extension MutablePersistableRecord { /// primary key does not match any row in the database. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed - public mutating func updateChangesAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + public mutating func updateChangesAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, selection: [any SQLSelectable], - fetch: (Statement) throws -> T, + fetch: (StatementBase) throws -> T, modify: (inout Self) throws -> Void) throws -> T? { @@ -537,8 +537,8 @@ extension MutablePersistableRecord { @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func updateAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil) + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil) throws -> Self where Self: FetchableRecord { @@ -563,8 +563,8 @@ extension MutablePersistableRecord { @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func updateAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, as returnedType: T.Type) throws -> T { @@ -596,8 +596,8 @@ extension MutablePersistableRecord { @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public mutating func updateChangesAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, modify: (inout Self) throws -> Void) throws -> Self? where Self: FetchableRecord @@ -627,8 +627,8 @@ extension MutablePersistableRecord { @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public mutating func updateChangesAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, as returnedType: T.Type, modify: (inout Self) throws -> Void) throws -> T? @@ -678,12 +678,12 @@ extension MutablePersistableRecord { /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ - public func updateAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + public func updateAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, columns: some Collection, selection: [any SQLSelectable], - fetch: (Statement) throws -> T + fetch: (StatementBase) throws -> T ) throws -> T { GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") @@ -738,12 +738,12 @@ extension MutablePersistableRecord { /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ - public func updateAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + public func updateAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, columns: some Collection, selection: [any SQLSelectable], - fetch: (Statement) throws -> T + fetch: (StatementBase) throws -> T ) throws -> T { try updateAndFetch( db, onConflict: conflictResolution, @@ -780,11 +780,11 @@ extension MutablePersistableRecord { /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ - public func updateAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + public func updateAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) + fetch: (StatementBase) throws -> T) throws -> T { let databaseTableName = type(of: self).databaseTableName @@ -817,11 +817,11 @@ extension MutablePersistableRecord { /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ - public mutating func updateChangesAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + public mutating func updateChangesAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, selection: [any SQLSelectable], - fetch: (Statement) throws -> T, + fetch: (StatementBase) throws -> T, modify: (inout Self) throws -> Void) throws -> T? { @@ -841,12 +841,12 @@ extension MutablePersistableRecord { extension MutablePersistableRecord { #if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC @inlinable // allow specialization so that empty callbacks are removed - func updateChangesAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution?, + func updateChangesAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution?, from container: PersistenceContainer, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) + fetch: (StatementBase) throws -> T) throws -> T? { let changes = try PersistenceContainer(db, self).changesIterator(from: container) @@ -863,12 +863,12 @@ extension MutablePersistableRecord { #else @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ - func updateChangesAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution?, + func updateChangesAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution?, from container: PersistenceContainer, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) + fetch: (StatementBase) throws -> T) throws -> T? { let changes = try PersistenceContainer(db, self).changesIterator(from: container) @@ -887,8 +887,8 @@ extension MutablePersistableRecord { /// Executes an `UPDATE` statement, and runs update callbacks. @inlinable // allow specialization so that empty callbacks are removed func updateWithCallbacks( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution?, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution?, columns: Set) throws -> PersistenceSuccess { @@ -906,12 +906,12 @@ extension MutablePersistableRecord { /// Executes an `UPDATE` statement, with `RETURNING` clause if `selection` /// is not empty, and runs update callbacks. @inlinable // allow specialization so that empty callbacks are removed - func updateAndFetchWithCallbacks( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution?, + func updateAndFetchWithCallbacks( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution?, columns: Set, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) + fetch: (StatementBase) throws -> T) throws -> (PersistenceSuccess, T) { try willUpdate(db, columns: columns) @@ -936,12 +936,12 @@ extension MutablePersistableRecord { /// Executes an `UPDATE` statement, with `RETURNING` clause if `selection` /// is not empty, and DOES NOT run update callbacks. @usableFromInline - func updateAndFetchWithoutCallbacks( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution?, + func updateAndFetchWithoutCallbacks( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution?, columns: Set, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) + fetch: (StatementBase) throws -> T) throws -> (PersistenceSuccess, T) { let conflictResolution = conflictResolution ?? type(of: self) @@ -970,8 +970,8 @@ extension MutablePersistableRecord { @inlinable // allow specialization so that empty callbacks are removed func updateChanges( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution?, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution?, from container: PersistenceContainer) throws -> Bool { diff --git a/GRDB/Record/MutablePersistableRecord+Upsert.swift b/GRDB/Record/MutablePersistableRecord+Upsert.swift index 8adacf3ca..448f6e08e 100644 --- a/GRDB/Record/MutablePersistableRecord+Upsert.swift +++ b/GRDB/Record/MutablePersistableRecord+Upsert.swift @@ -31,7 +31,7 @@ extension MutablePersistableRecord { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed - public mutating func upsert(_ db: Database) throws { + public mutating func upsert(_ db: DatabaseBase) throws { try willSave(db) var saved: PersistenceSuccess? @@ -127,7 +127,7 @@ extension MutablePersistableRecord { /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public mutating func upsertAndFetch( - _ db: Database, + _ db: DatabaseBase, onConflict conflictTarget: [String] = [], doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> Self @@ -154,7 +154,7 @@ extension MutablePersistableRecord { /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public mutating func upsertAndFetch( - _ db: Database, + _ db: DatabaseBase, as returnedType: T.Type, onConflict conflictTarget: [String] = [], doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) @@ -209,7 +209,7 @@ extension MutablePersistableRecord { /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ - public mutating func upsert(_ db: Database) throws { + public mutating func upsert(_ db: DatabaseBase) throws { try willSave(db) var saved: PersistenceSuccess? @@ -305,7 +305,7 @@ extension MutablePersistableRecord { @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public mutating func upsertAndFetch( - _ db: Database, + _ db: DatabaseBase, onConflict conflictTarget: [String] = [], doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> Self @@ -333,7 +333,7 @@ extension MutablePersistableRecord { @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public mutating func upsertAndFetch( - _ db: Database, + _ db: DatabaseBase, as returnedType: T.Type, onConflict conflictTarget: [String] = [], doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) @@ -364,7 +364,7 @@ extension MutablePersistableRecord { extension MutablePersistableRecord { @inlinable // allow specialization so that empty callbacks are removed - mutating func upsertWithCallbacks(_ db: Database) + mutating func upsertWithCallbacks(_ db: DatabaseBase) throws -> InsertionSuccess { let (inserted, _) = try upsertAndFetchWithCallbacks( @@ -377,7 +377,7 @@ extension MutablePersistableRecord { @inlinable // allow specialization so that empty callbacks are removed mutating func upsertAndFetchWithCallbacks( - _ db: Database, + _ db: DatabaseBase, onConflict conflictTarget: [String], doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?, selection: [any SQLSelectable], @@ -407,7 +407,7 @@ extension MutablePersistableRecord { /// insertion callbacks. @usableFromInline func upsertAndFetchWithoutCallbacks( - _ db: Database, + _ db: DatabaseBase, onConflict conflictTarget: [String], doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?, selection: [any SQLSelectable], diff --git a/GRDB/Record/MutablePersistableRecord.swift b/GRDB/Record/MutablePersistableRecord.swift index d8e5b7811..94fc30a25 100644 --- a/GRDB/Record/MutablePersistableRecord.swift +++ b/GRDB/Record/MutablePersistableRecord.swift @@ -141,7 +141,7 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// Default implementation does nothing. /// /// - parameter db: A database connection. - mutating func willInsert(_ db: Database) throws + mutating func willInsert(_ db: DatabaseBase) throws /// Persistence callback called around the record insertion. /// @@ -153,7 +153,7 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// /// ```swift /// struct Player: MutablePersistableRecord { - /// func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + /// func aroundInsert(_ db: DatabaseBase, insert: () throws -> InsertionSuccess) throws { /// print("Player will insert") /// _ = try insert() /// print("Player did insert") @@ -164,7 +164,7 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// - parameter db: A database connection. /// - parameter insert: A function that inserts the record, and returns /// information about the inserted row. - func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws + func aroundInsert(_ db: DatabaseBase, insert: () throws -> InsertionSuccess) throws /// Persistence callback called upon successful insertion. /// @@ -200,7 +200,7 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// /// - parameter db: A database connection. /// - parameter columns: The updated columns. - func willUpdate(_ db: Database, columns: Set) throws + func willUpdate(_ db: DatabaseBase, columns: Set) throws /// Persistence callback called around the record update. /// @@ -212,7 +212,7 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// /// ```swift /// struct Player: MutablePersistableRecord { - /// func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + /// func aroundUpdate(_ db: DatabaseBase, columns: Set, update: () throws -> PersistenceSuccess) throws { /// print("Player will update") /// _ = try update() /// print("Player did update") @@ -223,7 +223,7 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// - parameter columns: The updated columns. /// - parameter update: A function that updates the record. Its result is /// reserved for GRDB usage. - func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws + func aroundUpdate(_ db: DatabaseBase, columns: Set, update: () throws -> PersistenceSuccess) throws /// Persistence callback called upon successful update. /// @@ -239,7 +239,7 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// Default implementation does nothing. /// /// - parameter db: A database connection. - func willSave(_ db: Database) throws + func willSave(_ db: DatabaseBase) throws /// Persistence callback called around the record update or insertion. /// @@ -251,7 +251,7 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// /// ```swift /// struct Player: MutablePersistableRecord { - /// func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + /// func aroundSave(_ db: DatabaseBase, save: () throws -> PersistenceSuccess) throws { /// print("Player will save") /// _ = try save() /// print("Player did save") @@ -262,7 +262,7 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// - parameter db: A database connection. /// - parameter save: A function that saves the record. Its result is /// reserved for GRDB usage. - func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws + func aroundSave(_ db: DatabaseBase, save: () throws -> PersistenceSuccess) throws /// Persistence callback called upon successful update or insertion. /// @@ -278,7 +278,7 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// Default implementation does nothing. /// /// - parameter db: A database connection. - func willDelete(_ db: Database) throws + func willDelete(_ db: DatabaseBase) throws /// Persistence callback called around the destruction of the record. /// @@ -290,7 +290,7 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// /// ```swift /// struct Player: MutablePersistableRecord { - /// func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + /// func aroundDelete(_ db: DatabaseBase, delete: () throws -> Bool) throws { /// print("Player will delete") /// _ = try delete() /// print("Player did delete") @@ -301,7 +301,7 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// - parameter db: A database connection. /// - parameter delete: A function that deletes the record and returns /// whether a row was deleted in the database. - func aroundDelete(_ db: Database, delete: () throws -> Bool) throws + func aroundDelete(_ db: DatabaseBase, delete: () throws -> Bool) throws /// Persistence callback called upon successful deletion. /// @@ -340,7 +340,7 @@ extension MutablePersistableRecord { /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func exists(_ db: Database) throws -> Bool { + public func exists(_ db: DatabaseBase) throws -> Bool { guard let statement = try DAO(db, self).existsStatement() else { // Nil primary key return false @@ -357,13 +357,13 @@ extension MutablePersistableRecord { /// See public struct PersistenceConflictPolicy: Sendable { /// The conflict resolution algorithm for insertions - public let conflictResolutionForInsert: Database.ConflictResolution + public let conflictResolutionForInsert: DatabaseConflictResolution /// The conflict resolution algorithm for updates - public let conflictResolutionForUpdate: Database.ConflictResolution + public let conflictResolutionForUpdate: DatabaseConflictResolution /// Creates a policy - public init(insert: Database.ConflictResolution = .abort, update: Database.ConflictResolution = .abort) { + public init(insert: DatabaseConflictResolution = .abort, update: DatabaseConflictResolution = .abort) { self.conflictResolutionForInsert = insert self.conflictResolutionForUpdate = update } diff --git a/GRDB/Record/PersistableRecord+Insert.swift b/GRDB/Record/PersistableRecord+Insert.swift index 27e76c251..699a29039 100644 --- a/GRDB/Record/PersistableRecord+Insert.swift +++ b/GRDB/Record/PersistableRecord+Insert.swift @@ -3,7 +3,7 @@ extension PersistableRecord { @inline(__always) @inlinable - public func willInsert(_ db: Database) throws { } + public func willInsert(_ db: DatabaseBase) throws { } @inline(__always) @inlinable @@ -32,8 +32,8 @@ extension PersistableRecord { /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public func insert( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil) + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil) throws { try willSave(db) @@ -112,8 +112,8 @@ extension PersistableRecord { /// thrown if the insertion failed due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed public func insertAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, as returnedType: T.Type) throws -> T { @@ -174,11 +174,11 @@ extension PersistableRecord { /// error thrown by the persistence callbacks defined by the record type. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed - public func insertAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + public func insertAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) + fetch: (StatementBase) throws -> T) throws -> T { GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") @@ -257,10 +257,10 @@ extension PersistableRecord { /// error thrown by the persistence callbacks defined by the record type. /// - precondition: The result of `select` is not empty. @inlinable // allow specialization so that empty callbacks are removed - public func insertAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, - fetch: (Statement) throws -> T, + public func insertAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, + fetch: (StatementBase) throws -> T, select: (DatabaseComponents) throws -> [any SQLSelectable] ) throws -> T where Self: TableRecord @@ -325,8 +325,8 @@ extension PersistableRecord { @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func insertAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, as returnedType: T.Type) throws -> T { @@ -388,11 +388,11 @@ extension PersistableRecord { /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ - public func insertAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + public func insertAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) + fetch: (StatementBase) throws -> T) throws -> T { GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") @@ -472,10 +472,10 @@ extension PersistableRecord { /// - precondition: The result of `select` is not empty. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ - public func insertAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, - fetch: (Statement) throws -> T, + public func insertAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, + fetch: (StatementBase) throws -> T, select: (DatabaseComponents) throws -> [any SQLSelectable] ) throws -> T where Self: TableRecord @@ -495,8 +495,8 @@ extension PersistableRecord { /// Executes an `INSERT` statement, and runs insertion callbacks. @inlinable // allow specialization so that empty callbacks are removed func insertWithCallbacks( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution?) + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution?) throws -> InsertionSuccess { let (inserted, _) = try insertAndFetchWithCallbacks(db, onConflict: conflictResolution, selection: []) { @@ -509,11 +509,11 @@ extension PersistableRecord { /// Executes an `INSERT` statement, with `RETURNING` clause if `selection` /// is not empty, and runs insertion callbacks. @inlinable // allow specialization so that empty callbacks are removed - func insertAndFetchWithCallbacks( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution?, + func insertAndFetchWithCallbacks( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution?, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) + fetch: (StatementBase) throws -> T) throws -> (InsertionSuccess, T) { try willInsert(db) diff --git a/GRDB/Record/PersistableRecord+Save.swift b/GRDB/Record/PersistableRecord+Save.swift index c1ea9105b..04fd06c31 100644 --- a/GRDB/Record/PersistableRecord+Save.swift +++ b/GRDB/Record/PersistableRecord+Save.swift @@ -16,8 +16,8 @@ extension PersistableRecord { /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public func save( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil) + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil) throws { try willSave(db) @@ -58,8 +58,8 @@ extension PersistableRecord { /// thrown if the database changes fail due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed public func saveAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, as returnedType: T.Type) throws -> T { @@ -104,11 +104,11 @@ extension PersistableRecord { /// error thrown by the persistence callbacks defined by the record type. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed - public func saveAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + public func saveAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) + fetch: (StatementBase) throws -> T) throws -> T { GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") @@ -151,8 +151,8 @@ extension PersistableRecord { @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func saveAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, as returnedType: T.Type) throws -> T { @@ -198,11 +198,11 @@ extension PersistableRecord { /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ - public func saveAndFetch( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + public func saveAndFetch( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) + fetch: (StatementBase) throws -> T) throws -> T { GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") @@ -234,8 +234,8 @@ extension PersistableRecord { /// update callbacks. @inlinable // allow specialization so that empty callbacks are removed func updateOrInsertWithCallbacks( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution?) + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution?) throws -> PersistenceSuccess { let (saved, _) = try updateOrInsertAndFetchWithCallbacks( @@ -251,11 +251,11 @@ extension PersistableRecord { /// Executes an `UPDATE` or `INSERT` statement, with `RETURNING` clause /// if `selection` is not empty, and runs insertion or update callbacks. @inlinable // allow specialization so that empty callbacks are removed - func updateOrInsertAndFetchWithCallbacks( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution?, + func updateOrInsertAndFetchWithCallbacks( + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution?, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) + fetch: (StatementBase) throws -> T) throws -> (PersistenceSuccess, T) { // Attempt at updating if the record has a primary key diff --git a/GRDB/Record/PersistableRecord+Upsert.swift b/GRDB/Record/PersistableRecord+Upsert.swift index bbe439fdf..adef83590 100644 --- a/GRDB/Record/PersistableRecord+Upsert.swift +++ b/GRDB/Record/PersistableRecord+Upsert.swift @@ -31,7 +31,7 @@ extension PersistableRecord { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed - public func upsert(_ db: Database) throws { + public func upsert(_ db: DatabaseBase) throws { try willSave(db) var saved: PersistenceSuccess? @@ -127,7 +127,7 @@ extension PersistableRecord { /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public func upsertAndFetch( - _ db: Database, + _ db: DatabaseBase, onConflict conflictTarget: [String] = [], doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> Self @@ -154,7 +154,7 @@ extension PersistableRecord { /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed public func upsertAndFetch( - _ db: Database, + _ db: DatabaseBase, as returnedType: T.Type, onConflict conflictTarget: [String] = [], doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) @@ -209,7 +209,7 @@ extension PersistableRecord { /// error thrown by the persistence callbacks defined by the record type. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ - public func upsert(_ db: Database) throws { + public func upsert(_ db: DatabaseBase) throws { try willSave(db) var saved: PersistenceSuccess? @@ -305,7 +305,7 @@ extension PersistableRecord { @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func upsertAndFetch( - _ db: Database, + _ db: DatabaseBase, onConflict conflictTarget: [String] = [], doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> Self @@ -333,7 +333,7 @@ extension PersistableRecord { @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func upsertAndFetch( - _ db: Database, + _ db: DatabaseBase, as returnedType: T.Type, onConflict conflictTarget: [String] = [], doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) @@ -364,7 +364,7 @@ extension PersistableRecord { extension PersistableRecord { @inlinable // allow specialization so that empty callbacks are removed - func upsertWithCallbacks(_ db: Database) + func upsertWithCallbacks(_ db: DatabaseBase) throws -> InsertionSuccess { let (inserted, _) = try upsertAndFetchWithCallbacks( @@ -377,7 +377,7 @@ extension PersistableRecord { @inlinable // allow specialization so that empty callbacks are removed func upsertAndFetchWithCallbacks( - _ db: Database, + _ db: DatabaseBase, onConflict conflictTarget: [String], doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?, selection: [any SQLSelectable], diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index 05e283ba3..eae866389 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -50,7 +50,7 @@ public protocol PersistableRecord: MutablePersistableRecord { /// /// - note: If you need a mutating variant of this method, adopt the /// ``MutablePersistableRecord`` protocol instead. - func willInsert(_ db: Database) throws + func willInsert(_ db: DatabaseBase) throws /// Persistence callback called upon successful insertion. /// diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 443ddf728..4c3846934 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -231,7 +231,7 @@ open class Record { /// your implementation. /// /// - parameter db: A database connection. - open func willInsert(_ db: Database) throws { } + open func willInsert(_ db: DatabaseBase) throws { } /// Called around the record insertion. /// @@ -242,7 +242,7 @@ open class Record { /// /// ```swift /// class Player: Record { - /// func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + /// func aroundInsert(_ db: DatabaseBase, insert: () throws -> InsertionSuccess) throws { /// print("Player will insert") /// try super.aroundInsert(db, insert: insert) /// print("Player did insert") @@ -253,7 +253,7 @@ open class Record { /// - parameter db: A database connection. /// - parameter insert: A function that inserts the record, and returns /// information about the inserted row. - open func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + open func aroundInsert(_ db: DatabaseBase, insert: () throws -> InsertionSuccess) throws { let inserted = try insert() resetDatabaseChanges(with: inserted.persistenceContainer) } @@ -287,7 +287,7 @@ open class Record { /// /// - parameter db: A database connection. /// - parameter columns: The updated columns. - open func willUpdate(_ db: Database, columns: Set) throws { } + open func willUpdate(_ db: DatabaseBase, columns: Set) throws { } /// Called around the record update. /// @@ -299,7 +299,7 @@ open class Record { /// ```swift /// class Player: Record { /// override func aroundUpdate( - /// _ db: Database, + /// _ db: DatabaseBase, /// columns: Set, /// update: () throws -> PersistenceSuccess) /// throws @@ -315,7 +315,7 @@ open class Record { /// - parameter columns: The updated columns. /// - parameter update: A function that updates the record. Its result is /// reserved for GRDB usage. - open func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + open func aroundUpdate(_ db: DatabaseBase, columns: Set, update: () throws -> PersistenceSuccess) throws { let updated = try update() resetDatabaseChanges(with: updated.persistenceContainer) } @@ -334,7 +334,7 @@ open class Record { /// your implementation. /// /// - parameter db: A database connection. - open func willSave(_ db: Database) throws { } + open func willSave(_ db: DatabaseBase) throws { } /// Called around the record update or insertion. /// @@ -345,7 +345,7 @@ open class Record { /// /// ```swift /// class Player: Record { - /// override func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + /// override func aroundSave(_ db: DatabaseBase, save: () throws -> PersistenceSuccess) throws { /// print("Player will save") /// try super.aroundSave(db, save: save) /// print("Player did save") @@ -356,7 +356,7 @@ open class Record { /// - parameter db: A database connection. /// - parameter save: A function that saves the recordsave: A function that saves the record. Its result is /// reserved for GRDB usage. - open func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + open func aroundSave(_ db: DatabaseBase, save: () throws -> PersistenceSuccess) throws { _ = try save() } @@ -374,7 +374,7 @@ open class Record { /// your implementation. /// /// - parameter db: A database connection. - open func willDelete(_ db: Database) throws { } + open func willDelete(_ db: DatabaseBase) throws { } /// Called around the destruction of the record. /// @@ -385,7 +385,7 @@ open class Record { /// /// ```swift /// class Player: Record { - /// override func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + /// override func aroundDelete(_ db: DatabaseBase, delete: () throws -> Bool) throws { /// print("Player will delete") /// try super.aroundDelete(db, delete: delete) /// print("Player did delete") @@ -396,7 +396,7 @@ open class Record { /// - parameter db: A database connection. /// - parameter delete: A function that deletes the record and returns /// whether a row was deleted in the database. - open func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + open func aroundDelete(_ db: DatabaseBase, delete: () throws -> Bool) throws { _ = try delete() setHasDatabaseChanges() } @@ -423,7 +423,7 @@ open class Record { /// if the primary key does not match any row in the database and record /// could not be updated. @discardableResult - public final func updateChanges(_ db: Database) throws -> Bool { + public final func updateChanges(_ db: DatabaseBase) throws -> Bool { let changedColumns = try Set(databaseChanges.keys) if changedColumns.isEmpty { return false diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index 019b9e6fb..59137a20f 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -372,7 +372,7 @@ extension TableRecord { /// ``` /// /// - parameter db: A database connection. - public static func fetchCount(_ db: Database) throws -> Int { + public static func fetchCount(_ db: DatabaseBase) throws -> Int { try all().fetchCount(db) } } @@ -411,7 +411,7 @@ extension TableRecord { /// try PartialPlayer.numberOfSelectedColumns(db) // 2 /// } /// ``` - public static func numberOfSelectedColumns(_ db: Database) throws -> Int { + public static func numberOfSelectedColumns(_ db: DatabaseBase) throws -> Int { // The alias makes it possible to count the columns in `SELECT *`: let alias = TableAlias(tableName: databaseTableName) let context = SQLGenerationContext(db) @@ -442,7 +442,7 @@ extension TableRecord { /// - returns: The number of deleted records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult - public static func deleteAll(_ db: Database) throws -> Int { + public static func deleteAll(_ db: DatabaseBase) throws -> Int { try all().deleteAll(db) } } @@ -468,7 +468,7 @@ extension TableRecord { /// - db: A database connection. /// - key: A primary key value. /// - returns: Whether a record exists for this primary key. - public static func exists(_ db: Database, key: some DatabaseValueConvertible) throws -> Bool { + public static func exists(_ db: DatabaseBase, key: some DatabaseValueConvertible) throws -> Bool { try !filter(key: key).isEmpty(db) } } @@ -496,7 +496,7 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// - db: A database connection. /// - id: A primary key value. /// - returns: Whether a record exists for this primary key. - public static func exists(_ db: Database, id: ID) throws -> Bool { + public static func exists(_ db: DatabaseBase, id: ID) throws -> Bool { if id.databaseValue.isNull { // Don't hit the database return false @@ -533,7 +533,7 @@ extension TableRecord { /// - db: A database connection. /// - key: A key dictionary. /// - returns: Whether a record exists for this key. - public static func exists(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { + public static func exists(_ db: DatabaseBase, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { try !filter(key: key).isEmpty(db) } } @@ -565,7 +565,7 @@ extension TableRecord { /// - returns: The number of deleted records. @discardableResult public static func deleteAll( - _ db: Database, + _ db: DatabaseBase, keys: some Collection ) throws -> Int { if keys.isEmpty { @@ -598,7 +598,7 @@ extension TableRecord { /// - key: A primary key value. /// - returns: Whether a record was deleted. @discardableResult - public static func deleteOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Bool { + public static func deleteOne(_ db: DatabaseBase, key: some DatabaseValueConvertible) throws -> Bool { if key.databaseValue.isNull { // Don't hit the database return false @@ -636,7 +636,7 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// - returns: The number of deleted records. @discardableResult public static func deleteAll( - _ db: Database, + _ db: DatabaseBase, ids: some Collection ) throws -> Int { if ids.isEmpty { @@ -673,7 +673,7 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// - id: A primary key value. /// - returns: Whether a record was deleted. @discardableResult - public static func deleteOne(_ db: Database, id: ID) throws -> Bool { + public static func deleteOne(_ db: DatabaseBase, id: ID) throws -> Bool { try deleteAll(db, ids: [id]) > 0 } } @@ -712,7 +712,7 @@ extension TableRecord { /// - keys: An array of key dictionaries. /// - returns: The number of deleted records. @discardableResult - public static func deleteAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Int { + public static func deleteAll(_ db: DatabaseBase, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Int { if keys.isEmpty { // Avoid hitting the database return 0 @@ -751,7 +751,7 @@ extension TableRecord { /// - key: A key dictionary. /// - returns: Whether a record was deleted. @discardableResult - public static func deleteOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { + public static func deleteOne(_ db: DatabaseBase, key: [String: (any DatabaseValueConvertible)?]) throws -> Bool { try deleteAll(db, keys: [key]) > 0 } } @@ -785,8 +785,8 @@ extension TableRecord { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public static func updateAll( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, assignments: (DatabaseComponents) throws -> [ColumnAssignment] ) throws -> Int { try updateAll(db, onConflict: conflictResolution, assignments(databaseComponents)) @@ -817,8 +817,8 @@ extension TableRecord { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public static func updateAll( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, assignment: (DatabaseComponents) throws -> ColumnAssignment ) throws -> Int { try updateAll(db, onConflict: conflictResolution, [assignment(databaseComponents)]) @@ -845,8 +845,8 @@ extension TableRecord { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public static func updateAll( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, _ assignments: [ColumnAssignment]) throws -> Int { @@ -874,8 +874,8 @@ extension TableRecord { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. @discardableResult public static func updateAll( - _ db: Database, - onConflict conflictResolution: Database.ConflictResolution? = nil, + _ db: DatabaseBase, + onConflict conflictResolution: DatabaseConflictResolution? = nil, _ assignments: ColumnAssignment...) throws -> Int { @@ -944,7 +944,7 @@ extension TableRecord { /// /// - returns: ``RecordError/recordNotFound(databaseTableName:key:)``, or /// any error that prevented the `RecordError` from being constructed. - public static func recordNotFound(_ db: Database, key: some DatabaseValueConvertible) -> any Error { + public static func recordNotFound(_ db: DatabaseBase, key: some DatabaseValueConvertible) -> any Error { do { let column = try db.filteringPrimaryKeyColumn(databaseTableName) return RecordError.recordNotFound( @@ -969,7 +969,7 @@ extension TableRecord where Self: EncodableRecord { /// /// - returns: ``RecordError/recordNotFound(databaseTableName:key:)``, or /// any error that prevented the `RecordError` from being constructed. - public func recordNotFound(_ db: Database) -> any Error { + public func recordNotFound(_ db: DatabaseBase) -> any Error { do { let databaseTableName = type(of: self).databaseTableName let primaryKey = try db.primaryKey(databaseTableName) @@ -992,7 +992,7 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// /// - returns: ``RecordError/recordNotFound(databaseTableName:key:)``, or /// any error that prevented the `RecordError` from being constructed. - public static func recordNotFound(_ db: Database, id: Self.ID) -> any Error { + public static func recordNotFound(_ db: DatabaseBase, id: Self.ID) -> any Error { recordNotFound(db, key: id) } } diff --git a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift index d75b89c73..bca871ee1 100644 --- a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift @@ -26,6 +26,8 @@ where Reducer: ValueReducer, // // Configuration is not mutable. + typealias API = Reducer.API + /// How to schedule observed values and errors. private let scheduler: Scheduler @@ -77,23 +79,23 @@ where Reducer: ValueReducer, /// Ability to access the database private struct DatabaseAccess { /// The observed DatabasePool. - let dbPool: DatabasePool + let dbPool: DatabasePoolBase /// The fetcher that fetches database values. private let fetcher: Reducer.Fetcher - init(dbPool: DatabasePool, fetcher: Reducer.Fetcher) { + init(dbPool: DatabasePoolBase, fetcher: Reducer.Fetcher) { self.dbPool = dbPool self.fetcher = fetcher } - func fetch(_ db: Database) throws -> Reducer.Fetcher.Value { + func fetch(_ db: DatabaseBase) throws -> Reducer.Fetcher.Value { try db.isolated(readOnly: true) { try fetcher.fetch(db) } } - func fetchRecordingObservedRegion(_ db: Database) throws -> (Reducer.Fetcher.Value, DatabaseRegion) { + func fetchRecordingObservedRegion(_ db: DatabaseBase) throws -> (Reducer.Fetcher.Value, DatabaseRegion) { var region = DatabaseRegion() let fetchedValue = try db.isolated(readOnly: true) { try db.recordingSelection(®ion) { @@ -159,7 +161,7 @@ where Reducer: ValueReducer, private var reducer: Reducer init( - dbPool: DatabasePool, + dbPool: DatabasePoolBase, scheduler: Scheduler, trackingMode: ValueObservationTrackingMode, reducer: Reducer, @@ -269,7 +271,7 @@ extension ValueConcurrentObserver { return AnyDatabaseCancellable(self) } - private func startObservation(_ writerDB: Database, observedRegion: DatabaseRegion) { + private func startObservation(_ writerDB: DatabaseBase, observedRegion: DatabaseRegion) { observationState.region = observedRegion assert(observationState.isModified == false) writerDB.add(transactionObserver: self, extent: .observerLifetime) @@ -290,7 +292,7 @@ extension ValueConcurrentObserver { // We perform the initial read from a long-lived WAL snapshot // transaction, because it is a handy way to keep a read transaction // open until we grab a write access, and compare the database versions. - let initialFetchTransaction: WALSnapshotTransaction + let initialFetchTransaction: WALSnapshotTransactionBase do { initialFetchTransaction = try databaseAccess.dbPool.walSnapshotTransaction() } catch DatabaseError.SQLITE_ERROR { @@ -422,7 +424,7 @@ extension ValueConcurrentObserver { private func asyncStartObservation( from databaseAccess: DatabaseAccess, - initialFetchTransaction: WALSnapshotTransaction, + initialFetchTransaction: WALSnapshotTransactionBase, initialRegion: DatabaseRegion) { // We'll start the observation when we can access the writer @@ -710,7 +712,7 @@ extension ValueConcurrentObserver { // MARK: - Observing Database Transactions -extension ValueConcurrentObserver: TransactionObserver { +extension ValueConcurrentObserver: TransactionObserverBase { func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { if let region = observationState.region { return region.isModified(byEventsOfKind: eventKind) @@ -735,7 +737,7 @@ extension ValueConcurrentObserver: TransactionObserver { } } - func databaseDidCommit(_ writerDB: Database) { + func databaseDidCommit(_ writerDB: DatabaseBase) { // Ignore transaction unless database was modified guard observationState.isModified else { return } @@ -863,7 +865,7 @@ extension ValueConcurrentObserver: TransactionObserver { } } - func databaseDidRollback(_ db: Database) { + func databaseDidRollback(_ db: DatabaseBase) { // Reset the isModified flag until next transaction observationState.isModified = false } @@ -874,7 +876,7 @@ extension ValueConcurrentObserver: TransactionObserver { extension ValueConcurrentObserver: DatabaseCancellable { func cancel() { // Notify cancellation - let (events, dbPool): (ValueObservationEvents?, DatabasePool?) = lock.synchronized { + let (events, dbPool): (ValueObservationEvents?, DatabasePoolBase?) = lock.synchronized { let events = notificationCallbacks?.events // Set callbacks to nil so that we can't notify anything after // the cancellation. @@ -906,7 +908,7 @@ extension ValueConcurrentObserver: DatabaseCancellable { } } - private func stopDatabaseObservation(_ writerDB: Database) { + private func stopDatabaseObservation(_ writerDB: DatabaseBase) { writerDB.remove(transactionObserver: self) observationState = .notObserving lock.synchronized { diff --git a/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift b/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift index 67d915bf0..7baf3fff4 100644 --- a/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift @@ -19,14 +19,17 @@ import Foundation /// /// **Notify** is calling user callbacks, in case of database change or error. final class ValueWriteOnlyObserver: @unchecked Sendable -where Writer: DatabaseWriter, +where Writer: DatabaseWriterBase, Reducer: ValueReducer, - Scheduler: ValueObservationScheduler + Scheduler: ValueObservationScheduler, + Writer.API == Reducer.API { // MARK: - Configuration // // Configuration is not mutable. + typealias API = Writer.API + /// How to schedule observed values and errors. private let scheduler: Scheduler @@ -92,13 +95,13 @@ where Writer: DatabaseWriter, self.fetcher = fetcher } - func fetch(_ db: Database) throws -> Reducer.Fetcher.Value { + func fetch(_ db: DatabaseBase) throws -> Reducer.Fetcher.Value { try db.isolated(readOnly: readOnly) { try fetcher.fetch(db) } } - func fetchRecordingObservedRegion(_ db: Database) throws -> (Reducer.Fetcher.Value, DatabaseRegion) { + func fetchRecordingObservedRegion(_ db: DatabaseBase) throws -> (Reducer.Fetcher.Value, DatabaseRegion) { var region = DatabaseRegion() let fetchedValue = try db.isolated(readOnly: readOnly) { try db.recordingSelection(®ion) { @@ -303,7 +306,7 @@ extension ValueWriteOnlyObserver { /// By grouping the initial fetch and the beginning of observation in a /// single database access, we are sure that no concurrent write can happen /// during the initial fetch, and that we won't miss any future change. - private func fetchAndStartObservation(_ db: Database) throws -> Reducer.Fetcher.Value? { + private func fetchAndStartObservation(_ db: DatabaseBase) throws -> Reducer.Fetcher.Value? { let (events, databaseAccess) = lock.synchronized { (notificationCallbacks?.events, self.databaseAccess) } @@ -329,7 +332,7 @@ extension ValueWriteOnlyObserver { } } - private func startObservation(_ db: Database, observedRegion: DatabaseRegion) { + private func startObservation(_ db: DatabaseBase, observedRegion: DatabaseRegion) { observationState.region = observedRegion assert(observationState.isModified == false) db.add(transactionObserver: self, extent: .observerLifetime) @@ -338,7 +341,7 @@ extension ValueWriteOnlyObserver { // MARK: - Observing Database Transactions -extension ValueWriteOnlyObserver: TransactionObserver { +extension ValueWriteOnlyObserver: TransactionObserverBase { func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { if let region = observationState.region { return region.isModified(byEventsOfKind: eventKind) @@ -363,7 +366,7 @@ extension ValueWriteOnlyObserver: TransactionObserver { } } - func databaseDidCommit(_ db: Database) { + func databaseDidCommit(_ db: DatabaseBase) { // Ignore transaction unless database was modified guard observationState.isModified else { return } @@ -438,7 +441,7 @@ extension ValueWriteOnlyObserver: TransactionObserver { } } - func databaseDidRollback(_ db: Database) { + func databaseDidRollback(_ db: DatabaseBase) { // Reset the isModified flag until next transaction observationState.isModified = false } @@ -481,7 +484,7 @@ extension ValueWriteOnlyObserver: DatabaseCancellable { } } - private func stopDatabaseObservation(_ db: Database) { + private func stopDatabaseObservation(_ db: DatabaseBase) { db.remove(transactionObserver: self) observationState = .notObserving lock.synchronized { diff --git a/GRDB/ValueObservation/Reducers/Fetch.swift b/GRDB/ValueObservation/Reducers/Fetch.swift index 693c934bb..759bd0188 100644 --- a/GRDB/ValueObservation/Reducers/Fetch.swift +++ b/GRDB/ValueObservation/Reducers/Fetch.swift @@ -1,19 +1,19 @@ extension ValueReducers { /// A `ValueReducer` that perform database fetches. - public struct Fetch: ValueReducer { + public struct Fetch: ValueReducer { public struct _Fetcher: _ValueReducerFetcher { - let _fetch: @Sendable (Database) throws -> Value + let _fetch: @Sendable (DatabaseBase) throws -> Value - public func fetch(_ db: Database) throws -> Value { + public func fetch(_ db: DatabaseBase) throws -> Value { assert(db.isInsideTransaction, "Fetching in a non-isolated way is illegal") return try _fetch(db) } } - private let _fetch: @Sendable (Database) throws -> Value + private let _fetch: @Sendable (DatabaseBase) throws -> Value /// Creates a reducer which passes raw fetched values through. - init(fetch: @escaping @Sendable (Database) throws -> Value) { + init(fetch: @escaping @Sendable (DatabaseBase) throws -> Value) { self._fetch = fetch } diff --git a/GRDB/ValueObservation/Reducers/Trace.swift b/GRDB/ValueObservation/Reducers/Trace.swift index 107d80de7..871454472 100644 --- a/GRDB/ValueObservation/Reducers/Trace.swift +++ b/GRDB/ValueObservation/Reducers/Trace.swift @@ -9,7 +9,7 @@ extension ValueReducers { let base: Base.Fetcher let willFetch: @Sendable () -> Void - public func fetch(_ db: Database) throws -> Base.Fetcher.Value { + public func fetch(_ db: DatabaseBase) throws -> Base.Fetcher.Value { willFetch() return try base.fetch(db) } diff --git a/GRDB/ValueObservation/Reducers/ValueReducer.swift b/GRDB/ValueObservation/Reducers/ValueReducer.swift index 44411cbfb..74f1da4a5 100644 --- a/GRDB/ValueObservation/Reducers/ValueReducer.swift +++ b/GRDB/ValueObservation/Reducers/ValueReducer.swift @@ -11,9 +11,11 @@ // which is its `Fetcher`. /// Implementation details of `ValueReducer`. -public protocol _ValueReducer: GRDBSendableMetatype { +public protocol _ValueReducer: GRDBSendableMetatype { + associatedtype API: SQLiteAPI + /// The Sendable type that fetches database values - associatedtype Fetcher: _ValueReducerFetcher + associatedtype Fetcher: _ValueReducerFetcher /// The type of observed values associatedtype Value: Sendable @@ -38,11 +40,13 @@ public protocol _ValueReducer: GRDBSendableMetatype { mutating func _value(_ fetched: Fetcher.Value) throws -> Value? } -public protocol _ValueReducerFetcher: Sendable { +public protocol _ValueReducerFetcher: Sendable { + associatedtype API: SQLiteAPI + /// The type of fetched database values associatedtype Value - func fetch(_ db: Database) throws -> Value + func fetch(_ db: DatabaseBase) throws -> Value } /// `ValueReducer` supports ``ValueObservation``. diff --git a/GRDB/ValueObservation/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift index 0bc78496c..aee7a44d6 100644 --- a/GRDB/ValueObservation/SharedValueObservation.swift +++ b/GRDB/ValueObservation/SharedValueObservation.swift @@ -117,7 +117,7 @@ extension ValueObservation { /// - parameter extent: The extent of the shared database observation. /// - returns: A `SharedValueObservation` public func shared( - in reader: any DatabaseReader, + in reader: some DatabaseReaderBase, scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main), extent: SharedValueObservationExtent = .whileObserved) -> SharedValueObservation diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 642c2465b..29cd49457 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -5,6 +5,8 @@ import Dispatch import Foundation public struct ValueObservation: Sendable { + public typealias API = Reducer.API + var events = ValueObservationEvents() /// A boolean value indicating whether the observation requires write access @@ -120,7 +122,7 @@ extension ValueObservation: Refinable { /// fresh value. /// - returns: A DatabaseCancellable that can stop the observation. @preconcurrency public func start( - in reader: any DatabaseReader, + in reader: some DatabaseReaderBase, scheduling scheduler: some ValueObservationScheduler, onError: @escaping @Sendable (Error) -> Void, onChange: @escaping @Sendable (Reducer.Value) -> Void) @@ -180,7 +182,7 @@ extension ValueObservation: Refinable { /// fresh value. /// - returns: A DatabaseCancellable that can stop the observation. @preconcurrency @MainActor public func start( - in reader: any DatabaseReader, + in reader: some DatabaseReaderBase, scheduling scheduler: some ValueObservationMainActorScheduler = .mainActor, onError: @escaping @MainActor (Error) -> Void, onChange: @escaping @MainActor (Reducer.Value) -> Void) @@ -313,7 +315,7 @@ extension ValueObservation: Refinable { // MARK: - Fetching Values /// Fetches the initial value. - func fetchInitialValue(_ db: Database) throws -> Reducer.Value + func fetchInitialValue(_ db: DatabaseBase) throws -> Reducer.Value where Reducer: ValueReducer { var reducer = makeReducer() @@ -348,7 +350,7 @@ extension ValueObservation { /// - parameter bufferingPolicy: see the documntation /// of `AsyncThrowingStream`. public func values( - in reader: any DatabaseReader, + in reader: some DatabaseReaderBase, scheduling scheduler: some ValueObservationScheduler = .task, bufferingPolicy: AsyncValueObservation.BufferingPolicy = .unbounded) -> AsyncValueObservation @@ -483,7 +485,7 @@ extension ValueObservation { /// values are dispatched asynchronously on the main dispatch queue. /// - returns: A Combine publisher public func publisher( - in reader: any DatabaseReader, + in reader: some DatabaseReaderBase, scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main)) -> DatabasePublishers.Value where Reducer: ValueReducer @@ -646,6 +648,7 @@ extension ValueObservation { // MARK: - Creating ValueObservation +#warning("TODO: expose a version with default api") /// Creates an optimized `ValueObservation` that notifies the fetched value /// whenever it changes. /// @@ -783,16 +786,18 @@ extension ValueObservation { /// ``` /// /// - parameter fetch: The closure that fetches the observed value. - @preconcurrency public static func trackingConstantRegion( - _ fetch: @escaping @Sendable (Database) throws -> Value) + @preconcurrency public static func trackingConstantRegion( + api: API.Type, + _ fetch: @escaping @Sendable (DatabaseBase) throws -> Value) -> Self - where Reducer == ValueReducers.Fetch + where Reducer == ValueReducers.Fetch { .init( trackingMode: .constantRegionRecordedFromSelection, makeReducer: { ValueReducers.Fetch(fetch: fetch) }) } +#warning("TODO: expose a version with default api") /// Creates a `ValueObservation` that notifies the fetched value whenever /// the provided regions are modified. /// @@ -855,16 +860,18 @@ extension ValueObservation { /// - parameter otherRegions: A list of supplementary regions /// to observe. /// - parameter fetch: The closure that fetches the observed value. - @preconcurrency public static func tracking( + @preconcurrency public static func tracking( region: any DatabaseRegionConvertible, _ otherRegions: any DatabaseRegionConvertible..., - fetch: @escaping @Sendable (Database) throws -> Value) + api: API.Type, + fetch: @escaping @Sendable (DatabaseBase) throws -> Value) -> Self - where Reducer == ValueReducers.Fetch + where Reducer == ValueReducers.Fetch { - tracking(regions: [region] + otherRegions, fetch: fetch) + tracking(regions: [region] + otherRegions, api: api, fetch: fetch) } +#warning("TODO: expose a version with default api") /// Creates a `ValueObservation` that notifies the fetched value whenever /// the provided regions are modified. /// @@ -925,17 +932,19 @@ extension ValueObservation { /// /// - parameter regions: An array of observed regions. /// - parameter fetch: The closure that fetches the observed value. - @preconcurrency public static func tracking( + @preconcurrency public static func tracking( regions: [any DatabaseRegionConvertible], - fetch: @escaping @Sendable (Database) throws -> Value) + api: API.Type, + fetch: @escaping @Sendable (DatabaseBase) throws -> Value) -> Self - where Reducer == ValueReducers.Fetch + where Reducer == ValueReducers.Fetch { .init( trackingMode: .constantRegion(regions), makeReducer: { ValueReducers.Fetch(fetch: fetch) }) } +#warning("TODO: expose a version with default api") /// Creates a `ValueObservation` that notifies the fetched values whenever /// it changes. /// @@ -983,10 +992,11 @@ extension ValueObservation { /// ``` /// /// - parameter fetch: The closure that fetches the observed value. - @preconcurrency public static func tracking( - _ fetch: @escaping @Sendable (Database) throws -> Value) + @preconcurrency public static func tracking( + api: API.Type, + _ fetch: @escaping @Sendable (DatabaseBase) throws -> Value) -> Self - where Reducer == ValueReducers.Fetch + where Reducer == ValueReducers.Fetch { .init( trackingMode: .nonConstantRegionRecordedFromSelection, diff --git a/README.md b/README.md index 4261c65e8..05d07a117 100644 --- a/README.md +++ b/README.md @@ -2431,7 +2431,7 @@ Callbacks can also help implementing record validation: struct Link: PersistableRecord { var url: URL - func willSave(_ db: Database) throws { + func willSave(_ db: DatabaseBase) throws { if url.host == nil { throw ValidationError("url must be absolute.") } @@ -2483,7 +2483,7 @@ In the `MutablePersistableRecord` protocol, `willInsert` and `didInsert` are mut > struct PictureFile: PersistableRecord { > var path: String > -> func willDelete(_ db: Database) { +> func willDelete(_ db: DatabaseBase) { > db.afterNextTransaction { _ in > try? deleteFileOnDisk() > } diff --git a/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift b/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift index baefd0dcd..9a7549a1d 100644 --- a/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift @@ -8,7 +8,7 @@ private struct Player: Codable, FetchableRecord, PersistableRecord { var name: String var score: Int? - static func createTable(_ db: Database) throws { + static func createTable(_ db: DatabaseBase) throws { try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() diff --git a/Tests/GRDBCombineTests/DatabaseRegionObservationPublisherTests.swift b/Tests/GRDBCombineTests/DatabaseRegionObservationPublisherTests.swift index a83adfa02..a6c94a278 100644 --- a/Tests/GRDBCombineTests/DatabaseRegionObservationPublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseRegionObservationPublisherTests.swift @@ -8,7 +8,7 @@ private struct Player: Codable, FetchableRecord, PersistableRecord { var name: String var score: Int? - static func createTable(_ db: Database) throws { + static func createTable(_ db: DatabaseBase) throws { try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() diff --git a/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift b/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift index 7d1b2d0a5..e7951f35e 100644 --- a/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift @@ -8,7 +8,7 @@ private struct Player: Codable, FetchableRecord, PersistableRecord { var name: String var score: Int? - static func createTable(_ db: Database) throws { + static func createTable(_ db: DatabaseBase) throws { try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() diff --git a/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift b/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift index 0849a0085..63c441b11 100644 --- a/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift +++ b/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift @@ -8,7 +8,7 @@ private struct Player: Codable, FetchableRecord, PersistableRecord { var name: String var score: Int? - static func createTable(_ db: Database) throws { + static func createTable(_ db: DatabaseBase) throws { try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() diff --git a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift index b7d737d18..00ed729e4 100644 --- a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift @@ -2364,7 +2364,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase { // View with custom primary key. // Existence check is performed on the primary key. struct SchemaSource: DatabaseSchemaSource { - func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + func columnsForPrimaryKey(_ db: DatabaseBase, inView view: DatabaseObjectID) throws -> [String]? { ["id"] } } diff --git a/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift b/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift index 816e8beac..9f60cd592 100644 --- a/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift +++ b/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift @@ -166,7 +166,7 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase { } private func testHasManyWithTwoSteps( - _ db: Database, + _ db: DatabaseBase, ab: BAssociation, ac: CAssociation, bCondition: String, @@ -609,7 +609,7 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase { } private func testHasManyWithThreeSteps( - _ db: Database, + _ db: DatabaseBase, bs: BsAssociation, cs: CsAssociation, dsThroughCs: DsCsAssociation, diff --git a/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift b/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift index a9521cc5c..9e828df47 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift @@ -168,7 +168,7 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { } private func testHasOneWithTwoSteps( - _ db: Database, + _ db: DatabaseBase, ab: BAssociation, ac: CAssociation, bCondition: String, @@ -867,7 +867,7 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { } private func testHasOneWithThreeSteps( - _ db: Database, + _ db: DatabaseBase, b: BAssociation, c: CAssociation, dThroughC: DCAssociation, diff --git a/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift b/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift index b97580fbe..6ada49544 100644 --- a/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingObservationTests.swift @@ -10,7 +10,7 @@ private struct CompoundPrimaryKeyChild: TableRecord { } class AssociationPrefetchingObservationTests: GRDBTestCase { private func assertRequestRegionEqual( - _ db: Database, + _ db: DatabaseBase, _ request: QueryInterfaceRequest, _ expectedDescriptions: String..., file: StaticString = #file, line: UInt = #line) throws diff --git a/Tests/GRDBTests/AssociationPrefetchingRowTests.swift b/Tests/GRDBTests/AssociationPrefetchingRowTests.swift index c6fd39bd8..77c83d7b3 100644 --- a/Tests/GRDBTests/AssociationPrefetchingRowTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingRowTests.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import XCTest import GRDB diff --git a/Tests/GRDBTests/ColumnInfoTests.swift b/Tests/GRDBTests/ColumnInfoTests.swift index 3951b81a1..390681b00 100644 --- a/Tests/GRDBTests/ColumnInfoTests.swift +++ b/Tests/GRDBTests/ColumnInfoTests.swift @@ -275,8 +275,8 @@ class ColumnInfoTests: GRDBTestCase { class Observer: TransactionObserver { func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true } func databaseDidChange(with event: DatabaseEvent) { } - func databaseDidCommit(_ db: Database) { } - func databaseDidRollback(_ db: Database) { } + func databaseDidCommit(_ db: DatabaseBase) { } + func databaseDidRollback(_ db: DatabaseBase) { } } let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: Observer(), extent: .databaseLifetime) diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index 183fd89ed..e6d7d92b7 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -118,19 +118,19 @@ private struct UserFetchableRecord3 : FetchableRecord { // MARK: - StatementColumnConvertible private struct UserStatementColumnConvertible1 : StatementColumnConvertible { - init?(sqliteStatement: SQLiteStatement, index: CInt) { } + init?(sqliteStatement: SQLiteStatementBase, index: CInt) { } } private struct UserStatementColumnConvertible2 : StatementColumnConvertible { - init(sqliteStatement: SQLiteStatement, index: CInt) { } + init(sqliteStatement: SQLiteStatementBase, index: CInt) { } } private class UserStatementColumnConvertible3 : StatementColumnConvertible { - required init?(sqliteStatement: SQLiteStatement, index: CInt) { } + required init?(sqliteStatement: SQLiteStatementBase, index: CInt) { } } private class UserStatementColumnConvertible4 : StatementColumnConvertible { - required init(sqliteStatement: SQLiteStatement, index: CInt) { } + required init(sqliteStatement: SQLiteStatementBase, index: CInt) { } } // MARK: - TableRecord @@ -148,8 +148,8 @@ private class UserTableRecord2 : TableRecord { private class UserTransactionObserver : TransactionObserver { func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false } func databaseDidChange(with event: DatabaseEvent) { } - func databaseDidCommit(_ db: Database) { } - func databaseDidRollback(_ db: Database) { } + func databaseDidCommit(_ db: DatabaseBase) { } + func databaseDidRollback(_ db: DatabaseBase) { } } // MARK: - VirtualTableModule @@ -159,7 +159,7 @@ private struct UserVirtualTableModule1 : VirtualTableModule { let moduleName = "UserVirtualTableModule1" func makeTableDefinition(configuration: VirtualTableConfiguration) -> CustomTableDefinition { preconditionFailure() } func moduleArguments(for definition: CustomTableDefinition, in db: Database) throws -> [String] { preconditionFailure() } - func database(_ db: Database, didCreate tableName: String, using definition: CustomTableDefinition) throws { } + func database(_ db: DatabaseBase, didCreate tableName: String, using definition: CustomTableDefinition) throws { } } private class UserVirtualTableModule2 : VirtualTableModule { @@ -167,5 +167,5 @@ private class UserVirtualTableModule2 : VirtualTableModule { let moduleName = "UserVirtualTableModule2" func makeTableDefinition(configuration: VirtualTableConfiguration) -> CustomTableDefinition { preconditionFailure() } func moduleArguments(for definition: CustomTableDefinition, in db: Database) throws -> [String] { preconditionFailure() } - func database(_ db: Database, didCreate tableName: String, using definition: CustomTableDefinition) throws { } + func database(_ db: DatabaseBase, didCreate tableName: String, using definition: CustomTableDefinition) throws { } } diff --git a/Tests/GRDBTests/CompilationSubClassTests.swift b/Tests/GRDBTests/CompilationSubClassTests.swift index 4dfe564dc..5dab69ad6 100644 --- a/Tests/GRDBTests/CompilationSubClassTests.swift +++ b/Tests/GRDBTests/CompilationSubClassTests.swift @@ -13,11 +13,11 @@ private class UserRecord : Record { override class var databaseSelection: [any SQLSelectable] { super.databaseSelection } override func encode(to container: inout PersistenceContainer) throws { try super.encode(to: &container) } - override func willInsert(_ db: Database) throws { + override func willInsert(_ db: DatabaseBase) throws { try super.willInsert(db) } - override func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + override func aroundInsert(_ db: DatabaseBase, insert: () throws -> InsertionSuccess) throws { try super.aroundInsert(db, insert: insert) } @@ -25,11 +25,11 @@ private class UserRecord : Record { super.didInsert(inserted) } - override func willUpdate(_ db: Database, columns: Set) throws { + override func willUpdate(_ db: DatabaseBase, columns: Set) throws { try super.willUpdate(db, columns: columns) } - override func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + override func aroundUpdate(_ db: DatabaseBase, columns: Set, update: () throws -> PersistenceSuccess) throws { try super.aroundUpdate(db, columns: columns, update: update) } @@ -37,11 +37,11 @@ private class UserRecord : Record { super.didUpdate(updated) } - override func willSave(_ db: Database) throws { + override func willSave(_ db: DatabaseBase) throws { try super.willSave(db) } - override func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + override func aroundSave(_ db: DatabaseBase, save: () throws -> PersistenceSuccess) throws { try super.aroundSave(db, save: save) } @@ -49,11 +49,11 @@ private class UserRecord : Record { super.didSave(saved) } - override func willDelete(_ db: Database) throws { + override func willDelete(_ db: DatabaseBase) throws { try super.willDelete(db) } - override func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + override func aroundDelete(_ db: DatabaseBase, delete: () throws -> Bool) throws { try super.aroundDelete(db, delete: delete) } diff --git a/Tests/GRDBTests/DataMemoryTests.swift b/Tests/GRDBTests/DataMemoryTests.swift index 1187ed250..aa0992c10 100644 --- a/Tests/GRDBTests/DataMemoryTests.swift +++ b/Tests/GRDBTests/DataMemoryTests.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import XCTest @testable import GRDB diff --git a/Tests/GRDBTests/DatabaseCursorTests.swift b/Tests/GRDBTests/DatabaseCursorTests.swift index 6b43570b4..131d6a7e8 100644 --- a/Tests/GRDBTests/DatabaseCursorTests.swift +++ b/Tests/GRDBTests/DatabaseCursorTests.swift @@ -214,7 +214,7 @@ class DatabaseCursorTests: GRDBTestCase { // This test passes if it compiles func testAssociatedType() throws { func accept(_ cursor: some DatabaseCursor) { } - func useCursor(_ db: Database) throws { + func useCursor(_ db: DatabaseBase) throws { let cursor = try String.fetchCursor(db, sql: "SELECT 'foo'") accept(cursor) } diff --git a/Tests/GRDBTests/DatabaseDataDecodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDataDecodingStrategyTests.swift index a071683cc..ca94a1acd 100644 --- a/Tests/GRDBTests/DatabaseDataDecodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDataDecodingStrategyTests.swift @@ -38,7 +38,7 @@ private struct RecordWithOptionalData: FetchableReco class DatabaseDataDecodingStrategyTests: GRDBTestCase { /// test the conversion from a database value to a data extracted from a record private func test( - _ db: Database, + _ db: DatabaseBase, record: T.Type, data: (T) -> Data?, databaseValue: (any DatabaseValueConvertible)?, @@ -59,7 +59,7 @@ class DatabaseDataDecodingStrategyTests: GRDBTestCase { /// test the conversion from a database value to a data with a given strategy private func test( - _ db: Database, + _ db: DatabaseBase, strategy: Strategy.Type, databaseValue: some DatabaseValueConvertible, _ test: (Data) -> Void) @@ -69,7 +69,7 @@ class DatabaseDataDecodingStrategyTests: GRDBTestCase { try self.test(db, record: RecordWithOptionalData.self, data: { $0.data }, databaseValue: databaseValue, with: { test($0!) }) } - private func testNullDecoding(_ db: Database, strategy: Strategy.Type) throws { + private func testNullDecoding(_ db: DatabaseBase, strategy: Strategy.Type) throws { try self.test(db, record: RecordWithOptionalData.self, data: { $0.data }, databaseValue: nil) { data in XCTAssertNil(data) } diff --git a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift index a95dd9156..23f90dc09 100644 --- a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift @@ -65,7 +65,7 @@ private struct RecordWithOptionalDate: FetchableReco class DatabaseDateDecodingStrategyTests: GRDBTestCase { /// test the conversion from a database value to a date extracted from a record private func test( - _ db: Database, + _ db: DatabaseBase, record: T.Type, date: (T) -> Date?, databaseValue: (any DatabaseValueConvertible)?, @@ -86,7 +86,7 @@ class DatabaseDateDecodingStrategyTests: GRDBTestCase { /// test the conversion from a database value to a date with a given strategy private func test( - _ db: Database, + _ db: DatabaseBase, strategy: Strategy.Type, databaseValue: some DatabaseValueConvertible, _ test: (Date) -> Void) @@ -96,7 +96,7 @@ class DatabaseDateDecodingStrategyTests: GRDBTestCase { try self.test(db, record: RecordWithOptionalDate.self, date: { $0.date }, databaseValue: databaseValue, with: { test($0!) }) } - private func testNullDecoding(_ db: Database, strategy: Strategy.Type) throws { + private func testNullDecoding(_ db: DatabaseBase, strategy: Strategy.Type) throws { try self.test(db, record: RecordWithOptionalDate.self, date: { $0.date }, databaseValue: nil) { date in XCTAssertNil(date) } diff --git a/Tests/GRDBTests/DatabaseDumpTests.swift b/Tests/GRDBTests/DatabaseDumpTests.swift index 8a654f85a..e32157dc6 100644 --- a/Tests/GRDBTests/DatabaseDumpTests.swift +++ b/Tests/GRDBTests/DatabaseDumpTests.swift @@ -1148,7 +1148,7 @@ final class DatabaseDumpTests: GRDBTestCase { func test_dumpTables_single_view_with_schema_source() throws { struct SchemaSource: DatabaseSchemaSource { - func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + func columnsForPrimaryKey(_ db: DatabaseBase, inView view: DatabaseObjectID) throws -> [String]? { ["teamId", "name"] } } diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index da0922508..8db704918 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -1112,7 +1112,7 @@ class DatabaseMigratorTests : GRDBTestCase { func test_schemaSource_is_disabled_during_migrations() throws { struct SchemaSource: DatabaseSchemaSource { - func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + func columnsForPrimaryKey(_ db: DatabaseBase, inView view: DatabaseObjectID) throws -> [String]? { ["id"] } } @@ -1149,7 +1149,7 @@ class DatabaseMigratorTests : GRDBTestCase { func test_schemaSource_can_be_restored_during_migrations() throws { struct SchemaSource: DatabaseSchemaSource { - func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + func columnsForPrimaryKey(_ db: DatabaseBase, inView view: DatabaseObjectID) throws -> [String]? { ["id"] } } diff --git a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift index 7302e2aa4..784690d2c 100644 --- a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift +++ b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import XCTest @testable import GRDB diff --git a/Tests/GRDBTests/DatabasePoolTests.swift b/Tests/GRDBTests/DatabasePoolTests.swift index f8192e58f..a73d0337c 100644 --- a/Tests/GRDBTests/DatabasePoolTests.swift +++ b/Tests/GRDBTests/DatabasePoolTests.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import XCTest import GRDB diff --git a/Tests/GRDBTests/DatabaseSavepointTests.swift b/Tests/GRDBTests/DatabaseSavepointTests.swift index b2fe86d25..c74c67b23 100644 --- a/Tests/GRDBTests/DatabaseSavepointTests.swift +++ b/Tests/GRDBTests/DatabaseSavepointTests.swift @@ -1,7 +1,7 @@ import XCTest import GRDB -func insertItem(_ db: Database, name: String) throws { +func insertItem(_ db: DatabaseBase, name: String) throws { try db.execute(sql: "INSERT INTO items (name) VALUES (?)", arguments: [name]) } @@ -34,10 +34,10 @@ private class Observer : TransactionObserver { allRecordedEvents.append(event.copy()) } - func databaseDidCommit(_ db: Database) { + func databaseDidCommit(_ db: DatabaseBase) { } - func databaseDidRollback(_ db: Database) { + func databaseDidRollback(_ db: DatabaseBase) { } } diff --git a/Tests/GRDBTests/DatabaseSchemaSourceTests.swift b/Tests/GRDBTests/DatabaseSchemaSourceTests.swift index 16dd0d781..28ecd48ae 100644 --- a/Tests/GRDBTests/DatabaseSchemaSourceTests.swift +++ b/Tests/GRDBTests/DatabaseSchemaSourceTests.swift @@ -4,7 +4,7 @@ import GRDB class DatabaseSchemaSourceTests: GRDBTestCase { func test_schemaSource_can_query_schema() throws { struct SchemaSource: DatabaseSchemaSource { - func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + func columnsForPrimaryKey(_ db: DatabaseBase, inView view: DatabaseObjectID) throws -> [String]? { let tableName = view.name + "_table" if try db.tableExists(view.name + "_table"), try db.primaryKey(tableName).columns == ["id"], @@ -46,7 +46,7 @@ class DatabaseSchemaSourceTests: GRDBTestCase { func test_then_with_columnsForPrimaryKey_inView() throws { struct SchemaSource1: DatabaseSchemaSource { - func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + func columnsForPrimaryKey(_ db: DatabaseBase, inView view: DatabaseObjectID) throws -> [String]? { switch view.name { case "view1": ["code"] case "view2": ["id"] @@ -56,7 +56,7 @@ class DatabaseSchemaSourceTests: GRDBTestCase { } struct SchemaSource2: DatabaseSchemaSource { - func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + func columnsForPrimaryKey(_ db: DatabaseBase, inView view: DatabaseObjectID) throws -> [String]? { switch view.name { case "view1": ["identifier"] case "view3": ["uuid"] @@ -65,7 +65,7 @@ class DatabaseSchemaSourceTests: GRDBTestCase { } } - func setupSchema(_ db: Database) throws { + func setupSchema(_ db: DatabaseBase) throws { try db.execute(sql: """ CREATE VIEW view1 AS SELECT 'foo' AS code, 'whatever' AS identifier; CREATE VIEW view2 AS SELECT 1 AS id; diff --git a/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift index 54305e5c3..aab874e04 100644 --- a/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift @@ -12,11 +12,11 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { } } - func increment(_ db: Database) throws { + func increment(_ db: DatabaseBase) throws { try db.execute(sql: "INSERT INTO counter DEFAULT VALUES") } - func value(_ db: Database) throws -> Int { + func value(_ db: DatabaseBase) throws -> Int { try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM counter")! } } diff --git a/Tests/GRDBTests/DatabaseSnapshotTests.swift b/Tests/GRDBTests/DatabaseSnapshotTests.swift index 1cb422ecd..74176c885 100644 --- a/Tests/GRDBTests/DatabaseSnapshotTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotTests.swift @@ -10,11 +10,11 @@ class DatabaseSnapshotTests: GRDBTestCase { } } - func increment(_ db: Database) throws { + func increment(_ db: DatabaseBase) throws { try db.execute(sql: "INSERT INTO counter DEFAULT VALUES") } - func value(_ db: Database) throws -> Int { + func value(_ db: DatabaseBase) throws -> Int { try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM counter")! } } @@ -83,10 +83,10 @@ class DatabaseSnapshotTests: GRDBTestCase { func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false } func databaseDidChange(with event: DatabaseEvent) { } - func databaseDidCommit(_ db: Database) { + func databaseDidCommit(_ db: DatabaseBase) { snapshot = try! dbPool.makeSnapshot() } - func databaseDidRollback(_ db: Database) { } + func databaseDidRollback(_ db: DatabaseBase) { } } let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) diff --git a/Tests/GRDBTests/DatabaseValueConversionTests.swift b/Tests/GRDBTests/DatabaseValueConversionTests.swift index 7ea09e374..06cba0bae 100644 --- a/Tests/GRDBTests/DatabaseValueConversionTests.swift +++ b/Tests/GRDBTests/DatabaseValueConversionTests.swift @@ -32,7 +32,7 @@ private let jpegData = try! Data(contentsOf: testBundle.url(forResource: "Betty" class DatabaseValueConversionTests : GRDBTestCase { private func assertDecoding( - _ db: Database, + _ db: DatabaseBase, _ sql: String, _ type: T.Type, expectedSQLiteConversion: T?, @@ -84,7 +84,7 @@ class DatabaseValueConversionTests : GRDBTestCase { } private func assertFailedDecoding( - _ db: Database, + _ db: DatabaseBase, _ sql: String, _ type: T.Type, file: StaticString = #file, diff --git a/Tests/GRDBTests/FTS3TokenizerTests.swift b/Tests/GRDBTests/FTS3TokenizerTests.swift index 67bc4d52f..03208e687 100644 --- a/Tests/GRDBTests/FTS3TokenizerTests.swift +++ b/Tests/GRDBTests/FTS3TokenizerTests.swift @@ -3,7 +3,7 @@ import GRDB class FTS3TokenizerTests: GRDBTestCase { - private func match(_ db: Database, _ content: String, _ query: String) -> Bool { + private func match(_ db: DatabaseBase, _ content: String, _ query: String) -> Bool { try! db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: [content]) defer { try! db.execute(sql: "DELETE FROM documents") diff --git a/Tests/GRDBTests/FTS5TokenizerTests.swift b/Tests/GRDBTests/FTS5TokenizerTests.swift index 044384914..14a649840 100644 --- a/Tests/GRDBTests/FTS5TokenizerTests.swift +++ b/Tests/GRDBTests/FTS5TokenizerTests.swift @@ -4,7 +4,7 @@ import GRDB class FTS5TokenizerTests: GRDBTestCase { - private func match(_ db: Database, _ content: String, _ query: String) -> Bool { + private func match(_ db: DatabaseBase, _ content: String, _ query: String) -> Bool { try! db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: [content]) defer { try! db.execute(sql: "DELETE FROM documents") diff --git a/Tests/GRDBTests/FoundationDateTests.swift b/Tests/GRDBTests/FoundationDateTests.swift index 024ef4395..c0cd1e5a1 100644 --- a/Tests/GRDBTests/FoundationDateTests.swift +++ b/Tests/GRDBTests/FoundationDateTests.swift @@ -323,7 +323,7 @@ class FoundationDateTests : GRDBTestCase { } func assert( - _ db: Database, + _ db: DatabaseBase, _ expression: SQLExpression, equal expectedDate: Date, file: StaticString = #file, @@ -372,7 +372,7 @@ class FoundationDateTests : GRDBTestCase { } func assert( - _ db: Database, + _ db: DatabaseBase, _ expression: SQLExpression, equal expectedDate: String, file: StaticString = #file, diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index af1df612b..323b74ec7 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import Foundation import XCTest @@ -171,7 +171,7 @@ class GRDBTestCase: XCTestCase { // Compare SQL strings (ignoring leading and trailing white space and semicolons. func assertEqualSQL( - _ db: Database, + _ db: DatabaseBase, _ request: some FetchRequest, _ sql: String, file: StaticString = #file, @@ -184,7 +184,7 @@ class GRDBTestCase: XCTestCase { // Compare SQL strings. func assertEqualSQL( - _ db: Database, + _ db: DatabaseBase, _ expression: some SQLExpressible, _ sql: String, file: StaticString = #file, @@ -229,12 +229,12 @@ let testBundle = Bundle(for: GRDBTestCase.self) extension FetchRequest { /// Turn request into a statement - func makeStatement(_ db: Database) throws -> Statement { + func makeStatement(_ db: DatabaseBase) throws -> Statement { try makePreparedRequest(db, forSingleResult: false).statement } /// Turn request into SQL and arguments - func build(_ db: Database) throws -> (sql: String, arguments: StatementArguments) { + func build(_ db: DatabaseBase) throws -> (sql: String, arguments: StatementArguments) { let statement = try makePreparedRequest(db, forSingleResult: false).statement return (sql: statement.sql, arguments: statement.arguments) } @@ -242,11 +242,11 @@ extension FetchRequest { /// A type-erased ValueReducer. struct AnyValueReducer: ValueReducer { - private var __fetch: @Sendable (Database) throws -> Fetched + private var __fetch: @Sendable (DatabaseBase) throws -> Fetched private var __value: (Fetched) -> Value? init( - fetch: @escaping @Sendable (Database) throws -> Fetched, + fetch: @escaping @Sendable (DatabaseBase) throws -> Fetched, value: @escaping (Fetched) -> Value?) { self.__fetch = fetch @@ -264,13 +264,13 @@ struct AnyValueReducer: ValueReducer { /// A type-erased _ValueReducerFetcher. struct AnyValueReducerFetcher: _ValueReducerFetcher { - private var _fetch: @Sendable (Database) throws -> Fetched + private var _fetch: @Sendable (DatabaseBase) throws -> Fetched - init(fetch: @escaping @Sendable (Database) throws -> Fetched) { + init(fetch: @escaping @Sendable (DatabaseBase) throws -> Fetched) { self._fetch = fetch } - func fetch(_ db: Database) throws -> Fetched { + func fetch(_ db: DatabaseBase) throws -> Fetched { try _fetch(db) } } diff --git a/Tests/GRDBTests/IndexInfoTests.swift b/Tests/GRDBTests/IndexInfoTests.swift index 9ebec7dd8..ec88a1a50 100644 --- a/Tests/GRDBTests/IndexInfoTests.swift +++ b/Tests/GRDBTests/IndexInfoTests.swift @@ -84,7 +84,7 @@ class IndexInfoTests: GRDBTestCase { func testColumnsThatUniquelyIdentityRows_with_view_and_schema_source() throws { struct MySchemaSource: DatabaseSchemaSource { - func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + func columnsForPrimaryKey(_ db: DatabaseBase, inView view: DatabaseObjectID) throws -> [String]? { ["id"] } } diff --git a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift index e3a348503..a351d1bf2 100644 --- a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift @@ -16,7 +16,7 @@ private struct Player: FetchableRecord, MutablePersistableRecord, Codable { self.creationDate = creationDate } - mutating func willInsert(_ db: Database) throws { + mutating func willInsert(_ db: DatabaseBase) throws { if creationDate == nil { creationDate = Date() } diff --git a/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift b/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift index 5ebae5d26..69b29a231 100644 --- a/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift @@ -185,12 +185,12 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { transactionEvents.append(event.copy()) } - func databaseDidCommit(_ db: Database) { + func databaseDidCommit(_ db: DatabaseBase) { events = transactionEvents transactionEvents = [] } - func databaseDidRollback(_ db: Database) { + func databaseDidRollback(_ db: DatabaseBase) { events = [] transactionEvents = [] } diff --git a/Tests/GRDBTests/MutablePersistableRecordTests.swift b/Tests/GRDBTests/MutablePersistableRecordTests.swift index 5e5fd6f6e..3e92b8f2a 100644 --- a/Tests/GRDBTests/MutablePersistableRecordTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordTests.swift @@ -15,7 +15,7 @@ private struct MutablePersistableRecordPerson : MutablePersistableRecord { container["aGe"] = age } - func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + func aroundInsert(_ db: DatabaseBase, insert: () throws -> InsertionSuccess) throws { let inserted = try insert() XCTAssertNotNil(inserted.rowID) XCTAssertEqual(inserted.rowIDColumn, "id") @@ -84,13 +84,13 @@ private struct MutablePersistableRecordCustomizedCountry : MutablePersistableRec container["name"] = name } - mutating func willInsert(_ db: Database) throws { + mutating func willInsert(_ db: DatabaseBase) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") callbacks.willInsertCount += 1 } - func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + func aroundInsert(_ db: DatabaseBase, insert: () throws -> InsertionSuccess) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") @@ -104,13 +104,13 @@ private struct MutablePersistableRecordCustomizedCountry : MutablePersistableRec rowID = inserted.rowID } - func willUpdate(_ db: Database, columns: Set) throws { + func willUpdate(_ db: DatabaseBase, columns: Set) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") callbacks.willUpdateCount += 1 } - func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + func aroundUpdate(_ db: DatabaseBase, columns: Set, update: () throws -> PersistenceSuccess) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") @@ -123,13 +123,13 @@ private struct MutablePersistableRecordCustomizedCountry : MutablePersistableRec callbacks.didUpdateCount += 1 } - func willSave(_ db: Database) throws { + func willSave(_ db: DatabaseBase) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") callbacks.willSaveCount += 1 } - func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + func aroundSave(_ db: DatabaseBase, save: () throws -> PersistenceSuccess) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") @@ -142,13 +142,13 @@ private struct MutablePersistableRecordCustomizedCountry : MutablePersistableRec callbacks.didSaveCount += 1 } - func willDelete(_ db: Database) throws { + func willDelete(_ db: DatabaseBase) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") callbacks.willDeleteCount += 1 } - func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + func aroundDelete(_ db: DatabaseBase, delete: () throws -> Bool) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") @@ -174,11 +174,11 @@ private struct PartialPlayer: Codable, MutablePersistableRecord, FetchableRecord typealias Columns = FullPlayer.Columns - mutating func willInsert(_ db: Database) throws { + mutating func willInsert(_ db: DatabaseBase) throws { callbacks.willInsertCount += 1 } - func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + func aroundInsert(_ db: DatabaseBase, insert: () throws -> InsertionSuccess) throws { callbacks.aroundInsertEnterCount += 1 _ = try insert() callbacks.aroundInsertExitCount += 1 @@ -189,11 +189,11 @@ private struct PartialPlayer: Codable, MutablePersistableRecord, FetchableRecord callbacks.didInsertCount += 1 } - func willUpdate(_ db: Database, columns: Set) throws { + func willUpdate(_ db: DatabaseBase, columns: Set) throws { callbacks.willUpdateCount += 1 } - func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + func aroundUpdate(_ db: DatabaseBase, columns: Set, update: () throws -> PersistenceSuccess) throws { callbacks.aroundUpdateEnterCount += 1 _ = try update() callbacks.aroundUpdateExitCount += 1 @@ -203,11 +203,11 @@ private struct PartialPlayer: Codable, MutablePersistableRecord, FetchableRecord callbacks.didUpdateCount += 1 } - func willSave(_ db: Database) throws { + func willSave(_ db: DatabaseBase) throws { callbacks.willSaveCount += 1 } - func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + func aroundSave(_ db: DatabaseBase, save: () throws -> PersistenceSuccess) throws { callbacks.aroundSaveEnterCount += 1 _ = try save() callbacks.aroundSaveExitCount += 1 @@ -217,11 +217,11 @@ private struct PartialPlayer: Codable, MutablePersistableRecord, FetchableRecord callbacks.didSaveCount += 1 } - func willDelete(_ db: Database) throws { + func willDelete(_ db: DatabaseBase) throws { callbacks.willDeleteCount += 1 } - func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + func aroundDelete(_ db: DatabaseBase, delete: () throws -> Bool) throws { callbacks.aroundDeleteEnterCount += 1 _ = try delete() callbacks.aroundDeleteExitCount += 1 @@ -250,11 +250,11 @@ private struct FullPlayer: Codable, MutablePersistableRecord, FetchableRecord { let callbacks = Callbacks() - mutating func willInsert(_ db: Database) throws { + mutating func willInsert(_ db: DatabaseBase) throws { callbacks.willInsertCount += 1 } - func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + func aroundInsert(_ db: DatabaseBase, insert: () throws -> InsertionSuccess) throws { callbacks.aroundInsertEnterCount += 1 _ = try insert() callbacks.aroundInsertExitCount += 1 @@ -265,11 +265,11 @@ private struct FullPlayer: Codable, MutablePersistableRecord, FetchableRecord { callbacks.didInsertCount += 1 } - func willUpdate(_ db: Database, columns: Set) throws { + func willUpdate(_ db: DatabaseBase, columns: Set) throws { callbacks.willUpdateCount += 1 } - func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + func aroundUpdate(_ db: DatabaseBase, columns: Set, update: () throws -> PersistenceSuccess) throws { callbacks.aroundUpdateEnterCount += 1 _ = try update() callbacks.aroundUpdateExitCount += 1 @@ -279,11 +279,11 @@ private struct FullPlayer: Codable, MutablePersistableRecord, FetchableRecord { callbacks.didUpdateCount += 1 } - func willSave(_ db: Database) throws { + func willSave(_ db: DatabaseBase) throws { callbacks.willSaveCount += 1 } - func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + func aroundSave(_ db: DatabaseBase, save: () throws -> PersistenceSuccess) throws { callbacks.aroundSaveEnterCount += 1 _ = try save() callbacks.aroundSaveExitCount += 1 @@ -293,11 +293,11 @@ private struct FullPlayer: Codable, MutablePersistableRecord, FetchableRecord { callbacks.didSaveCount += 1 } - func willDelete(_ db: Database) throws { + func willDelete(_ db: DatabaseBase) throws { callbacks.willDeleteCount += 1 } - func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + func aroundDelete(_ db: DatabaseBase, delete: () throws -> Bool) throws { callbacks.aroundDeleteEnterCount += 1 _ = try delete() callbacks.aroundDeleteExitCount += 1 @@ -2653,7 +2653,7 @@ extension MutablePersistableRecordTests { func test_aroundSave_misuse_by_not_calling_the_action() throws { struct BadRecord: MutablePersistableRecord, Encodable { let id = 1 - func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + func aroundSave(_ db: DatabaseBase, save: () throws -> PersistenceSuccess) throws { // It is a programmer error to not call the `save` argument } } @@ -2669,7 +2669,7 @@ extension MutablePersistableRecordTests { func test_aroundSave_misuse_by_not_rethrowing_the_action_error() throws { struct BadRecord: MutablePersistableRecord, Encodable { let id = 1 - func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + func aroundSave(_ db: DatabaseBase, save: () throws -> PersistenceSuccess) throws { // It is a programmer error to not rethrow the error of the `save` argument _ = try? save() } @@ -2687,7 +2687,7 @@ extension MutablePersistableRecordTests { func test_aroundUpdate_misuse_by_not_calling_the_action() throws { struct BadRecord: MutablePersistableRecord, Encodable { let id = 1 - func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + func aroundUpdate(_ db: DatabaseBase, columns: Set, update: () throws -> PersistenceSuccess) throws { // It is a programmer error to not call the `update` argument } } @@ -2703,7 +2703,7 @@ extension MutablePersistableRecordTests { func test_aroundUpdate_misuse_by_not_rethrowing_the_action_error() throws { struct BadRecord: MutablePersistableRecord, Encodable { let id = 1 - func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + func aroundUpdate(_ db: DatabaseBase, columns: Set, update: () throws -> PersistenceSuccess) throws { // It is a programmer error to not rethrow the error of the `update` argument _ = try? update() } @@ -2721,7 +2721,7 @@ extension MutablePersistableRecordTests { func test_aroundInsert_misuse_by_not_calling_the_action() throws { struct BadRecord: MutablePersistableRecord, Encodable { let id = 1 - func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + func aroundInsert(_ db: DatabaseBase, insert: () throws -> InsertionSuccess) throws { // It is a programmer error to not call the `insert` argument } } @@ -2738,7 +2738,7 @@ extension MutablePersistableRecordTests { func test_aroundInsert_misuse_by_not_rethrowing_the_action_error() throws { struct BadRecord: MutablePersistableRecord, Encodable { let id = 1 - func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + func aroundInsert(_ db: DatabaseBase, insert: () throws -> InsertionSuccess) throws { // It is a programmer error to not rethrow the error of the `insert` argument _ = try? insert() } @@ -2760,7 +2760,7 @@ extension MutablePersistableRecordTests { func test_aroundDelete_misuse_by_not_calling_the_action() throws { struct BadRecord: MutablePersistableRecord, Encodable { let id = 1 - func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + func aroundDelete(_ db: DatabaseBase, delete: () throws -> Bool) throws { // It is a programmer error to not call the `delete` argument } } @@ -2776,7 +2776,7 @@ extension MutablePersistableRecordTests { func test_aroundDelete_misuse_by_not_rethrowing_the_action_error() throws { struct BadRecord: MutablePersistableRecord, Encodable { let id = 1 - func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + func aroundDelete(_ db: DatabaseBase, delete: () throws -> Bool) throws { // It is a programmer error to not rethrow the error of the `delete` argument _ = try? delete() } diff --git a/Tests/GRDBTests/PersistableRecordTests.swift b/Tests/GRDBTests/PersistableRecordTests.swift index 6be773caa..c9474120f 100644 --- a/Tests/GRDBTests/PersistableRecordTests.swift +++ b/Tests/GRDBTests/PersistableRecordTests.swift @@ -84,13 +84,13 @@ private struct PersistableRecordCustomizedCountry : PersistableRecord { container["name"] = name } - func willInsert(_ db: Database) throws { + func willInsert(_ db: DatabaseBase) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") callbacks.willInsertCount += 1 } - func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + func aroundInsert(_ db: DatabaseBase, insert: () throws -> InsertionSuccess) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") @@ -103,13 +103,13 @@ private struct PersistableRecordCustomizedCountry : PersistableRecord { callbacks.didInsertCount += 1 } - func willUpdate(_ db: Database, columns: Set) throws { + func willUpdate(_ db: DatabaseBase, columns: Set) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") callbacks.willUpdateCount += 1 } - func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + func aroundUpdate(_ db: DatabaseBase, columns: Set, update: () throws -> PersistenceSuccess) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") @@ -122,13 +122,13 @@ private struct PersistableRecordCustomizedCountry : PersistableRecord { callbacks.didUpdateCount += 1 } - func willSave(_ db: Database) throws { + func willSave(_ db: DatabaseBase) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") callbacks.willSaveCount += 1 } - func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + func aroundSave(_ db: DatabaseBase, save: () throws -> PersistenceSuccess) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") @@ -141,13 +141,13 @@ private struct PersistableRecordCustomizedCountry : PersistableRecord { callbacks.didSaveCount += 1 } - func willDelete(_ db: Database) throws { + func willDelete(_ db: DatabaseBase) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") callbacks.willDeleteCount += 1 } - func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + func aroundDelete(_ db: DatabaseBase, delete: () throws -> Bool) throws { // Make sure database can be used try db.execute(sql: "SELECT 1") @@ -185,11 +185,11 @@ private struct PartialPlayer: Codable, PersistableRecord, FetchableRecord { typealias Columns = FullPlayer.Columns - func willInsert(_ db: Database) throws { + func willInsert(_ db: DatabaseBase) throws { callbacks.willInsertCount += 1 } - func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + func aroundInsert(_ db: DatabaseBase, insert: () throws -> InsertionSuccess) throws { callbacks.aroundInsertEnterCount += 1 _ = try insert() callbacks.aroundInsertExitCount += 1 @@ -199,11 +199,11 @@ private struct PartialPlayer: Codable, PersistableRecord, FetchableRecord { callbacks.didInsertCount += 1 } - func willUpdate(_ db: Database, columns: Set) throws { + func willUpdate(_ db: DatabaseBase, columns: Set) throws { callbacks.willUpdateCount += 1 } - func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + func aroundUpdate(_ db: DatabaseBase, columns: Set, update: () throws -> PersistenceSuccess) throws { callbacks.aroundUpdateEnterCount += 1 _ = try update() callbacks.aroundUpdateExitCount += 1 @@ -213,11 +213,11 @@ private struct PartialPlayer: Codable, PersistableRecord, FetchableRecord { callbacks.didUpdateCount += 1 } - func willSave(_ db: Database) throws { + func willSave(_ db: DatabaseBase) throws { callbacks.willSaveCount += 1 } - func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + func aroundSave(_ db: DatabaseBase, save: () throws -> PersistenceSuccess) throws { callbacks.aroundSaveEnterCount += 1 _ = try save() callbacks.aroundSaveExitCount += 1 @@ -227,11 +227,11 @@ private struct PartialPlayer: Codable, PersistableRecord, FetchableRecord { callbacks.didSaveCount += 1 } - func willDelete(_ db: Database) throws { + func willDelete(_ db: DatabaseBase) throws { callbacks.willDeleteCount += 1 } - func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + func aroundDelete(_ db: DatabaseBase, delete: () throws -> Bool) throws { callbacks.aroundDeleteEnterCount += 1 _ = try delete() callbacks.aroundDeleteExitCount += 1 @@ -260,11 +260,11 @@ private struct FullPlayer: Codable, PersistableRecord, FetchableRecord { let callbacks = Callbacks() - func willInsert(_ db: Database) throws { + func willInsert(_ db: DatabaseBase) throws { callbacks.willInsertCount += 1 } - func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws { + func aroundInsert(_ db: DatabaseBase, insert: () throws -> InsertionSuccess) throws { callbacks.aroundInsertEnterCount += 1 _ = try insert() callbacks.aroundInsertExitCount += 1 @@ -274,11 +274,11 @@ private struct FullPlayer: Codable, PersistableRecord, FetchableRecord { callbacks.didInsertCount += 1 } - func willUpdate(_ db: Database, columns: Set) throws { + func willUpdate(_ db: DatabaseBase, columns: Set) throws { callbacks.willUpdateCount += 1 } - func aroundUpdate(_ db: Database, columns: Set, update: () throws -> PersistenceSuccess) throws { + func aroundUpdate(_ db: DatabaseBase, columns: Set, update: () throws -> PersistenceSuccess) throws { callbacks.aroundUpdateEnterCount += 1 _ = try update() callbacks.aroundUpdateExitCount += 1 @@ -288,11 +288,11 @@ private struct FullPlayer: Codable, PersistableRecord, FetchableRecord { callbacks.didUpdateCount += 1 } - func willSave(_ db: Database) throws { + func willSave(_ db: DatabaseBase) throws { callbacks.willSaveCount += 1 } - func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { + func aroundSave(_ db: DatabaseBase, save: () throws -> PersistenceSuccess) throws { callbacks.aroundSaveEnterCount += 1 _ = try save() callbacks.aroundSaveExitCount += 1 @@ -302,11 +302,11 @@ private struct FullPlayer: Codable, PersistableRecord, FetchableRecord { callbacks.didSaveCount += 1 } - func willDelete(_ db: Database) throws { + func willDelete(_ db: DatabaseBase) throws { callbacks.willDeleteCount += 1 } - func aroundDelete(_ db: Database, delete: () throws -> Bool) throws { + func aroundDelete(_ db: DatabaseBase, delete: () throws -> Bool) throws { callbacks.aroundDeleteEnterCount += 1 _ = try delete() callbacks.aroundDeleteExitCount += 1 diff --git a/Tests/GRDBTests/PrimaryKeyInfoTests.swift b/Tests/GRDBTests/PrimaryKeyInfoTests.swift index 7cae11b84..cd2c4d21d 100644 --- a/Tests/GRDBTests/PrimaryKeyInfoTests.swift +++ b/Tests/GRDBTests/PrimaryKeyInfoTests.swift @@ -251,7 +251,7 @@ class PrimaryKeyInfoTests: GRDBTestCase { func test_custom_schemaSource_nil_result() throws { struct MySchemaSource: DatabaseSchemaSource { - func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + func columnsForPrimaryKey(_ db: DatabaseBase, inView view: DatabaseObjectID) throws -> [String]? { nil } } @@ -289,7 +289,7 @@ class PrimaryKeyInfoTests: GRDBTestCase { func test_custom_schemaSource_empty_result() throws { struct MySchemaSource: DatabaseSchemaSource { - func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + func columnsForPrimaryKey(_ db: DatabaseBase, inView view: DatabaseObjectID) throws -> [String]? { [] } } @@ -327,7 +327,7 @@ class PrimaryKeyInfoTests: GRDBTestCase { func test_custom_schemaSource_custom_primary_key() throws { struct MySchemaSource: DatabaseSchemaSource { - func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + func columnsForPrimaryKey(_ db: DatabaseBase, inView view: DatabaseObjectID) throws -> [String]? { ["playerId"] } } diff --git a/Tests/GRDBTests/RecordEditedTests.swift b/Tests/GRDBTests/RecordEditedTests.swift index 64573f4c4..7ed5995cb 100644 --- a/Tests/GRDBTests/RecordEditedTests.swift +++ b/Tests/GRDBTests/RecordEditedTests.swift @@ -15,7 +15,7 @@ private class Person : Record { super.init() } - static func setup(_ db: Database) throws { + static func setup(_ db: DatabaseBase) throws { try db.execute(sql: """ CREATE TABLE persons ( id INTEGER PRIMARY KEY, @@ -46,7 +46,7 @@ private class Person : Record { container["creationDate"] = creationDate } - override func willInsert(_ db: Database) throws { + override func willInsert(_ db: DatabaseBase) throws { if creationDate == nil { creationDate = Date() } @@ -114,7 +114,7 @@ private class PersonWithModifiedCaseColumns: Record { container["CREATIONDATE"] = creationDate } - override func willInsert(_ db: Database) throws { + override func willInsert(_ db: DatabaseBase) throws { if creationDate == nil { creationDate = Date() } diff --git a/Tests/GRDBTests/RecordMappedOnMutableViewTests.swift b/Tests/GRDBTests/RecordMappedOnMutableViewTests.swift index 429f8f1d9..8ba791e7c 100644 --- a/Tests/GRDBTests/RecordMappedOnMutableViewTests.swift +++ b/Tests/GRDBTests/RecordMappedOnMutableViewTests.swift @@ -45,7 +45,7 @@ private struct Captain: Codable, } private struct SchemaSource: DatabaseSchemaSource { - func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + func columnsForPrimaryKey(_ db: DatabaseBase, inView view: DatabaseObjectID) throws -> [String]? { if view.name == "captain" { return ["id"] } else { diff --git a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift index 069f0e4f3..371839d10 100644 --- a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift @@ -13,7 +13,7 @@ private class MinimalNonOptionalPrimaryKeySingle: Record, Hashable { super.init() } - static func setup(_ db: Database) throws { + static func setup(_ db: DatabaseBase) throws { try db.execute(sql: "CREATE TABLE minimalSingles (id TEXT NOT NULL PRIMARY KEY)") } diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index 7102057a5..c05aadf02 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -12,7 +12,7 @@ class MinimalRowID : Record, Hashable { super.init() } - static func setup(_ db: Database) throws { + static func setup(_ db: DatabaseBase) throws { try db.execute(sql: "CREATE TABLE minimalRowIDs (id INTEGER PRIMARY KEY)") } diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift index 2216058f9..fd9ee72b1 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift @@ -11,7 +11,7 @@ class MinimalSingle: Record, Hashable { super.init() } - static func setup(_ db: Database) throws { + static func setup(_ db: DatabaseBase) throws { try db.execute(sql: "CREATE TABLE minimalSingles (UUID TEXT NOT NULL PRIMARY KEY)") } diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index d8bc981db..dc94315e8 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -16,7 +16,7 @@ private class Person : Record, Hashable { super.init() } - static func setup(_ db: Database) throws { + static func setup(_ db: DatabaseBase) throws { try db.execute(sql: """ CREATE TABLE persons ( creationDate TEXT NOT NULL, @@ -50,7 +50,7 @@ private class Person : Record, Hashable { container["creationDate"] = creationDate } - override func willInsert(_ db: Database) throws { + override func willInsert(_ db: DatabaseBase) throws { if creationDate == nil { creationDate = Date() } diff --git a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift index cf792c686..e22db2873 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift @@ -14,7 +14,7 @@ private class Citizenship : Record, Hashable { super.init() } - static func setup(_ db: Database) throws { + static func setup(_ db: DatabaseBase) throws { try db.execute(sql: """ CREATE TABLE citizenships ( personName TEXT NOT NULL, diff --git a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift index a96bd496e..b15ab383e 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift @@ -14,7 +14,7 @@ private class Item : Record, Hashable { super.init() } - static func setup(_ db: Database) throws { + static func setup(_ db: DatabaseBase) throws { try db.execute(sql: """ CREATE TABLE items ( name TEXT, diff --git a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift index dabb5c908..934b0acb0 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift @@ -16,7 +16,7 @@ private class Person : Record, Hashable { super.init() } - static func setup(_ db: Database) throws { + static func setup(_ db: DatabaseBase) throws { try db.execute(sql: """ CREATE TABLE persons ( id INTEGER PRIMARY KEY, @@ -47,7 +47,7 @@ private class Person : Record, Hashable { container["creationDate"] = creationDate } - override func willInsert(_ db: Database) throws { + override func willInsert(_ db: DatabaseBase) throws { if creationDate == nil { creationDate = Date() } diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift index ca70ff5b4..e7b4d8ffb 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift @@ -12,7 +12,7 @@ class Pet : Record, Hashable { super.init() } - static func setup(_ db: Database) throws { + static func setup(_ db: DatabaseBase) throws { try db.execute(sql: """ CREATE TABLE pets ( UUID TEXT NOT NULL PRIMARY KEY, diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift index 8451feeab..db5d8cd97 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift @@ -11,7 +11,7 @@ class Email : Record, Hashable { super.init() } - static func setup(_ db: Database) throws { + static func setup(_ db: DatabaseBase) throws { try db.execute(sql: """ CREATE TABLE emails ( email TEXT NOT NULL PRIMARY KEY ON CONFLICT REPLACE, diff --git a/Tests/GRDBTests/RecordSubClassTests.swift b/Tests/GRDBTests/RecordSubClassTests.swift index ce82183f5..4f603e56b 100644 --- a/Tests/GRDBTests/RecordSubClassTests.swift +++ b/Tests/GRDBTests/RecordSubClassTests.swift @@ -15,7 +15,7 @@ private class Person : Record { super.init() } - static func setup(_ db: Database) throws { + static func setup(_ db: DatabaseBase) throws { try db.execute(sql: """ CREATE TABLE persons ( id INTEGER PRIMARY KEY, @@ -46,7 +46,7 @@ private class Person : Record { container["creationDate"] = creationDate } - override func willInsert(_ db: Database) throws { + override func willInsert(_ db: DatabaseBase) throws { if creationDate == nil { creationDate = Date() } @@ -90,12 +90,12 @@ private class PersonWithOverrides : Person { try super.init(row: row) } - override func willInsert(_ db: Database) throws { + override func willInsert(_ db: DatabaseBase) throws { lastSavingMethod = .insert try super.willInsert(db) } - override func willUpdate(_ db: Database, columns: Set) throws { + override func willUpdate(_ db: DatabaseBase, columns: Set) throws { lastSavingMethod = .update try super.willUpdate(db, columns: columns) } diff --git a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift index e9dba8383..4240cac5e 100644 --- a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift +++ b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift @@ -13,7 +13,7 @@ class BadlyMangledStuff : Record { super.init() } - static func setup(_ db: Database) throws { + static func setup(_ db: DatabaseBase) throws { try db.execute(sql: "CREATE TABLE stuffs (id INTEGER PRIMARY KEY, name TEXT)") } diff --git a/Tests/GRDBTests/SelectStatementTests.swift b/Tests/GRDBTests/SelectStatementTests.swift index 95d8d39c4..8180f5b11 100644 --- a/Tests/GRDBTests/SelectStatementTests.swift +++ b/Tests/GRDBTests/SelectStatementTests.swift @@ -301,12 +301,12 @@ class SelectStatementTests : GRDBTestCase { didChange = true } - func databaseDidCommit(_ db: Database) { + func databaseDidCommit(_ db: DatabaseBase) { triggered = didChange didChange = false } - func databaseDidRollback(_ db: Database) { + func databaseDidRollback(_ db: DatabaseBase) { didChange = false } } diff --git a/Tests/GRDBTests/SingletonRecordTest.swift b/Tests/GRDBTests/SingletonRecordTest.swift index 3f4e3ba27..eced265b9 100644 --- a/Tests/GRDBTests/SingletonRecordTest.swift +++ b/Tests/GRDBTests/SingletonRecordTest.swift @@ -22,7 +22,7 @@ extension AppConfiguration { // Database Access extension AppConfiguration: FetchableRecord, PersistableRecord { // Customize the default PersistableRecord behavior - func willUpdate(_ db: Database, columns: Set) throws { + func willUpdate(_ db: DatabaseBase, columns: Set) throws { // Insert the default configuration if it does not exist yet. if try !exists(db) { try AppConfiguration.default.insert(db) @@ -31,13 +31,13 @@ extension AppConfiguration: FetchableRecord, PersistableRecord { /// Returns the persisted configuration, or the default one if the /// database table is empty. - static func find(_ db: Database) throws -> AppConfiguration { + static func find(_ db: DatabaseBase) throws -> AppConfiguration { try fetchOne(db) ?? .default } } class SingletonRecordTest: GRDBTestCase { - private func createEmptyAppConfigurationTable(_ db: Database) throws { + private func createEmptyAppConfigurationTable(_ db: DatabaseBase) throws { // Table creation try db.create(table: "appConfiguration") { t in // Single row guarantee diff --git a/Tests/GRDBTests/SingletonUserDefaultsTest.swift b/Tests/GRDBTests/SingletonUserDefaultsTest.swift index 7db9f80e3..a8b2ef3d6 100644 --- a/Tests/GRDBTests/SingletonUserDefaultsTest.swift +++ b/Tests/GRDBTests/SingletonUserDefaultsTest.swift @@ -28,7 +28,7 @@ extension AppConfiguration { // Database Access extension AppConfiguration: FetchableRecord, PersistableRecord { // Customize the default PersistableRecord behavior - func willUpdate(_ db: Database, columns: Set) throws { + func willUpdate(_ db: DatabaseBase, columns: Set) throws { // Insert the default configuration if it does not exist yet. if try !exists(db) { try AppConfiguration.default.insert(db) @@ -37,13 +37,13 @@ extension AppConfiguration: FetchableRecord, PersistableRecord { /// Returns the persisted configuration, or the default one if the /// database table is empty. - static func find(_ db: Database) throws -> AppConfiguration { + static func find(_ db: DatabaseBase) throws -> AppConfiguration { try fetchOne(db) ?? .default } } class SingletonUserDefaultsTest: GRDBTestCase { - private func createEmptyAppConfigurationTable(_ db: Database) throws { + private func createEmptyAppConfigurationTable(_ db: DatabaseBase) throws { // Table creation try db.create(table: "appConfiguration") { t in // Single row guarantee diff --git a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift index 02b77ec50..5ea735024 100644 --- a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift +++ b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import XCTest import GRDB @@ -23,7 +23,7 @@ private struct Fetched: DatabaseValueConvertible, StatementColumnConvertible, Ha self.fast = fast } - init(sqliteStatement: SQLiteStatement, index: CInt) { + init(sqliteStatement: SQLiteStatementBase, index: CInt) { self.init(int: Int(sqlite3_column_int64(sqliteStatement, index)), fast: true) } diff --git a/Tests/GRDBTests/TableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift index fdbc26fc8..4cb830b2a 100644 --- a/Tests/GRDBTests/TableRecordDeleteTests.swift +++ b/Tests/GRDBTests/TableRecordDeleteTests.swift @@ -50,7 +50,7 @@ private struct CitizenshipView : TableRecord { // Schema source private struct ViewSchemaSource: DatabaseSchemaSource { - func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + func columnsForPrimaryKey(_ db: DatabaseBase, inView view: DatabaseObjectID) throws -> [String]? { switch view.name { case "personsView": return ["id"] diff --git a/Tests/GRDBTests/TableRecordUpdateTests.swift b/Tests/GRDBTests/TableRecordUpdateTests.swift index dfa9b76dc..3ba22a56a 100644 --- a/Tests/GRDBTests/TableRecordUpdateTests.swift +++ b/Tests/GRDBTests/TableRecordUpdateTests.swift @@ -14,7 +14,7 @@ private struct Player: Codable, Identifiable, PersistableRecord, FetchableRecord static let bonus = Column(CodingKeys.bonus) } - static func createTable(_ db: Database) throws { + static func createTable(_ db: DatabaseBase) throws { try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text) @@ -37,7 +37,7 @@ private struct PlayerView: Codable, Identifiable, PersistableRecord, FetchableRe static let bonus = Column(CodingKeys.bonus) } - static func createTable(_ db: Database) throws { + static func createTable(_ db: DatabaseBase) throws { try db.execute(sql: """ CREATE VIEW playerView AS SELECT * FROM player; -- Insert trigger @@ -59,7 +59,7 @@ private struct PlayerView: Codable, Identifiable, PersistableRecord, FetchableRe } private struct ViewSchemaSource: DatabaseSchemaSource { - func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + func columnsForPrimaryKey(_ db: DatabaseBase, inView view: DatabaseObjectID) throws -> [String]? { ["id"] } } @@ -67,7 +67,7 @@ private struct ViewSchemaSource: DatabaseSchemaSource { private typealias Columns = Player.Columns private extension QueryInterfaceRequest { - func incrementScore(_ db: Database) throws { + func incrementScore(_ db: DatabaseBase) throws { try updateAll(db) { $0.score += 1 } } } diff --git a/Tests/GRDBTests/TransactionDateTests.swift b/Tests/GRDBTests/TransactionDateTests.swift index f2121530b..26c11c5be 100644 --- a/Tests/GRDBTests/TransactionDateTests.swift +++ b/Tests/GRDBTests/TransactionDateTests.swift @@ -289,7 +289,7 @@ class TransactionDateTests: GRDBTestCase { case name } - mutating func willInsert(_ db: Database) throws { + mutating func willInsert(_ db: DatabaseBase) throws { isInserted = true try initializeTimestamps(db) } @@ -333,7 +333,7 @@ class TransactionDateTests: GRDBTestCase { self.name = name } - func willInsert(_ db: Database) throws { + func willInsert(_ db: DatabaseBase) throws { // Can't call initializeTimestamps because it is mutating if creationDate == nil { creationDate = try db.transactionDate @@ -385,7 +385,7 @@ extension TimestampedRecord { /// `TimestampedRecord` types that customize the `willInsert` /// persistence callback should call `initializeTimestamps` from /// their implementation. - mutating func willInsert(_ db: Database) throws { + mutating func willInsert(_ db: DatabaseBase) throws { try initializeTimestamps(db) } @@ -395,7 +395,7 @@ extension TimestampedRecord { /// It is called automatically before insertion, if your type does not /// customize the `willInsert` persistence callback. If you customize /// this callback, call `initializeTimestamps` from your implementation. - mutating func initializeTimestamps(_ db: Database) throws { + mutating func initializeTimestamps(_ db: DatabaseBase) throws { if creationDate == nil { creationDate = try db.transactionDate } @@ -409,7 +409,7 @@ extension TimestampedRecord { /// /// - parameter modificationDate: The modification date. If nil, the /// transaction date is used. - mutating func updateWithTimestamp(_ db: Database, modificationDate: Date? = nil) throws { + mutating func updateWithTimestamp(_ db: DatabaseBase, modificationDate: Date? = nil) throws { self.modificationDate = try modificationDate ?? db.transactionDate try update(db) } @@ -442,7 +442,7 @@ extension TimestampedRecord { /// - returns: Whether the record was changed and updated. @discardableResult mutating func updateChangesWithTimestamp( - _ db: Database, + _ db: DatabaseBase, modificationDate: Date? = nil, modify: (inout Self) -> Void) throws -> Bool @@ -470,7 +470,7 @@ extension TimestampedRecord { /// /// - parameter modificationDate: The modification date. If nil, the /// transaction date is used. - mutating func touch(_ db: Database, modificationDate: Date? = nil) throws { + mutating func touch(_ db: DatabaseBase, modificationDate: Date? = nil) throws { try updateChanges(db) { $0.modificationDate = try modificationDate ?? db.transactionDate } diff --git a/Tests/GRDBTests/TransactionObserverSavepointsTests.swift b/Tests/GRDBTests/TransactionObserverSavepointsTests.swift index b0df5932b..e77cdab44 100644 --- a/Tests/GRDBTests/TransactionObserverSavepointsTests.swift +++ b/Tests/GRDBTests/TransactionObserverSavepointsTests.swift @@ -18,12 +18,12 @@ private class Observer : TransactionObserver { events.append(event.copy()) } - func databaseDidCommit(_ db: Database) { + func databaseDidCommit(_ db: DatabaseBase) { lastCommittedEvents = events events = [] } - func databaseDidRollback(_ db: Database) { + func databaseDidRollback(_ db: DatabaseBase) { lastCommittedEvents = [] events = [] } diff --git a/Tests/GRDBTests/TransactionObserverTests.swift b/Tests/GRDBTests/TransactionObserverTests.swift index cedbb2302..605387484 100644 --- a/Tests/GRDBTests/TransactionObserverTests.swift +++ b/Tests/GRDBTests/TransactionObserverTests.swift @@ -68,7 +68,7 @@ private class Observer : TransactionObserver { } } - func databaseDidCommit(_ db: Database) { + func databaseDidCommit(_ db: DatabaseBase) { didCommitCount += 1 lastCommittedEvents = events events = [] @@ -79,7 +79,7 @@ private class Observer : TransactionObserver { didCommitBlock?(db) } - func databaseDidRollback(_ db: Database) { + func databaseDidRollback(_ db: DatabaseBase) { didRollbackCount += 1 lastCommittedEvents = [] events = [] @@ -1728,8 +1728,8 @@ class TransactionObserverTests: GRDBTestCase { } func databaseWillCommit() throws { willCommitCount += 1 } - func databaseDidCommit(_ db: Database) { didCommitCount += 1 } - func databaseDidRollback(_ db: Database) { didRollbackCount += 1 } + func databaseDidCommit(_ db: DatabaseBase) { didCommitCount += 1 } + func databaseDidRollback(_ db: DatabaseBase) { didRollbackCount += 1 } } let observer = Observer() @@ -2479,8 +2479,8 @@ class TransactionObserverTests: GRDBTestCase { } func databaseWillCommit() throws { willCommitCount += 1 } - func databaseDidCommit(_ db: Database) { didCommitCount += 1 } - func databaseDidRollback(_ db: Database) { didRollbackCount += 1 } + func databaseDidCommit(_ db: DatabaseBase) { didCommitCount += 1 } + func databaseDidRollback(_ db: DatabaseBase) { didRollbackCount += 1 } } let dbQueue = try makeDatabaseQueue() diff --git a/Tests/GRDBTests/TruncateOptimizationTests.swift b/Tests/GRDBTests/TruncateOptimizationTests.swift index d0700bb2f..a69fe31e2 100644 --- a/Tests/GRDBTests/TruncateOptimizationTests.swift +++ b/Tests/GRDBTests/TruncateOptimizationTests.swift @@ -41,14 +41,14 @@ class TruncateOptimizationTests: GRDBTestCase { } } - func databaseDidCommit(_ db: Database) { + func databaseDidCommit(_ db: DatabaseBase) { if !deletionEvents.isEmpty { notify(deletionEvents) } deletionEvents = [:] } - func databaseDidRollback(_ db: Database) { + func databaseDidRollback(_ db: DatabaseBase) { deletionEvents = [:] } } @@ -56,8 +56,8 @@ class TruncateOptimizationTests: GRDBTestCase { class UniversalObserver : TransactionObserver { func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true } func databaseDidChange(with event: DatabaseEvent) { } - func databaseDidCommit(_ db: Database) { } - func databaseDidRollback(_ db: Database) { } + func databaseDidCommit(_ db: DatabaseBase) { } + func databaseDidRollback(_ db: DatabaseBase) { } } func testExecuteDelete() throws { @@ -105,8 +105,8 @@ class TruncateOptimizationTests: GRDBTestCase { } } - func databaseDidCommit(_ db: Database) { } - func databaseDidRollback(_ db: Database) { } + func databaseDidCommit(_ db: DatabaseBase) { } + func databaseDidRollback(_ db: DatabaseBase) { } } let observer = DeletionObserver() diff --git a/Tests/GRDBTests/UpdateStatementTests.swift b/Tests/GRDBTests/UpdateStatementTests.swift index f11e35117..a6b86fc83 100644 --- a/Tests/GRDBTests/UpdateStatementTests.swift +++ b/Tests/GRDBTests/UpdateStatementTests.swift @@ -1,14 +1,14 @@ -// Import C SQLite functions -#if GRDBCIPHER // CocoaPods (SQLCipher subspec) -import SQLCipher -#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) -import SQLite3 -#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework -// #elseif SomeTrait -// import ... -#else // Default SPM trait must be the default. It impossible to detect from Xcode. -import GRDBSQLite -#endif +//// Import C SQLite functions +//#if GRDBCIPHER // CocoaPods (SQLCipher subspec) +//import SQLCipher +//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec) +//import SQLite3 +//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework +//// #elseif SomeTrait +//// import ... +//#else // Default SPM trait must be the default. It impossible to detect from Xcode. +//import GRDBSQLite +//#endif import XCTest import GRDB diff --git a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift index c11704e34..593cebc07 100644 --- a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift @@ -19,7 +19,7 @@ private struct ParentInfo: FetchableRecord, Decodable, Equatable { } class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { - private func setup(_ db: Database) throws { + private func setup(_ db: DatabaseBase) throws { try db.create(table: "parent") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text) @@ -31,7 +31,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { } } - private func performDatabaseModifications(_ db: Database) throws { + private func performDatabaseModifications(_ db: DatabaseBase) throws { try db.inTransaction { try db.execute(sql: """ INSERT INTO parent (id, name) VALUES (1, 'foo'); diff --git a/Tests/GRDBTests/ValueObservationRecorder.swift b/Tests/GRDBTests/ValueObservationRecorder.swift index 8a895c564..c5b81bb51 100644 --- a/Tests/GRDBTests/ValueObservationRecorder.swift +++ b/Tests/GRDBTests/ValueObservationRecorder.swift @@ -356,8 +356,8 @@ extension GRDBTestCase { func assertValueObservation( _ observation: ValueObservation, records expectedValues: [Reducer.Value], - setup: (Database) throws -> Void, - recordedUpdates: @escaping (Database) throws -> Void, + setup: (DatabaseBase) throws -> Void, + recordedUpdates: @escaping (DatabaseBase) throws -> Void, file: StaticString = #file, line: UInt = #line) throws @@ -568,7 +568,7 @@ extension GRDBTestCase { func assertValueObservation( _ observation: ValueObservation, fails testFailure: (Failure, any DatabaseWriter) throws -> Void, - setup: (Database) throws -> Void, + setup: (DatabaseBase) throws -> Void, file: StaticString = #file, line: UInt = #line) throws diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index 6134d8453..e18448686 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -23,7 +23,7 @@ class ValueObservationTests: GRDBTestCase { // See func testValuesFromAnyDatabaseWriter(writer: any DatabaseWriter) { func observe( - fetch: @escaping @Sendable (Database) throws -> T + fetch: @escaping @Sendable (DatabaseBase) throws -> T ) throws -> AsyncValueObservation { ValueObservation.tracking(fetch).values(in: writer) } @@ -1366,8 +1366,8 @@ class ValueObservationTests: GRDBTestCase { } func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true } func databaseDidChange(with event: DatabaseEvent) { } - func databaseDidRollback(_ db: Database) { } - func databaseDidCommit(_ db: Database) { + func databaseDidRollback(_ db: DatabaseBase) { } + func databaseDidCommit(_ db: DatabaseBase) { task.cancel() } } diff --git a/Tests/GRDBTests/VirtualTableModuleTests.swift b/Tests/GRDBTests/VirtualTableModuleTests.swift index b13848acd..f852f43d4 100644 --- a/Tests/GRDBTests/VirtualTableModuleTests.swift +++ b/Tests/GRDBTests/VirtualTableModuleTests.swift @@ -15,7 +15,7 @@ private struct FTS3TokenizeModule : VirtualTableModule { return [tokenizer] } - func database(_ db: Database, didCreate tableName: String, using definition: FTS3TokenizeTableDefinition) throws { + func database(_ db: DatabaseBase, didCreate tableName: String, using definition: FTS3TokenizeTableDefinition) throws { } } @@ -33,7 +33,7 @@ private struct ThrowingFTS3TokenizeModule : VirtualTableModule { return [tokenizer] } - func database(_ db: Database, didCreate tableName: String, using definition: FTS3TokenizeTableDefinition) throws { + func database(_ db: DatabaseBase, didCreate tableName: String, using definition: FTS3TokenizeTableDefinition) throws { throw DatabaseError(resultCode: ResultCode(rawValue: 123)) } } diff --git a/Tests/Performance/GRDBPerformance/InsertRecordOptimizedTests.swift b/Tests/Performance/GRDBPerformance/InsertRecordOptimizedTests.swift index b0bf10bce..01b875a37 100644 --- a/Tests/Performance/GRDBPerformance/InsertRecordOptimizedTests.swift +++ b/Tests/Performance/GRDBPerformance/InsertRecordOptimizedTests.swift @@ -16,7 +16,7 @@ private struct Item: Codable, FetchableRecord, PersistableRecord { var i8: Int var i9: Int - static func optimizedInsertStatement(_ db: Database) throws -> Statement { + static func optimizedInsertStatement(_ db: DatabaseBase) throws -> Statement { try db.makeStatement(literal: """ INSERT INTO \(self) ( \(CodingKeys.i0), diff --git a/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift b/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift index b778f3f9b..acca4b9a0 100644 --- a/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift +++ b/Tests/Performance/GRDBProfiling/GRDBProfiling/AppDelegate.swift @@ -70,7 +70,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { try dbQueue.read(_fetchValues) } - func _fetchValues(_ db: Database) throws { + func _fetchValues(_ db: DatabaseBase) throws { var count = 0 let cursor = try Int.fetchCursor(db, sql: "SELECT i0 FROM items") @@ -89,7 +89,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { try dbQueue.read(_fetchPositionalValues) } - func _fetchPositionalValues(_ db: Database) throws { + func _fetchPositionalValues(_ db: DatabaseBase) throws { var count = 0 let rows = try Row.fetchCursor(db, sql: "SELECT * FROM items") @@ -118,7 +118,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { try dbQueue.read(_fetchNamedValues) } - func _fetchNamedValues(_ db: Database) throws { + func _fetchNamedValues(_ db: DatabaseBase) throws { var count = 0 let rows = try Row.fetchCursor(db, sql: "SELECT * FROM items") @@ -152,7 +152,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { assert(items[expectedRowCount-1].i9 == expectedRowCount-1) } - func _fetchStructs(_ db: Database) throws -> [ItemStruct] { + func _fetchStructs(_ db: DatabaseBase) throws -> [ItemStruct] { try ItemStruct.fetchAll(db) } @@ -168,7 +168,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { assert(items[expectedRowCount-1].i9 == expectedRowCount-1) } - func _fetchCodables(_ db: Database) throws -> [ItemCodable] { + func _fetchCodables(_ db: DatabaseBase) throws -> [ItemCodable] { try ItemCodable.fetchAll(db) } @@ -184,7 +184,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { assert(items[expectedRowCount-1].i9 == expectedRowCount-1) } - func _fetchRecords(_ db: Database) throws -> [ItemRecord] { + func _fetchRecords(_ db: DatabaseBase) throws -> [ItemRecord] { try ItemRecord.fetchAll(db) } @@ -210,7 +210,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { try FileManager.default.removeItem(atPath: databasePath) } - func _insertPositionalValues(_ db: Database) throws { + func _insertPositionalValues(_ db: DatabaseBase) throws { let statement = try db.makeStatement(sql: "INSERT INTO items (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) VALUES (?,?,?,?,?,?,?,?,?,?)") for i in 0..) throws { let statement = try db.makeStatement(sql: "INSERT INTO items (i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) VALUES (:i0, :i1, :i2, :i3, :i4, :i5, :i6, :i7, :i8, :i9)") for i in 0..) throws { for i in 0..) throws { for i in 0..) throws { for i in 0.. Int { // Converting non-sendable function value to - // '@Sendable (Database) throws -> Int' may introduce data races. + // '@Sendable (DatabaseBase) throws -> Int' may introduce data races. try await writer.read(Player.fetchCount) }