Compare commits

..
Author SHA1 Message Date
Gwendal Roué b44628b9cd Add missing SendableMetatype requirements 2025-07-25 07:27:28 +02:00
245 changed files with 2728 additions and 6287 deletions

No files matched your search

+30 -30
View File
@@ -1,4 +1,4 @@
# https://github.com/actions/runner-images/blob/main/images/macos/macos-15-Readme.md
# https://github.com/actions/runner-images/blob/main/images/macos/macos-14-Readme.md
name: "GRDB CI"
@@ -40,20 +40,20 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
destination: "platform=macOS"
name: "macOS"
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
destination: "OS=18.5,name=iPhone 16 Pro"
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
destination: "OS=18.1,name=iPhone 16 Pro"
name: "iOS"
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
destination: "OS=18.5,name=Apple TV"
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
destination: "OS=18.1,name=Apple TV"
name: "tvOS"
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project GRDB.xcodeproj -scheme GRDB -destination "${{ matrix.destination }}" OTHER_SWIFT_FLAGS='$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' GCC_PREPROCESSOR_DEFINITIONS='$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' clean test
SPM:
@@ -66,11 +66,11 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
name: "Xcode 16.4"
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
name: "Xcode 16.1"
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: make test_SPM test_install_SPM
SQLCipher3:
@@ -83,11 +83,11 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
name: "Xcode 16.4"
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
name: "Xcode 16.1"
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher3Encrypted
SQLCipher4:
@@ -100,11 +100,11 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
name: "Xcode 16.4"
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
name: "Xcode 16.1"
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher4Encrypted
CustomSQLite:
@@ -117,11 +117,11 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
name: "Xcode 16.4"
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
name: "Xcode 16.1"
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: make test_framework_GRDBCustomSQLiteOSX
XCFramework:
@@ -134,11 +134,11 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
name: "Xcode 16.4"
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
name: "Xcode 16.1"
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: make test_universal_xcframework
+1 -1
View File
@@ -2,4 +2,4 @@ version: 1
builder:
configs:
- documentation_targets: [GRDB]
swift_version: 6.1
swift_version: 6.0
+113 -136
View File
@@ -7,8 +7,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 7.x Releases
- `7.8.x` Releases - [7.8.0](#780)
- `7.7.x` Releases - [7.7.0](#770) - [7.7.1](#771)
- `7.6.x` Releases - [7.6.0](#760) - [7.6.1](#761)
- `7.5.x` Releases - [7.5.0](#750)
- `7.4.x` Releases - [7.4.0](#740) - [7.4.1](#741)
@@ -140,27 +138,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 7.8.0
Released October 2, 2025
- **New**: Merged Migrations by [@groue](https://github.com/groue) in [#1818](https://github.com/groue/GRDB.swift/pull/1818)
## 7.7.1
Released September 29, 2025
- **Fixed**: Fix the save() method for record types with attached triggers by [@groue](https://github.com/groue) in [#1822](https://github.com/groue/GRDB.swift/pull/1822)
## 7.7.0
Released September 23, 2025
- **New**: Update GRDB7MigrationGuide.md reference by [@emmanuel-ferdman](https://github.com/emmanuel-ferdman) in [#1807](https://github.com/groue/GRDB.swift/pull/1807)
- **New**: Persistable Database Views by [@groue](https://github.com/groue) in [#1810](https://github.com/groue/GRDB.swift/pull/1810)
- **New**: Support for Xcode 26 by [@groue](https://github.com/groue) in [#1813](https://github.com/groue/GRDB.swift/pull/1813)
- **Fixed**: Fix another race condition regarding Task cancellation, completing [#1797](https://github.com/groue/GRDB.swift/pull/1797)
## 7.6.1
Released July 23, 2025
@@ -1731,7 +1708,7 @@ The [Advanced DatabasePool](README.md#advanced-databasepool) chapter has been ex
```diff
class DatabasePool {
+ func barrierWriteWithoutTransaction<T>(_ updates: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T
+ func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
+ func invalidateReadOnlyConnections()
}
@@ -1851,7 +1828,7 @@ The [ValueObservation](README.md#valueobservation) chapter has been updated so t
}
extension ValueObservation where Reducer == Void {
+ static func tracking<Value>(fetch: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Value) -> ValueObservation<ValueReducers.Fetch<Value>>
+ static func tracking<Value>(fetch: @escaping (Database) throws -> Value) -> ValueObservation<ValueReducers.Fetch<Value>>
}
```
@@ -1896,7 +1873,7 @@ The [ValueObservation Error Handling](README.md#valueobservation-error-handling)
+ var configuration: Configuration { get }
+
+ #if compiler(>=5.0)
+ func asyncRead(_ block: @escaping (Result<DatabaseBase<some SQLiteAPI>, Error>) -> Void)
+ func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void)
+ #endif
}
@@ -1904,7 +1881,7 @@ The [ValueObservation Error Handling](README.md#valueobservation-error-handling)
+ func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
+
+ #if compiler(>=5.0)
+ func asyncWrite<T>(_ updates: @escaping (DatabaseBase<some SQLiteAPI>) throws -> T, completion: @escaping (Database, Result<T, Error>) -> Void)
+ func asyncWrite<T>(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result<T, Error>) -> Void)
+ #endif
}
```
@@ -1984,8 +1961,8 @@ The [ValueObservation Error Handling](README.md#valueobservation-error-handling)
protocol FetchRequest {
+ // deprecated
func prepare(_ db: DatabaseBase<some SQLiteAPI>, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
+ func makePreparedRequest(_ db: DatabaseBase<some SQLiteAPI>, forSingleResult singleResult: Bool) throws -> PreparedRequest
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
+ func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
}
```
@@ -2189,37 +2166,37 @@ It comes with new features, but also a few breaking changes. The [GRDB 4 Migrati
}
class Row {
- static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor
- static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row]
- static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row?
+ static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RowCursor
+ static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Row]
+ static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> 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?
}
extension FetchableRecord {
- static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self>
- static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
- static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
+ static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RecordCursor<Self>
+ static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self]
+ static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self?
- static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self>
- 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<Self>
+ 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?
}
extension DatabaseValueConvertible {
- static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self>
- static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
- static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
+ static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self>
+ static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self]
+ static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self?
- static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self>
- 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<Self>
+ 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?
}
extension Optional where Wrapped: DatabaseValueConvertible {
- static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped>
- static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?]
+ static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped>
+ static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?]
- static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped>
- 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<Wrapped>
+ static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?]
}
extension TableRecord {
@@ -2324,7 +2301,7 @@ It comes with new features, but also a few breaking changes. The [GRDB 4 Migrati
struct ValueObservation<Reducer> {
- var extent: Database.TransactionObservationExtent
- static func tracking(_ regions: DatabaseRegionConvertible..., reducer: Reducer) -> ValueObservation
- static func tracking<Value>(_ regions: DatabaseRegionConvertible..., fetchDistinct fetch: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Value) -> ValueObservation<DistinctUntilChangedValueReducer<RawValueReducer<Value>>> where Value: Equatable
- static func tracking<Value>(_ regions: DatabaseRegionConvertible..., fetchDistinct fetch: @escaping (Database) throws -> Value) -> ValueObservation<DistinctUntilChangedValueReducer<RawValueReducer<Value>>> where Value: Equatable
}
```
@@ -2467,12 +2444,12 @@ It comes with new features, but also a few breaking changes. The [GRDB 4 Migrati
+ class DatabaseFuture<Value> { }
protocol FetchRequest {
- func prepare(_ db: DatabaseBase<some SQLiteAPI>) throws -> (SelectStatement, RowAdapter?)
+ func prepare(_ db: DatabaseBase<some SQLiteAPI>, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
- func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
+ func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
}
struct AnyFetchRequest<T> : FetchRequest {
- init(_ prepare: @escaping (DatabaseBase<some SQLiteAPI>) throws -> (SelectStatement, RowAdapter?))
- init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?))
+ init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?))
}
@@ -2595,24 +2572,24 @@ This release comes with:
}
extension MutablePersistableRecord {
+ mutating func updateChanges(_ db: DatabaseBase<some SQLiteAPI>, with change: (inout Self) throws -> Void) throws -> Bool
+ mutating func updateChanges(_ db: Database, with change: (inout Self) throws -> Void) throws -> Bool
}
extension PersistableRecord {
+ func updateChanges(_ db: DatabaseBase<some SQLiteAPI>, with change: (Self) throws -> Void) throws -> Bool
+ func updateChanges(_ db: Database, with change: (Self) throws -> Void) throws -> Bool
}
struct ValueObservation<Reducer> {
+ static func tracking(
+ _ regions: [DatabaseRegionConvertible],
+ reducer: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Reducer)
+ reducer: @escaping (Database) throws -> Reducer)
+ -> ValueObservation
}
+extension ValueObservation where Reducer == Void {
+ static func tracking<Value>(
+ _ regions: [DatabaseRegionConvertible],
+ fetch: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Value)
+ fetch: @escaping (Database) throws -> Value)
+ -> ValueObservation<ValueReducers.Raw<Value>>
+ static func combine<R1: ValueReducer, ...>(_ o1: ValueObservation<R1>, ...)
+ -> ValueObservation<...>
@@ -2697,13 +2674,13 @@ It used to be possible to define custom types that adopt the [DatabaseReader and
}
+protocol DatabaseRegionConvertible {
+ func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
+ func databaseRegion(_ db: Database) throws -> DatabaseRegion
+}
+
+extension DatabaseRegion: DatabaseRegionConvertible { }
+
+struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
+ init(_ region: @escaping (DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion)
+ init(_ region: @escaping (Database) throws -> DatabaseRegion)
+ init(_ region: DatabaseRegionConvertible)
+}
@@ -2719,7 +2696,7 @@ It used to be possible to define custom types that adopt the [DatabaseReader and
+protocol ValueReducer {
+ associatedtype Fetched
+ associatedtype Value
+ func fetch(_ db: DatabaseBase<some SQLiteAPI>) throws -> Fetched
+ func fetch(_ db: Database) throws -> Fetched
+ mutating func value(_ fetched: Fetched) -> Value?
+}
+
@@ -2728,7 +2705,7 @@ It used to be possible to define custom types that adopt the [DatabaseReader and
+}
+
+struct AnyValueReducer<Fetched, Value>: ValueReducer {
+ init(fetch: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Fetched, value: @escaping (Fetched) -> Value?)
+ init(fetch: @escaping (Database) throws -> Fetched, value: @escaping (Fetched) -> Value?)
+ init<Reducer: ValueReducer>(_ reducer: Reducer) where Reducer.Fetched == Fetched, Reducer.Value == Value
+}
@@ -2751,12 +2728,12 @@ It used to be possible to define custom types that adopt the [DatabaseReader and
+extension ValueObservation where Reducer == Void {
+ static func tracking<Value>(
+ _ regions: DatabaseRegionConvertible...,
+ fetch: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Value)
+ fetch: @escaping (Database) throws -> Value)
+ -> ValueObservation<ValueReducers.Raw<Value>>
+
+ static func tracking<Value>(
+ _ regions: DatabaseRegionConvertible...,
+ fetchDistinct: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Value)
+ fetchDistinct: @escaping (Database) throws -> Value)
+ -> ValueObservation<ValueReducers.Distinct<Value>>
+ where Value: Equatable
+
@@ -2801,7 +2778,7 @@ This release comes with **Association Aggregates**. They let you compute values
```diff
protocol AggregatingRequest {
- func group(_ expressions: [SQLExpressible]) -> Self
+ func group(_ expressions: @escaping (DatabaseBase<some SQLiteAPI>) throws -> [SQLExpressible]) -> Self
+ func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self
}
+extension AggregatingRequest {
@@ -2879,7 +2856,7 @@ Released September 16, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/co
```diff
protocol DatabaseWriter : DatabaseReader {
+ func concurrentRead<T>(_ block: @escaping (DatabaseBase<some SQLiteAPI>) throws -> T) -> Future<T>
+ func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> Future<T>
+ @available(*, deprecated)
func readFromCurrentState(_ block: @escaping (Database) -> Void) throws
}
@@ -2938,10 +2915,10 @@ Fixes:
```diff
class DatabaseQueue {
- func write<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T {
+ func write<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T {
- func unsafeReentrantRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T {
+ func unsafeReentrantRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T {
- func write<T>(_ block: (Database) throws -> T) rethrows -> T {
+ func write<T>(_ block: (Database) throws -> T) throws -> T {
- func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
+ func unsafeReentrantRead<T>(_ block: (Database) throws -> T) rethrows -> T {
}
```
@@ -3189,14 +3166,14 @@ Released February 25, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/com
extension MutablePersistable {
+ @discardableResult
+ func updateChanges(_ db: DatabaseBase<some SQLiteAPI>, from record: MutablePersistable) throws -> Bool
+ func updateChanges(_ db: Database, from record: MutablePersistable) throws -> Bool
+ func databaseEqual(_ record: Self) -> Bool
+ func databaseChanges(from record: MutablePersistable) -> [String: DatabaseValue]
}
class Record {
- final func updateChanges(_ db: DatabaseBase<some SQLiteAPI>) throws
- final func updateChanges(_ db: Database) throws
+ @discardableResult
+ final func updateChanges(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
+ final func updateChanges(_ db: Database) throws -> Bool
}
+@available(*, deprecated, message: "Prefer changes methods defined on the MutablePersistable protocol: databaseEqual(_:), databaseChanges(from:), updateChanges(from:)")
@@ -3212,7 +3189,7 @@ Released February 25, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/com
extension TableMapping {
+ static func selectionSQL(alias: String? = nil) -> String
+ static func numberOfSelectedColumns(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int
+ static func numberOfSelectedColumns(_ db: Database) throws -> Int
}
+struct EmptyRowAdapter: RowAdapter { }
@@ -3335,7 +3312,7 @@ Released January 18, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/comp
protocol Request {
+ // Default implementation
+ func fetchedRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
+ func fetchedRegion(_ db: Database) throws -> DatabaseRegion
}
+extension Row: RandomAccessCollection {
@@ -3402,8 +3379,8 @@ Released January 11, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/comp
}
extension RowConvertible where Self: TableMapping {
- static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, key: [String: DatabaseValueConvertible?]) throws -> Self?
+ static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, key: [String: DatabaseValueConvertible?]?) throws -> Self?
- static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Self?
+ static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]?) throws -> Self?
}
```
@@ -3533,7 +3510,7 @@ Released October 24, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/comp
```diff
extension Request {
+ func asSQLRequest(_ db: DatabaseBase<some SQLiteAPI>, cached: Bool = false) throws -> SQLRequest
+ func asSQLRequest(_ db: Database, cached: Bool = false) throws -> SQLRequest
}
struct SQLRequest {
+ let sql: String
@@ -3784,15 +3761,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: DatabaseBase<some SQLiteAPI>) throws -> Int
@discardableResult static func deleteAll<Sequence: Swift.Sequence>(_ db: DatabaseBase<some SQLiteAPI>, keys: Sequence) throws -> Int where Sequence.Element: DatabaseValueConvertible
@discardableResult static func deleteOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: DatabaseBase<some SQLiteAPI>, key: PrimaryKeyType?) throws -> Bool
@discardableResult static func deleteAll(_ db: DatabaseBase<some SQLiteAPI>, keys: [[String: DatabaseValueConvertible?]]) throws -> Int
@discardableResult static func deleteOne(_ db: DatabaseBase<some SQLiteAPI>, key: [String: DatabaseValueConvertible?]) throws -> Bool
@discardableResult static func deleteAll(_ db: Database) throws -> Int
@discardableResult static func deleteAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> Int where Sequence.Element: DatabaseValueConvertible
@discardableResult static func deleteOne<PrimaryKeyType: DatabaseValueConvertible>(_ 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
}
-extension QueryInterfaceRequest {
+extension QueryInterfaceRequest where RowDecoder: MutablePersistable {
@discardableResult func deleteAll(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int
@discardableResult func deleteAll(_ db: Database) throws -> Int
}
protocol TableMapping {
@@ -3862,30 +3839,30 @@ New features have been added in order to plug a few holes and support the [RxGRD
+ static func fetchCursor(...) throws -> RecordCursor<Self>
}
extension TypedRequest where RowDecoder: RowConvertible {
- func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseCursor<RowDecoder>
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> RecordCursor<RowDecoder>
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder>
+ func fetchCursor(_ db: Database) throws -> RecordCursor<RowDecoder>
}
extension TypedRequest where RowDecoder: DatabaseValueConvertible {
- func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseCursor<RowDecoder>
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseValueCursor<RowDecoder>
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder>
+ func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder>
}
extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible {
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> ColumnCursor<RowDecoder>
+ func fetchCursor(_ db: Database) throws -> ColumnCursor<RowDecoder>
}
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible {
- func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseCursor<RowDecoder._Wrapped?>
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped>
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder._Wrapped?>
+ func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped>
}
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> NullableColumnCursor<RowDecoder._Wrapped>
+ func fetchCursor(_ db: Database) throws -> NullableColumnCursor<RowDecoder._Wrapped>
}
extension TypedRequest where RowDecoder: Row {
- func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseCursor<Row>
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> RowCursor
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<Row>
+ func fetchCursor(_ db: Database) throws -> RowCursor
}
extension TableMapping {
- @available(*, deprecated) static func primaryKeyRowComparator(_ db: DatabaseBase<some SQLiteAPI>) throws -> (Row, Row) -> Bool
- @available(*, deprecated) static func primaryKeyRowComparator(_ db: Database) throws -> (Row, Row) -> Bool
}
+final class AnyDatabaseReader : DatabaseReader {
@@ -4048,7 +4025,7 @@ Released July 13, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/compare
}
protocol DatabaseReader {
+ func unsafeReentrantRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T
+ func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T
}
```
@@ -4110,7 +4087,7 @@ Released July 1, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/compare/
extension TableMapping {
+ @available(*, deprecated)
static func primaryKeyRowComparator(_ db: DatabaseBase<some SQLiteAPI>) throws -> (Row, Row) -> Bool
static func primaryKeyRowComparator(_ db: Database) throws -> (Row, Row) -> Bool
}
```
@@ -4235,8 +4212,8 @@ It comes with breaking changes, but the good news is that they are the last (unt
}
extension Request {
- func adapted(_ adapter: @escaping (DatabaseBase<some SQLiteAPI>) throws -> RowAdapter) -> AnyRequest
+ func adapted(_ adapter: @escaping (DatabaseBase<some SQLiteAPI>) throws -> RowAdapter) -> AdaptedRequest<Self>
- func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AnyRequest
+ func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedRequest<Self>
}
protocol TypedRequest : Request {
@@ -4245,8 +4222,8 @@ protocol TypedRequest : Request {
}
extension TypedRequest {
- func adapted(_ adapter: @escaping (DatabaseBase<some SQLiteAPI>) throws -> RowAdapter) -> AnyTypedRequest<Fetched>
+ func adapted(_ adapter: @escaping (DatabaseBase<some SQLiteAPI>) throws -> RowAdapter) -> AdaptedTypedRequest<Self>
- func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AnyTypedRequest<Fetched>
+ func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedTypedRequest<Self>
}
```
@@ -4366,7 +4343,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: DatabaseBase<some SQLiteAPI>)` 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: Database)` 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 +4661,19 @@ Many APIs were changed:
}
final class DatabasePool {
- func read<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T
- func nonIsolatedRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T
- func read<T>(_ block: (Database) throws -> T) rethrows -> T
- func nonIsolatedRead<T>(_ block: (Database) throws -> T) rethrows -> T
- func readFromWrite(_ block: @escaping (Database) -> Void)
+ func read<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T
+ func nonIsolatedRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T
+ func read<T>(_ block: (Database) throws -> T) throws -> T
+ func nonIsolatedRead<T>(_ block: (Database) throws -> T) throws -> T
+ func readFromWrite(_ block: @escaping (Database) -> Void) throws
}
protocol DatabaseReader {
- func read<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T
- func nonIsolatedRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T
+ func read<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T
+ func nonIsolatedRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T
- func read<T>(_ block: (Database) throws -> T) rethrows -> T
- func nonIsolatedRead<T>(_ block: (Database) throws -> T) rethrows -> T
+ func read<T>(_ block: (Database) throws -> T) throws -> T
+ func nonIsolatedRead<T>(_ block: (Database) throws -> T) throws -> T
}
protocol DatabaseWriter {
@@ -4747,13 +4724,13 @@ Many APIs were changed:
}
protocol MutablePersistable : TableMapping {
- func exists(_ db: DatabaseBase<some SQLiteAPI>) -> Bool
+ func exists(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
- func exists(_ db: Database) -> Bool
+ func exists(_ db: Database) throws -> Bool
}
extension MutablePersistable {
- func performExists(_ db: DatabaseBase<some SQLiteAPI>) -> Bool
+ func performExists(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
- func performExists(_ db: Database) -> Bool
+ func performExists(_ db: Database) throws -> Bool
}
extension QueryInterfaceRequest {
@@ -4780,8 +4757,8 @@ Many APIs were changed:
}
extension TableMapping {
- static func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) -> Int
+ static func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int
- static func fetchCount(_ db: Database) -> Int
+ static func fetchCount(_ db: Database) throws -> Int
}
```
@@ -4959,7 +4936,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: DatabaseBase<some SQLiteAPI>, didCreate tableName: String, using definition: TableDefinition) throws
+ func database(_ db: Database, didCreate tableName: String, using definition: TableDefinition) throws
}
```
@@ -5032,7 +5009,7 @@ Released September 28, 2016
**Breaking Changes**
- The SQLForeignKeyAction, SQLColumnType, SQLConflictResolution, and SQLCollation types have been renamed Database.ForeignKeyAction, Database.ColumnType, DatabaseConflictResolution, and Database.CollationName.
- The SQLForeignKeyAction, SQLColumnType, SQLConflictResolution, and SQLCollation types have been renamed Database.ForeignKeyAction, Database.ColumnType, Database.ConflictResolution, and Database.CollationName.
## 0.84.0
@@ -5295,8 +5272,8 @@ Released September 11, 2016
- func databaseDidRollback(db: Database)
+ func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
+ func databaseDidChange(with event: DatabaseEvent)
+ func databaseDidCommit(_ db: DatabaseBase<some SQLiteAPI>)
+ func databaseDidRollback(_ db: DatabaseBase<some SQLiteAPI>)
+ func databaseDidCommit(_ db: Database)
+ func databaseDidRollback(_ db: Database)
#if SQLITE_ENABLE_PREUPDATE_HOOK
- func databaseWillChangeWithEvent(event: DatabasePreUpdateEvent)
+ func databaseWillChange(with event: DatabasePreUpdateEvent)
@@ -5319,19 +5296,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: DatabaseBase<some SQLiteAPI>) throws
+ func update(_ db: DatabaseBase<some SQLiteAPI>, columns: Set<String>) throws
+ mutating func save(_ db: DatabaseBase<some SQLiteAPI>) throws
+ @discardableResult func delete(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
+ func exists(_ db: DatabaseBase<some SQLiteAPI>) -> Bool
+ mutating func insert(_ db: Database) throws
+ func update(_ db: Database, columns: Set<String>) throws
+ mutating func save(_ db: Database) throws
+ @discardableResult func delete(_ db: Database) throws -> Bool
+ func exists(_ db: Database) -> 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: DatabaseBase<some SQLiteAPI>) throws
+ func save(_ db: DatabaseBase<some SQLiteAPI>) throws
+ func insert(_ db: Database) throws
+ func save(_ db: Database) throws
}
protocol TableMapping {
- static func databaseTableName() -> String
@@ -5351,10 +5328,10 @@ Released September 11, 2016
+ class var databaseTableName: String
+ func awakeFromFetch(row: Row)
+ func didInsert(with rowID: Int64, for column: String?)
+ func update(_ db: DatabaseBase<some SQLiteAPI>, columns: Set<String>) throws
+ func insert(_ db: DatabaseBase<some SQLiteAPI>) throws
+ func save(_ db: DatabaseBase<some SQLiteAPI>) throws
+ @discardableResult func delete(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
+ func update(_ db: Database, columns: Set<String>) throws
+ func insert(_ db: Database) throws
+ func save(_ db: Database) throws
+ @discardableResult func delete(_ db: Database) throws -> Bool
}
```
@@ -5363,7 +5340,7 @@ Released September 11, 2016
```diff
protocol FetchRequest {
- func prepare(db: Database) throws -> (SelectStatement, RowAdapter?)
+ func prepare(_ db: DatabaseBase<some SQLiteAPI>) throws -> (SelectStatement, RowAdapter?)
+ func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
}
-struct SQLColumn {}
+struct Column {}
@@ -5943,10 +5920,10 @@ Released May 17, 2016
```diff
struct DatabaseMigrator {
- mutating func registerMigration(identifier: String, withDisabledForeignKeyChecks disabledForeignKeyChecks: Bool = false, migrate: (DatabaseBase<some SQLiteAPI>) throws -> Void)
+ mutating func registerMigration(identifier: String, migrate: (DatabaseBase<some SQLiteAPI>) throws -> Void)
- mutating func registerMigration(identifier: String, withDisabledForeignKeyChecks disabledForeignKeyChecks: Bool = false, migrate: (Database) throws -> Void)
+ mutating func registerMigration(identifier: String, migrate: (Database) throws -> Void)
+ @available(iOS 8.2, OSX 10.10, *)
+ mutating func registerMigrationWithDisabledForeignKeyChecks(identifier: String, migrate: (DatabaseBase<some SQLiteAPI>) throws -> Void)
+ mutating func registerMigrationWithDisabledForeignKeyChecks(identifier: String, migrate: (Database) throws -> Void)
```
@@ -158,7 +158,7 @@
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 2600;
LastUpgradeCheck = 1600;
TargetAttributes = {
56CFC6432C9F1DC9000B5023 = {
CreatedOnToolsVersion = 16.0;
@@ -293,7 +293,6 @@
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
@@ -351,7 +350,6 @@
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_EMIT_LOC_STRINGS = YES;
VALIDATE_PRODUCT = YES;
@@ -382,7 +380,7 @@
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.1;
SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
@@ -411,7 +409,7 @@
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.1;
SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
@@ -427,7 +425,7 @@
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 6.1;
SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/GRDBDemo";
};
@@ -444,7 +442,7 @@
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 6.1;
SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/GRDBDemo";
};
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2600"
LastUpgradeVersion = "1600"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
@@ -165,7 +165,7 @@ extension AppDatabase {
}
/// Support for `createRandomPlayersIfEmpty()` and `refreshPlayers()`.
private func createRandomPlayers(_ db: DatabaseBase<some SQLiteAPI>) throws {
private func createRandomPlayers(_ db: Database) throws {
for _ in 0..<8 {
_ = try Player.makeRandom().inserted(db) // insert but ignore inserted id
}
@@ -56,7 +56,7 @@ import GRDB
// Start observing the database.
// Previous observation, if any, is cancelled.
cancellable = observation.start(in: appDatabase.reader, scheduling: .immediate) { error in
cancellable = observation.start(in: appDatabase.reader) { error in
// Handle error
} onChange: { [unowned self] players in
self.players = players
+9 -9
View File
@@ -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: DatabaseBase<some SQLiteAPI>) throws
func insert(_ db: Database) throws
func didInsert(with rowID: Int64, for column: String?)
func update(_ db: DatabaseBase<some SQLiteAPI>, columns: Set<String>) throws
func save(_ db: DatabaseBase<some SQLiteAPI>) throws
func delete(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
func exists(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
func update(_ db: Database, columns: Set<String>) throws
func save(_ db: Database) throws
func delete(_ db: Database) throws -> Bool
func exists(_ db: Database) 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: DatabaseBase<some SQLiteAPI>) throws {
func insert(_ db: Database) throws {
try validate()
try performInsert(db)
}
func update(_ db: DatabaseBase<some SQLiteAPI>, columns: Set<String>) throws {
func update(_ db: Database, columns: Set<String>) 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: DatabaseBase<some SQLiteAPI>) throws {
func willSave(_ db: Database) 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: DatabaseBase<some SQLiteAPI>) throws {
override func willSave(_ db: Database) throws {
try super.willSave(db)
if url.host == nil {
throw ValidationError("url must be absolute.")
@@ -40,12 +40,12 @@ class TableChangeObserver : NSObject, TransactionObserver {
changedTableNames.insert(event.tableName)
}
func databaseDidCommit(_ db: DatabaseBase<some SQLiteAPI>) {
func databaseDidCommit(_ db: Database) {
print("Changed table(s): \(changedTableNames.joined(separator: ", "))")
changedTableNames = []
}
func databaseDidRollback(_ db: DatabaseBase<some SQLiteAPI>) {
func databaseDidRollback(_ db: Database) {
changedTableNames = []
}
}
+3 -3
View File
@@ -123,7 +123,7 @@ Columns are special expressions that allow some optimizations and niceties:
```swift
protocol DatabaseRegionConvertible {
func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
func databaseRegion(_ db: Database) throws -> DatabaseRegion
}
```
@@ -207,10 +207,10 @@ protocol FetchRequest<RowDecoder>: SQLSubqueryable, DatabaseRegionConvertible {
associatedtype RowDecoder
/// Returns a PreparedRequest that is ready to be executed.
func makePreparedRequest(_ db: DatabaseBase<some SQLiteAPI>, forSingleResult singleResult: Bool) throws -> PreparedRequest
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
/// Returns the number of rows fetched by the request.
func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int
func fetchCount(_ db: Database) throws -> Int
}
```
+1 -1
View File
@@ -204,7 +204,7 @@ Let's extend Player with database methods.
```swift
extension Player {
/// Deletes all player with no score
static func deleteAllWithoutScore(_ db: DatabaseBase<some SQLiteAPI>) throws {
static func deleteAllWithoutScore(_ db: Database) throws {
try db.execute(literal: "DELETE FROM \(self) WHERE \(CodingKeys.score) IS NULL")
}
}
+3 -3
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '7.8.0'
s.version = '7.6.1'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
@@ -9,7 +9,7 @@ Pod::Spec.new do |s|
s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" }
s.module_name = 'GRDB'
s.swift_versions = ['6.1']
s.swift_versions = ['6']
s.ios.deployment_target = '13.0'
s.osx.deployment_target = '10.15'
s.watchos.deployment_target = '7.0'
@@ -21,7 +21,7 @@ Pod::Spec.new do |s|
ss.framework = 'Foundation'
ss.library = 'sqlite3'
ss.xcconfig = {
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_ENABLE_FTS5 -D GRDBFRAMEWORK',
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_ENABLE_FTS5',
}
end
+1 -18
View File
@@ -81,7 +81,6 @@
56256ED025D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; };
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; };
562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
562822FA2E631F2100B5A627 /* DatabaseSchemaSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */; };
562B58CB2A29BBEF00E8C75D /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */; };
562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
562EA82F1F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
@@ -224,7 +223,6 @@
568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */; };
56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */; };
568515A42E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */; };
5685C1932AD52EE600DA4B7A /* ListDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */; };
56894F752606576600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F742606576600268F4D /* FoundationDecimalTests.swift */; };
56894FB72606589700268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.swift */; };
@@ -290,7 +288,6 @@
56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */; };
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B81DA51D0A0002DA19 /* FTS5Pattern.swift */; };
56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */; };
56BCA2622E6C28F800E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */; };
56BF2282241781C5003D86EB /* UtilsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF2281241781C5003D86EB /* UtilsTests.swift */; };
56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */; };
56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */; };
@@ -506,7 +503,6 @@
56256ECF25D1ACD0008C2BDD /* Table.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = "<group>"; };
56256ED825D1B316008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = "<group>"; };
562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSource.swift; sourceTree = "<group>"; };
562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = "<group>"; };
562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = "<group>"; };
@@ -678,7 +674,6 @@
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
56848972242DE36F002F9702 /* ValueObservationScheduler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationScheduler.swift; sourceTree = "<group>"; };
568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordMappedOnMutableViewTests.swift; sourceTree = "<group>"; };
5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ListDumpFormat.swift; sourceTree = "<group>"; };
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
56894F742606576600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = "<group>"; };
@@ -797,7 +792,6 @@
56B964C11DA521450002DA19 /* FTS5RecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5RecordTests.swift; sourceTree = "<group>"; };
56B964C21DA521450002DA19 /* FTS5TableBuilderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TableBuilderTests.swift; sourceTree = "<group>"; };
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdog.swift; sourceTree = "<group>"; };
56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSourceTests.swift; sourceTree = "<group>"; };
56BF2281241781C5003D86EB /* UtilsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UtilsTests.swift; sourceTree = "<group>"; };
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSavepointTests.swift; sourceTree = "<group>"; };
56C48E731C9A9923005DF1D9 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = "<group>"; };
@@ -1003,7 +997,6 @@
56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */,
563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */,
563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */,
568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */,
);
name = PersistableRecord;
sourceTree = "<group>";
@@ -1493,7 +1486,6 @@
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */,
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */,
568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */,
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */,
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */,
@@ -1600,7 +1592,6 @@
569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */,
564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */,
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */,
566A84192041146100E50BFD /* DatabaseSnapshot.swift */,
568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */,
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
@@ -1851,9 +1842,8 @@
DC3773EA19C8CBB3004FCF85 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = YES;
LastSwiftUpdateCheck = 0730;
LastUpgradeCheck = 2600;
LastUpgradeCheck = 1400;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
56E5D7F81B4D422D00430942 = {
@@ -2019,7 +2009,6 @@
56677C15241D14450050755D /* FailureTestCase.swift in Sources */,
5615B289222B17C000061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
568515A42E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */,
5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */,
56D496601D81304E008276D7 /* FoundationNSUUIDTests.swift in Sources */,
567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
@@ -2124,7 +2113,6 @@
D263F40A26C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift in Sources */,
5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */,
56D496861D813147008276D7 /* UpdateStatementTests.swift in Sources */,
56BCA2622E6C28F800E4F08D /* DatabaseSchemaSourceTests.swift in Sources */,
56D4965D1D81304E008276D7 /* FoundationNSNumberTests.swift in Sources */,
56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */,
56D496C11D81373A008276D7 /* DatabaseQueueBackupTests.swift in Sources */,
@@ -2219,7 +2207,6 @@
566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
56CEB4FA1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
562822FA2E631F2100B5A627 /* DatabaseSchemaSource.swift in Sources */,
56D110CE28AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */,
563082E42430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */,
564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
@@ -2552,7 +2539,6 @@
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_MODULE_VERIFIER = YES;
INFOPLIST_FILE = Support/Info.plist;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
@@ -2560,7 +2546,6 @@
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11";
SKIP_INSTALL = YES;
SUPPORTED_PLATFORMS = "watchsimulator watchos macosx iphonesimulator iphoneos driverkit appletvsimulator appletvos";
SUPPORTS_MACCATALYST = YES;
@@ -2585,7 +2570,6 @@
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_MODULE_VERIFIER = YES;
INFOPLIST_FILE = Support/Info.plist;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
@@ -2593,7 +2577,6 @@
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11";
SKIP_INSTALL = YES;
SUPPORTED_PLATFORMS = "watchsimulator watchos macosx iphonesimulator iphoneos driverkit appletvsimulator appletvos";
SUPPORTS_MACCATALYST = YES;
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2600"
LastUpgradeVersion = "1400"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
+15 -34
View File
@@ -1,14 +1,11 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
#if !canImport(Darwin)
@preconcurrency
@@ -90,7 +87,7 @@ public struct Configuration: Sendable {
/// with the number of snapshots.
///
/// The default configuration label is nil.
public var label: String?
public var label: String? = nil
/// A boolean value indicating whether SQLite 3.29+ interprets
/// double-quoted strings as string literals when they does not match any
@@ -201,7 +198,7 @@ public struct Configuration: Sendable {
// MARK: - Managing SQLite Connections
private var setups: [@Sendable (DatabaseBase<some SQLiteAPI>) throws -> Void] = []
private var setups: [@Sendable (Database) throws -> Void] = []
/// Defines a function to run whenever an SQLite connection is opened.
///
@@ -238,7 +235,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 (DatabaseBase<some SQLiteAPI>) throws -> Void) {
public mutating func prepareDatabase(_ setup: @escaping @Sendable (Database) throws -> Void) {
setups.append(setup)
}
@@ -332,7 +329,7 @@ public struct Configuration: Sendable {
/// The behavior in case of SQLITE_BUSY error, for read-only connections.
/// If nil, GRDB picks a default one.
var readonlyBusyMode: Database.BusyMode?
var readonlyBusyMode: Database.BusyMode? = nil
/// The maximum number of concurrent reader connections.
///
@@ -390,7 +387,7 @@ public struct Configuration: Sendable {
/// ``qos`` property.
///
/// The default is nil.
public var targetQueue: DispatchQueue?
public var targetQueue: DispatchQueue? = nil
/// The target dispatch queue for write database accesses.
///
@@ -398,7 +395,7 @@ public struct Configuration: Sendable {
/// by ``targetQueue``.
///
/// The default is nil.
public var writeTargetQueue: DispatchQueue?
public var writeTargetQueue: DispatchQueue? = nil
#if os(iOS)
/// A boolean value indicating whether the database connection releases
@@ -424,22 +421,6 @@ public struct Configuration: Sendable {
/// reveals that a lot of time is spent opening new SQLite connections.
public var persistentReadOnlyConnections = false
// MARK: - Database Schema
/// A custom schema source.
///
/// The use case for a custom schema source is enabling GRDB features that
/// would not work with the built-in schema introspection that is provided
/// by SQLite. For example, a custom schema source can help record types
/// that read or write in a database view.
///
/// The schema source is automatically disabled during database
/// migrations performed by ``DatabaseMigrator``: those access the raw
/// SQLite schema, unaltered. If a migration needs a schema source,
/// you may call ``Database/withSchemaSource(_:execute:)`` from within
/// the body of a migration.
public var schemaSource: (any DatabaseSchemaSource)?
// MARK: - Factory Configuration
/// Creates a factory configuration.
@@ -481,7 +462,7 @@ public struct Configuration: Sendable {
return threadingMode.SQLiteOpenFlags | flags
}
func setUp(_ db: DatabaseBase<some SQLiteAPI>) throws {
func setUp(_ db: Database) throws {
for f in setups {
try f(db)
}
File diff suppressed because it is too large. Load diff
+21 -24
View File
@@ -1,18 +1,15 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
extension DatabaseBase {
extension Database {
// MARK: - Statements
@@ -390,7 +387,7 @@ extension SQLStatementCursor: Cursor {
let baseAddress = buffer.baseAddress! // never nil because the buffer contains the trailing \0.
// Compile next statement
var statementEnd: UnsafePointer<CChar>?
var statementEnd: UnsafePointer<CChar>? = nil
let statement = try Statement(
database: database,
statementStart: baseAddress + offset,
@@ -434,10 +431,10 @@ extension SQLStatementCursor: Cursor {
}
}
extension DatabaseBase {
extension Database {
/// Makes sure statement can be executed, and prepares database observation.
@usableFromInline
func statementWillExecute(_ statement: StatementBase<API>) throws {
func statementWillExecute(_ statement: Statement) 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 +455,7 @@ extension DatabaseBase {
/// May throw a cancelled commit error, if a transaction observer cancels
/// an empty transaction.
@usableFromInline
func statementDidExecute(_ statement: StatementBase<API>) throws {
func statementDidExecute(_ statement: Statement) throws {
if statement.invalidatesDatabaseSchemaCache {
clearSchemaCache()
}
@@ -471,7 +468,7 @@ extension DatabaseBase {
/// Always throws an error
@usableFromInline
func statementDidFail(_ statement: StatementBase<API>, withResultCode resultCode: CInt) throws -> Never {
func statementDidFail(_ statement: Statement, 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 +531,15 @@ extension DatabaseBase {
}
/// A thread-unsafe statement cache
struct StatementCache<API: SQLiteAPI> {
unowned let db: DatabaseBase<API>
private var statements: [String: StatementBase<API>] = [:]
struct StatementCache {
unowned let db: Database
private var statements: [String: Statement] = [:]
init(database: DatabaseBase<API>) {
init(database: Database) {
self.db = database
}
mutating func statement(_ sql: String) throws -> StatementBase<API> {
mutating func statement(_ sql: String) throws -> Statement {
if let statement = statements[sql] {
return statement
}
@@ -562,11 +559,11 @@ struct StatementCache<API: SQLiteAPI> {
statements = [:]
}
mutating func remove(_ statement: StatementBase<API>) {
mutating func remove(_ statement: Statement) {
statements.removeFirst { $0.value === statement }
}
mutating func removeAll(where shouldBeRemoved: (StatementBase<API>) -> Bool) {
mutating func removeAll(where shouldBeRemoved: (Statement) -> Bool) {
statements = statements.filter { (_, statement) in !shouldBeRemoved(statement) }
}
}
+65 -145
View File
@@ -1,14 +1,11 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
@@ -116,11 +113,6 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``resumeNotification``
/// - ``suspendNotification``
///
/// ### The Schema Source
///
/// - ``schemaSource``
/// - ``withSchemaSource(_:execute:)``
///
/// ### Other Database Operations
///
/// - ``add(tokenizer:)``
@@ -142,7 +134,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``StorageClass``
/// - ``TraceEvent``
/// - ``TracingOptions``
public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, CustomDebugStringConvertible {
public final class Database: CustomStringConvertible, CustomDebugStringConvertible {
// The Database class is not thread-safe. An instance should always be
// used through a SerializedDatabase.
@@ -177,7 +169,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
/// connection has been opened is an SQLite misuse, and has no effect.
///
/// Related SQLite documentation: <https://www.sqlite.org/errlog.html>
nonisolated(unsafe) public static var logError: LogErrorFunction? {
nonisolated(unsafe) public static var logError: LogErrorFunction? = nil {
didSet {
if logError != nil {
_registerErrorLogCallback { (_, code, message) in
@@ -195,19 +187,6 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
/// The database configuration.
public let configuration: Configuration
/// The current schema source.
///
/// By default, it is the ``Configuration/schemaSource``
/// of ``configuration``. To modify the schema source,
/// use ``withSchemaSource(_:execute:)``.
///
/// The schema source is automatically disabled (nil) during database
/// migrations performed by ``DatabaseMigrator``: those access the raw
/// SQLite schema, unaltered. If a migration needs a schema source,
/// you may call ``Database/withSchemaSource(_:execute:)`` from within
/// the body of a migration.
public internal(set) var schemaSource: (any DatabaseSchemaSource)?
/// A description of this database connection.
///
/// The returned string is based on the ``Configuration/label``
@@ -315,7 +294,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
///
/// It is nil in read-only connections, because we do not report read-only
/// transactions to transaction observers.
private(set) var observationBroker: DatabaseObservationBroker<API>?
private(set) var observationBroker: DatabaseObservationBroker?
/// The list of compile options used when building SQLite
static func sqliteCompileOptions() throws -> Set<String> {
@@ -463,7 +442,6 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
self.description = description
self.configuration = configuration
self.schemaSource = configuration.schemaSource
self.path = path
// We do not report read-only transactions to transaction observers, so
@@ -481,7 +459,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
private static func openConnection(path: String, flags: CInt) throws -> SQLiteConnection {
// See <https://www.sqlite.org/c3ref/open.html>
var sqliteConnection: SQLiteConnection?
var sqliteConnection: SQLiteConnection? = nil
let code = sqlite3_open_v2(path, &sqliteConnection, flags, nil)
guard code == SQLITE_OK else {
// https://www.sqlite.org/c3ref/open.html
@@ -828,7 +806,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
collationPointer,
{ (collationPointer, length1, buffer1, length2, buffer2) in
let collation = Unmanaged<DatabaseCollation>.fromOpaque(collationPointer!).takeUnretainedValue()
return collation.xCompare(length1, buffer1.unsafelyUnwrapped, length2, buffer2.unsafelyUnwrapped)
return CInt(collation.function(length1, buffer1, length2, buffer2).rawValue)
}, nil)
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
@@ -1308,7 +1286,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
// Don't return String.fetchOne(self, sql: "PRAGMA journal_mode"), so
// that we don't create an infinite loop in checkForSuspensionViolation(from:)
var statement: SQLiteStatement?
var statement: SQLiteStatement? = nil
let sql = "PRAGMA journal_mode"
sqlite3_prepare_v2(sqliteConnection, sql, -1, &statement, nil)
defer { sqlite3_finalize(statement) }
@@ -1491,7 +1469,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
/// either ``TransactionCompletion/commit`` or ``TransactionCompletion/rollback``.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the
/// error thrown by `operations`.
public func inTransaction(_ kind: DatabaseTransactionKind? = nil, _ operations: () throws -> DatabaseTransactionCompletion) throws {
public func inTransaction(_ kind: TransactionKind? = nil, _ operations: () throws -> TransactionCompletion) throws {
// Begin transaction
try beginTransaction(kind)
@@ -1505,7 +1483,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
// Now that transaction has begun, we'll rollback in case of error.
// But we'll throw the first caught error, so that user knows
// what happened.
var firstError: Error?
var firstError: Error? = nil
let needsRollback: Bool
do {
let completion = try operations()
@@ -1648,7 +1626,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
// Now that savepoint has begun, we'll rollback in case of error.
// But we'll throw the first caught error, so that user knows
// what happened.
var firstError: Error?
var firstError: Error? = nil
let needsRollback: Bool
do {
let completion = try operations()
@@ -1703,7 +1681,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
/// 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: DatabaseTransactionKind? = nil) throws {
public func beginTransaction(_ kind: TransactionKind? = 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
@@ -1766,7 +1744,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
if isInsideTransaction {
try execute(sql: "ROLLBACK TRANSACTION")
}
assert(!isInsideTransaction)
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
}
/// Commits a database transaction.
@@ -1945,10 +1923,10 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
// Explicit non-conformance to Sendable: `Database` must be used from a
// serialized database access dispatch queue (see `SerializedDatabase`).
@available(*, unavailable)
extension DatabaseBase: Sendable { }
extension Database: Sendable { }
#if SQLITE_HAS_CODEC
extension DatabaseBase {
extension Database {
// MARK: - Encryption
@@ -2021,35 +1999,7 @@ extension DatabaseBase {
}
#endif
extension DatabaseBase {
/// Returns the count of changes executed by one statement execution.
func countChanges<T>(_ count: inout Int, forTable tableName: String, updates: () throws -> T) throws -> T {
// Database.changesCount calls sqlite3_changes(), whose documentation says:
//
// > https://sqlite.org/c3ref/changes.html
// > Changes to a view that are intercepted by INSTEAD OF triggers are not counted.
//
// We want to support INSTEAD OF triggers, so we prefer to use
// sqlite3_total_changes() for views.
//
// At the same time, FTS5 has sqlite3_total_changes() report changes
// even when database is not changed (https://github.com/groue/GRDB.swift/issues/1820)
//
// Well, let's do our best:
if try viewExists(tableName) {
let prevCount = totalChangesCount
let result = try updates()
count = totalChangesCount - prevCount
return result
} else {
let result = try updates()
count = changesCount
return result
}
}
}
extension DatabaseBase {
extension Database {
// MARK: - Database-Related Types
@@ -2207,6 +2157,26 @@ extension DatabaseBase {
public static let any = ColumnType(rawValue: "ANY")
}
/// An SQLite conflict resolution.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_conflict.html>
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: <https://www.sqlite.org/foreignkeys.html>
@@ -2393,6 +2363,29 @@ extension DatabaseBase {
}
}
/// A transaction commit, or rollback.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
@frozen
public enum TransactionCompletion: Sendable {
case commit
case rollback
}
/// A transaction kind.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
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 <https://www.sqlite.org/threadsafe.html>.
///
/// - Note: Only the multi-thread mode (`SQLITE_OPEN_NOMUTEX`) is currently
@@ -2416,79 +2409,6 @@ extension DatabaseBase {
}
}
#warning("TODO: export as DatabaseConflictResolution")
/// An SQLite conflict resolution.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_conflict.html>
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: <https://www.sqlite.org/lang_transaction.html>.
@frozen
public enum DatabaseTransactionCompletion: Sendable {
case commit
case rollback
}
#warning("TODO: export as Database.TransactionKind")
/// A transaction kind.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
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)
+24 -31
View File
@@ -1,14 +1,11 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
@@ -56,21 +53,12 @@ public final class DatabaseCollation: Identifiable, Sendable {
}
}
/// Feeds the `xCompare` parameter of sqlite3_create_collation_v2
/// <https://www.sqlite.org/c3ref/create_collation.html>
typealias XCompare = @Sendable (
_ length1: CInt,
_ buffer1: UnsafeRawPointer,
_ length2: CInt,
_ buffer2: UnsafeRawPointer
) -> CInt
/// The identifier of the collation.
public var id: ID { ID(name: name) }
/// The name of the collation.
public let name: String
let xCompare: XCompare
let function: @Sendable (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
/// Creates a collation.
///
@@ -87,16 +75,21 @@ public final class DatabaseCollation: Identifiable, Sendable {
/// - parameters:
/// - name: The collation name.
/// - function: A function that compares two strings.
public convenience init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
self.init(name, xCompare: { (length1, buffer1, length2, buffer2) in
let string1 = String(decoding: UnsafeRawBufferPointer(start: buffer1, count: Int(length1)), as: UTF8.self)
let string2 = String(decoding: UnsafeRawBufferPointer(start: buffer2, count: Int(length2)), as: UTF8.self)
return CInt(function(string1, string2).rawValue)
})
}
init(_ name: String, xCompare: @escaping XCompare) {
public init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
self.name = name
self.xCompare = xCompare
self.function = { (length1, buffer1, length2, buffer2) in
// Buffers are not C strings: they do not end with \0.
let string1 = String(
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped),
length: Int(length1),
encoding: .utf8,
freeWhenDone: false)!
let string2 = String(
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped),
length: Int(length2),
encoding: .utf8,
freeWhenDone: false)!
return function(string1, string2)
}
}
}
+8 -11
View File
@@ -1,14 +1,11 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
+28 -59
View File
@@ -1,14 +1,11 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A custom SQL function or aggregate.
///
@@ -85,43 +82,20 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// such as `Int`, `String`, `Date`, etc. The array is guaranteed to
/// have exactly `argumentCount` elements, provided `argumentCount` is
/// not nil.
public convenience init(
public init(
_ name: String,
argumentCount: Int? = nil,
pure: Bool = false,
function: @escaping @Sendable ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
{
self.init(name, argumentCount: argumentCount, pure: pure) { (argc, argv, context) in
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv[index]!)
}
let result = try function(arguments)
switch result?.databaseValue.storage ?? .null {
case .null:
sqlite3_result_null(context)
case .int64(let int64):
sqlite3_result_int64(context, int64)
case .double(let double):
sqlite3_result_double(context, double)
case .string(let string):
sqlite3_result_text(context, string, -1, SQLITE_TRANSIENT)
case .blob(let data):
data.withUnsafeBytes {
sqlite3_result_blob(context, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
}
}
}
}
init(
_ name: String,
argumentCount: Int? = nil,
pure: Bool = false,
xFunc: @escaping XFunc)
{
self.id = ID(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
self.isPure = pure
self.kind = .function(xFunc)
self.kind = .function { (argc, argv) in
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
}
return try function(arguments)
}
}
/// Creates an SQL aggregate function.
@@ -237,7 +211,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// Calls sqlite3_create_function_v2
/// See <https://sqlite.org/c3ref/create_function.html>
func install(in db: DatabaseBase<some SQLiteAPI>) {
func install(in db: Database) {
// Retain the function definition
let definition = kind.definition
let definitionP = Unmanaged.passRetained(definition).toOpaque()
@@ -264,7 +238,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// Calls sqlite3_create_function_v2
/// See <https://sqlite.org/c3ref/create_function.html>
func uninstall(in db: DatabaseBase<some SQLiteAPI>) {
func uninstall(in db: Database) {
let code = sqlite3_create_function_v2(
db.sqliteConnection,
id.name,
@@ -282,10 +256,11 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
private class FunctionDefinition {
let xFunc: XFunc
init(xFunc: @escaping XFunc)
let compute: (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?
init(compute: @escaping (CInt, UnsafeMutablePointer<OpaquePointer?>?)
throws -> (any DatabaseValueConvertible)?)
{
self.xFunc = xFunc
self.compute = compute
}
}
@@ -308,19 +283,11 @@ public final class DatabaseFunction: Identifiable, Sendable {
}
}
/// Feeds the `xFunc` parameter of sqlite3_create_function_v2
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
typealias XFunc = @Sendable (
_ argc: CInt,
_ argv: UnsafeMutablePointer<OpaquePointer?>,
_ context: OpaquePointer?
) throws -> Void
/// A function kind: an "SQL function" or an "aggregate".
/// See <http://sqlite.org/capi3ref.html#sqlite3_create_function>
private enum Kind: Sendable {
/// A regular function: SELECT f(1)
case function(XFunc)
case function(@Sendable (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
case aggregate(@Sendable () -> any DatabaseAggregate)
@@ -329,8 +296,8 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
var definition: AnyObject {
switch self {
case .function(let xFunc):
return FunctionDefinition(xFunc: xFunc)
case .function(let compute):
return FunctionDefinition(compute: compute)
case .aggregate(let makeAggregate):
return AggregateDefinition(makeAggregate: makeAggregate)
}
@@ -345,7 +312,9 @@ public final class DatabaseFunction: Identifiable, Sendable {
.fromOpaque(sqlite3_user_data(sqliteContext))
.takeUnretainedValue()
do {
try definition.xFunc(argc, argv.unsafelyUnwrapped, sqliteContext)
try DatabaseFunction.report(
result: definition.compute(argc, argv),
in: sqliteContext)
} catch {
DatabaseFunction.report(error: error, in: sqliteContext)
}
@@ -495,7 +464,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
/// }
/// ```
public protocol DatabaseAggregate: GRDBSendableMetatype {
public protocol DatabaseAggregate: SendableMetatype {
/// Creates an aggregate.
///
/// A new instance is created for each aggregation.
+35 -50
View File
@@ -4,8 +4,8 @@ import Foundation
import UIKit
#endif
public final class DatabasePoolBase<API: SQLiteAPI> {
private let writer: SerializedDatabase<API>
public final class DatabasePool {
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 DatabasePoolBase<API: SQLiteAPI> {
}
// @unchecked because of readerPool and suspensionObservers
extension DatabasePoolBase: @unchecked Sendable { }
extension DatabasePool: @unchecked Sendable { }
extension DatabasePoolBase {
extension DatabasePool {
// MARK: - Memory management
@@ -263,7 +263,7 @@ extension DatabasePoolBase {
#endif
}
extension DatabasePoolBase: DatabaseReaderBase {
extension DatabasePool: DatabaseReader {
public func close() throws {
try readerPool?.barrier {
@@ -336,7 +336,7 @@ extension DatabasePoolBase: DatabaseReaderBase {
// MARK: - Reading from Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
public func read<T>(_ value: (Database) throws -> T) throws -> T {
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
@@ -352,7 +352,7 @@ extension DatabasePoolBase: DatabaseReaderBase {
}
public func read<T: Sendable>(
_ value: @Sendable (DatabaseBase<API>) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
@@ -361,13 +361,8 @@ extension DatabasePoolBase: DatabaseReaderBase {
return try await readerPool.get { reader in
try await reader.execute { db in
defer {
// Commit or rollback, but make sure we leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
}
// The block isolation comes from the DEFERRED transaction.
@@ -379,7 +374,7 @@ extension DatabasePoolBase: DatabaseReaderBase {
}
public func asyncRead(
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
@@ -392,13 +387,8 @@ extension DatabasePoolBase: DatabaseReaderBase {
// Second async jump because that's how `Pool.async` has to be used.
reader.async { db in
defer {
// Commit or rollback, but make sure we leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
releaseReader(.reuse)
}
@@ -418,7 +408,7 @@ extension DatabasePoolBase: DatabaseReaderBase {
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
@@ -432,7 +422,7 @@ extension DatabasePoolBase: DatabaseReaderBase {
}
public func unsafeRead<T: Sendable>(
_ value: @Sendable (DatabaseBase<API>) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
@@ -447,7 +437,7 @@ extension DatabasePoolBase: DatabaseReaderBase {
}
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
@@ -475,7 +465,7 @@ extension DatabasePoolBase: DatabaseReaderBase {
}
}
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
if let reader = currentReader {
return try reader.reentrantSync(value)
} else if writer.onValidQueue {
@@ -494,7 +484,7 @@ extension DatabasePoolBase: DatabaseReaderBase {
}
public func spawnConcurrentRead(
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
) {
asyncConcurrentRead(value)
}
@@ -537,7 +527,7 @@ extension DatabasePoolBase: DatabaseReaderBase {
///
/// - parameter value: A function that accesses the database.
public func asyncConcurrentRead(
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
) {
// Check that we're on the writer queue...
writer.execute { db in
@@ -561,13 +551,8 @@ extension DatabasePoolBase: DatabaseReaderBase {
let (reader, releaseReader) = try readerPool.get()
reader.async { db in
defer {
// Commit or rollback, but make sure we leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
releaseReader(.reuse)
}
@@ -684,15 +669,15 @@ extension DatabasePoolBase: DatabaseReaderBase {
// MARK: - WAL Snapshot Transactions
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
/// Returns a long-lived WAL snapshot transaction on a reader connection.
func walSnapshotTransaction() throws -> WALSnapshotTransactionBase<API> {
func walSnapshotTransaction() throws -> WALSnapshotTransaction {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
let (reader, releaseReader) = try readerPool.get()
return try WALSnapshotTransactionBase(onReader: reader, release: { isInsideTransaction in
return try WALSnapshotTransaction(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 +690,7 @@ extension DatabasePoolBase: DatabaseReaderBase {
/// - 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<WALSnapshotTransactionBase<API>, Error>) -> Void
_ completion: @escaping @Sendable (Result<WALSnapshotTransaction, Error>) -> Void
) {
guard let readerPool else {
completion(.failure(DatabaseError.connectionIsClosed()))
@@ -777,22 +762,22 @@ extension DatabasePoolBase: DatabaseReaderBase {
}
}
extension DatabasePoolBase: DatabaseWriterBase {
extension DatabasePool: DatabaseWriter {
// MARK: - Writing in Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func writeWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
try writer.sync(updates)
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: @Sendable (DatabaseBase<API>) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func barrierWriteWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) throws -> T {
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
@@ -802,7 +787,7 @@ extension DatabasePoolBase: DatabaseWriterBase {
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @Sendable (DatabaseBase<API>) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
@@ -832,7 +817,7 @@ extension DatabasePoolBase: DatabaseWriterBase {
}
public func asyncBarrierWriteWithoutTransaction(
_ updates: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
_ updates: @escaping @Sendable (Result<Database, Error>) -> Void
) {
guard let readerPool else {
updates(.failure(DatabaseError.connectionIsClosed()))
@@ -873,7 +858,7 @@ extension DatabasePoolBase: DatabaseWriterBase {
/// - throws: The error thrown by `updates`, or by the wrapping transaction.
public func writeInTransaction(
_ kind: Database.TransactionKind? = nil,
_ updates: (DatabaseBase<API>) throws -> Database.TransactionCompletion)
_ updates: (Database) throws -> Database.TransactionCompletion)
throws
{
try writer.sync { db in
@@ -883,18 +868,18 @@ extension DatabasePoolBase: DatabaseWriterBase {
}
}
public func unsafeReentrantWrite<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(
_ updates: @escaping @Sendable (DatabaseBase<API>) -> Void
_ updates: @escaping @Sendable (Database) -> Void
) {
writer.async(updates)
}
}
extension DatabasePoolBase {
extension DatabasePool {
// MARK: - Snapshots
@@ -950,7 +935,7 @@ extension DatabasePoolBase {
purpose: "snapshot.\(databaseSnapshotCountMutex.increment())")
}
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
/// Creates a database snapshot that allows concurrent accesses to an
/// unchanging database content, as it exists at the moment the snapshot
/// is created.
+28 -38
View File
@@ -4,8 +4,8 @@ import Foundation
import UIKit
#endif
public final class DatabaseQueueBase<API: SQLiteAPI> {
private let writer: SerializedDatabase<API>
public final class DatabaseQueue {
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 DatabaseQueueBase<API: SQLiteAPI> {
}
// @unchecked because of suspensionObservers
extension DatabaseQueueBase: @unchecked Sendable { }
extension DatabaseQueue: @unchecked Sendable { }
extension DatabaseQueueBase {
extension DatabaseQueue {
// MARK: - Memory management
@@ -183,7 +183,7 @@ extension DatabaseQueueBase {
#endif
}
extension DatabaseQueueBase: DatabaseReaderBase {
extension DatabaseQueue: DatabaseReader {
public func close() throws {
try writer.sync { try $0.close() }
}
@@ -225,7 +225,7 @@ extension DatabaseQueueBase: DatabaseReaderBase {
// MARK: - Reading from Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
public func read<T>(_ value: (Database) throws -> T) throws -> T {
try writer.sync { db in
try db.isolated(readOnly: true) {
try value(db)
@@ -234,7 +234,7 @@ extension DatabaseQueueBase: DatabaseReaderBase {
}
public func read<T: Sendable>(
_ value: @Sendable (DatabaseBase<API>) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute { db in
try db.isolated(readOnly: true) {
@@ -244,17 +244,12 @@ extension DatabaseQueueBase: DatabaseReaderBase {
}
public func asyncRead(
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
) {
writer.async { db in
defer {
// Commit or rollback, but make sure we leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
try? db.endReadOnly()
}
@@ -273,28 +268,28 @@ extension DatabaseQueueBase: DatabaseReaderBase {
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (DatabaseBase<API>) throws -> T) rethrows -> T {
public func unsafeRead<T>(_ value: (Database) throws -> T) rethrows -> T {
try writer.sync(value)
}
public func unsafeRead<T: Sendable>(
_ value: @Sendable (DatabaseBase<API>) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute(value)
}
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
) {
writer.async { value(.success($0)) }
}
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<API>) throws -> T) rethrows -> T {
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) rethrows -> T {
try writer.reentrantSync(value)
}
public func spawnConcurrentRead(
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
) {
// Check that we're on the writer queue...
writer.execute { db in
@@ -302,13 +297,8 @@ extension DatabaseQueueBase: DatabaseReaderBase {
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
defer {
// Commit or rollback, but make sure we leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
try? db.endReadOnly()
}
@@ -349,7 +339,7 @@ extension DatabaseQueueBase: DatabaseReaderBase {
}
}
extension DatabaseQueueBase: DatabaseWriterBase {
extension DatabaseQueue: DatabaseWriter {
// MARK: - Writing in Database
/// Wraps database operations inside a database transaction.
@@ -381,7 +371,7 @@ extension DatabaseQueueBase: DatabaseWriterBase {
/// - throws: The error thrown by `updates`, or by the wrapping transaction.
public func inTransaction(
_ kind: Database.TransactionKind? = nil,
_ updates: (DatabaseBase<API>) throws -> Database.TransactionCompletion)
_ updates: (Database) throws -> Database.TransactionCompletion)
throws
{
try writer.sync { db in
@@ -392,29 +382,29 @@ extension DatabaseQueueBase: DatabaseWriterBase {
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func writeWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
try writer.sync(updates)
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: @Sendable (DatabaseBase<API>) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func barrierWriteWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) throws -> T {
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
try writer.sync(updates)
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @Sendable (DatabaseBase<API>) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
public func asyncBarrierWriteWithoutTransaction(
_ updates: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
_ updates: @escaping @Sendable (Result<Database, Error>) -> Void
) {
writer.async { updates(.success($0)) }
}
@@ -453,16 +443,16 @@ extension DatabaseQueueBase: DatabaseWriterBase {
///
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`.
public func inDatabase<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
public func inDatabase<T>(_ updates: (Database) throws -> T) rethrows -> T {
try writer.sync(updates)
}
public func unsafeReentrantWrite<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(
_ updates: @escaping @Sendable (DatabaseBase<API>) -> Void
_ updates: @escaping @Sendable (Database) -> Void
) {
writer.async(updates)
}
@@ -470,7 +460,7 @@ extension DatabaseQueueBase: DatabaseWriterBase {
// MARK: - Temp Copy
extension DatabaseQueueBase {
extension DatabaseQueue {
/// Returns a connection to an in-memory copy of the database at `path`.
///
/// Changes performed on the returned connection do not impact the
+26 -27
View File
@@ -52,8 +52,7 @@ import Dispatch
/// ### Supporting Types
///
/// - ``AnyDatabaseReader``
public protocol DatabaseReaderBase<API>: AnyObject, Sendable {
associatedtype API: SQLiteAPI
public protocol DatabaseReader: AnyObject, Sendable {
/// The database configuration.
var configuration: Configuration { get }
@@ -187,7 +186,7 @@ public protocol DatabaseReaderBase<API>: 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<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T
func read<T>(_ value: (Database) throws -> T) throws -> T
/// Executes read-only database operations, and returns their result after
/// they have finished executing.
@@ -216,7 +215,7 @@ public protocol DatabaseReaderBase<API>: AnyObject, Sendable {
/// database access, or the error thrown by `value`, or
/// `CancellationError` if the task is cancelled.
func read<T: Sendable>(
_ value: @Sendable (DatabaseBase<API>) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T
/// Schedules read-only database operations for execution, and
@@ -246,7 +245,7 @@ public protocol DatabaseReaderBase<API>: 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<DatabaseBase<API>, Error>) -> Void
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
)
/// Executes database operations, and returns their result after they have
@@ -285,7 +284,7 @@ public protocol DatabaseReaderBase<API>: 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<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T
func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -320,7 +319,7 @@ public protocol DatabaseReaderBase<API>: AnyObject, Sendable {
/// database access, or the error thrown by `value`, or
/// `CancellationError` if the task is cancelled.
func unsafeRead<T: Sendable>(
_ value: @Sendable (DatabaseBase<API>) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T
/// Schedules database operations for execution, and returns immediately.
@@ -355,7 +354,7 @@ public protocol DatabaseReaderBase<API>: 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<DatabaseBase<API>, Error>) -> Void
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
)
/// Executes database operations, and returns their result after they have
@@ -399,7 +398,7 @@ public protocol DatabaseReaderBase<API>: 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<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T
func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T
// MARK: - Value Observation
@@ -418,7 +417,7 @@ public protocol DatabaseReaderBase<API>: AnyObject, Sendable {
) -> AnyDatabaseCancellable
}
extension DatabaseReaderBase {
extension DatabaseReader {
// MARK: - Backup
@@ -500,7 +499,7 @@ extension DatabaseReaderBase {
}
#if canImport(Combine)
extension DatabaseReaderBase {
extension DatabaseReader {
// MARK: - Publishing Database Values
/// Returns a publisher that publishes one value and completes.
@@ -532,7 +531,7 @@ extension DatabaseReaderBase {
/// - parameter value: A closure which accesses the database.
public func readPublisher<Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
value: @escaping @Sendable (DatabaseBase<API>) throws -> Output
value: @escaping @Sendable (Database) throws -> Output
) -> DatabasePublishers.Read<Output> {
OnDemandFuture { fulfill in
self.asyncRead { dbResult in
@@ -569,7 +568,7 @@ extension Publisher where Failure == Error {
}
#endif
extension DatabaseReaderBase {
extension DatabaseReader {
// MARK: - Value Observation Support
/// Adding an observation in a read-only database emits only the
@@ -620,17 +619,17 @@ extension DatabaseReaderBase {
///
/// An instance of `AnyDatabaseReader` forwards its operations to an underlying
/// base database reader.
public final class AnyDatabaseReaderBase<API: SQLiteAPI> {
private let base: any DatabaseReader<API>
public final class AnyDatabaseReader {
private let base: any DatabaseReader
/// Creates a new database reader that wraps and forwards operations
/// to `base`.
public init(_ base: any DatabaseReader<API>) {
public init(_ base: any DatabaseReader) {
self.base = base
}
}
extension AnyDatabaseReaderBase: DatabaseReaderBase {
extension AnyDatabaseReader: DatabaseReader {
public var configuration: Configuration {
base.configuration
}
@@ -648,40 +647,40 @@ extension AnyDatabaseReaderBase: DatabaseReaderBase {
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
public func read<T>(_ value: (Database) throws -> T) throws -> T {
try base.read(value)
}
public func read<T: Sendable>(
_ value: @Sendable (DatabaseBase<API>) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await base.read(value)
}
public func asyncRead(
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
) {
base.asyncRead(value)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
try base.unsafeRead(value)
}
public func unsafeRead<T: Sendable>(
_ value: @Sendable (DatabaseBase<API>) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await base.unsafeRead(value)
}
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
) {
base.asyncUnsafeRead(value)
}
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
try base.unsafeReentrantRead(value)
}
@@ -736,20 +735,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<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
public func reentrantRead<T>(_ value: (Database) 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<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
public func unsafeRead<T>(_ value: (Database) 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<DatabaseBase<API>, Error>) -> Void
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
) {
asyncRead(value)
}
+11 -11
View File
@@ -163,7 +163,7 @@ public struct DatabaseRegion: Sendable {
}
/// Returns a region suitable for database observation
func observableRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion {
func observableRegion(_ db: Database) 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: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion {
func canonicalTables(_ db: Database) 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: DatabaseBase<some SQLiteAPI>) throws -> [DatabaseEventKind] {
func impactfulEventKinds(_ db: Database) throws -> [DatabaseEventKind] {
if let tableRegions {
return try tableRegions.flatMap { (table, tableRegion) -> [DatabaseEventKind] in
let tableName = table.rawValue // canonical table name
@@ -256,8 +256,8 @@ extension DatabaseRegion {
}
} else {
// full database
return try db.fetchSchemaIdentifiers().flatMap { schemaID in
let schema = try db.schema(schemaID)
return try db.schemaIdentifiers().flatMap { schemaIdentifier in
let schema = try db.schema(schemaIdentifier)
return try schema.objects
.filter { $0.type == .table }
.flatMap { table in
@@ -420,7 +420,7 @@ public protocol DatabaseRegionConvertible: Sendable {
/// Returns a database region.
///
/// - parameter db: A database connection.
func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
func databaseRegion(_ db: Database) throws -> DatabaseRegion
}
extension DatabaseRegionConvertible where Self == DatabaseRegion {
@@ -430,16 +430,16 @@ extension DatabaseRegionConvertible where Self == DatabaseRegion {
}
extension DatabaseRegion: DatabaseRegionConvertible {
public func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion {
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
self
}
}
/// A type-erased DatabaseRegionConvertible
public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
let _region: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
let _region: @Sendable (Database) throws -> DatabaseRegion
public init(_ region: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion) {
public init(_ region: @escaping @Sendable (Database) throws -> DatabaseRegion) {
_region = region
}
@@ -447,7 +447,7 @@ public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
_region = { try region.databaseRegion($0) }
}
public func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion {
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
try _region(db)
}
}
@@ -461,7 +461,7 @@ extension DatabaseRegion {
}
}
static func union<API: SQLiteAPI>(_ regions: [any DatabaseRegionConvertible]) -> @Sendable (DatabaseBase<API>) throws -> DatabaseRegion {
static func union(_ regions: [any DatabaseRegionConvertible]) -> @Sendable (Database) throws -> DatabaseRegion {
return { db in
try regions.reduce(into: DatabaseRegion()) { union, region in
try union.formUnion(region.databaseRegion(db))
+9 -13
View File
@@ -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 (DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
var observedRegion: @Sendable (Database) 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 (DatabaseBase<some SQLiteAPI>) -> Void)
onChange: @escaping @Sendable (Database) -> Void)
-> AnyDatabaseCancellable
{
let stateMutex = Mutex(ObservationState.pending)
@@ -146,12 +146,12 @@ extension DatabaseRegionObservation {
}
#endif
private class DatabaseRegionObserver: TransactionObserverBase {
private class DatabaseRegionObserver: TransactionObserver {
let region: DatabaseRegion
let onChange: @Sendable (DatabaseBase<some SQLiteAPI>) -> Void
let onChange: @Sendable (Database) -> Void
var isChanged = false
init(region: DatabaseRegion, onChange: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) -> Void) {
init(region: DatabaseRegion, onChange: @escaping @Sendable (Database) -> Void) {
self.region = region
self.onChange = onChange
}
@@ -172,14 +172,14 @@ private class DatabaseRegionObserver: TransactionObserverBase {
}
}
func databaseDidCommit(_ db: DatabaseBase<some SQLiteAPI>) {
func databaseDidCommit(_ db: Database) {
guard isChanged else { return }
isChanged = false
onChange(db)
}
func databaseDidRollback(_ db: DatabaseBase<some SQLiteAPI>) {
func databaseDidRollback(_ db: Database) {
isChanged = false
}
}
@@ -201,11 +201,7 @@ extension DatabasePublishers {
self.observation = observation
}
public func receive<S>(subscriber: S)
where S: Subscriber & GRDBSendableMetatype,
Failure == S.Failure,
Output == S.Input
{
public func receive<S>(subscriber: S) where S: Subscriber & SendableMetatype, Failure == S.Failure, Output == S.Input {
let subscription = DatabaseRegionSubscription(
writer: writer,
observation: observation,
@@ -216,7 +212,7 @@ extension DatabasePublishers {
private class DatabaseRegionSubscription<Downstream>:
Subscription, @unchecked Sendable
where Downstream: Subscriber & GRDBSendableMetatype,
where Downstream: Subscriber & SendableMetatype,
Downstream.Failure == Error,
Downstream.Input == Database
{
-218
View File
@@ -1,218 +0,0 @@
/// A type that provides information about the database schema.
///
/// ## Overview
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
/// The use case for a custom schema source is to enable GRDB features that
/// would not work with the built-in schema introspection provided
/// by SQLite.
///
/// For example, if your database schema contains a view and you wish to use
/// GRDB features that need a primary key, such as the
/// ``FetchableRecord/find(_:id:)`` record method, or the persistence
/// methods of the ``PersistableRecord`` protocol, then use a schema source
/// that implements the ``columnsForPrimaryKey(_:inView:)`` method. See
/// <doc:ViewRecords> for a detailed guide about such views.
///
/// ## Enabling a Schema Source
///
/// To enable a schema source in a database connection, configure its
/// ``Configuration/schemaSource``:
///
/// ```swift
/// struct MySchemaSource: DatabaseSchemaSource { ... }
///
/// var config = Configuration()
/// config.schemaSource = MySchemaSource()
/// let dbQueue = try DatabaseQueue(path: "/path/to/db.sqlite", configuration: config)
/// ```
///
/// ## Schema Sources and Migrations
///
/// By default, schema sources are disabled during <doc:Migrations>. In
/// migrations that need a schema source, you can use
/// ``Database/withSchemaSource(_:execute:)``:
///
/// ```swift
/// migrator.registerMigration("My migration") { db in
/// // No schema source is enabled at this point.
/// try db.withSchemaSource(MySchemaSource()) {
/// // Here the provided schema source is in effect.
/// }
/// }
/// ```
///
/// Take care that **a good migration is a migration that is never
/// modified once it has shipped**: check
/// <doc:Migrations#Good-Practices-for-Defining-Migrations>.
///
/// ## Topics
///
/// ### Customizing the Database Schema
///
/// - ``columnsForPrimaryKey(_:inView:)``
///
/// ### Chaining Schema Sources
///
/// - ``then(_:)``
public protocol DatabaseSchemaSource: Sendable {
/// Returns the names of the columns for the primary key in the
/// provided database view.
///
/// Return `nil` if no customization should happen. Return an empty
/// array to specify that the view has no primary key. The default
/// implementation returns `nil`.
///
/// In your implementation, make sure that the returned columns define
/// a genuine **primary key**:
///
/// - All columns exist in the provided view.
/// - The set of columns reliably identifies and distinguishes between
/// each individual row in the view.
/// - No column contains NULL values.
///
/// It is a programmer error with undefined consequences to miss
/// those requirements.
///
/// For example:
///
/// ```swift
/// // A schema source that specifies that all views are identified by
/// // their "id" column:
/// struct MySchemaSource: DatabaseSchemaSource {
/// func columnsForPrimaryKey(_ db: DatabaseBase<some SQLiteAPI>, inView view: DatabaseObjectID) {
/// ["id"]
/// }
/// }
///
/// // A database connection configured with the schema source.
/// var config = Configuration()
/// config.schemaSource = MySchemaSource()
/// let dbQueue = try DatabaseQueue(path: "/path/to/db.sqlite", configuration: config)
///
/// // A record type that feeds from a view.
/// struct Player: Decodable, Identifiable, FetchableRecord {
/// static let databaseTableName = "playerView"
/// var id: String
/// var name: String
/// }
///
/// // Thanks to the schema source, we can fetch players by id:
/// let player = try dbQueue.read { db in
/// try Player.find(db, id: "alice")
/// }
/// ```
///
/// ### Schema Sources in Libraries
///
/// When you are developing a schema source for a library, some extra
/// care is necessary whenever the database file is owned by the users
/// of your library. Your users may define views for their own purposes,
/// and your library knows nothing about the eventual primary key of
/// those views.
///
/// In this case, make your schema source `public`, and have this method
/// return `nil` for those unknown views. If needed, use the `db`
/// argument and query the database schema with
/// <doc:DatabaseSchemaIntrospection> methods.
///
/// For example:
///
/// ```swift
/// // 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: DatabaseBase<some SQLiteAPI>, inView view: DatabaseObjectID) {
/// if view.name == "playerView" {
/// // This is a view managed by my library:
/// return ["id"]
/// } else if try db.tableExists(view.name + "MyLibrary") {
/// // This is a view managed by my library:
/// return ["uuid"]
/// } else {
/// // Not a view managed by my library:
/// // don't mess with user's schema
/// return nil
/// }
/// }
/// }
/// ```
///
/// With such a setup, your user will be able to deal with their
/// own views, by chaining your schema source with other ones
/// (see ``DatabaseSchemaSource/then(_:)``):
///
/// ```swift
/// // Application code
/// import MyLibrary
/// import GRDB
///
/// let myLibrarySchemaSource = MyLibrarySchemaSource()
/// let customSchemaSource = TheirCustomSchemaSource()
/// let schemaSource = myLibrarySchemaSource.then(customSchemaSource)
///
/// var config = Configuration()
/// config.schemaSource = schemaSource
/// let dbQueue = try DatabaseQueue(path: "...", configuration: config)
/// ```
///
/// - Parameters:
/// - db: A database connection.
/// - view: The identifier of a database view.
func columnsForPrimaryKey(
_ db: DatabaseBase<some SQLiteAPI>,
inView view: DatabaseObjectID
) throws -> [String]?
}
extension DatabaseSchemaSource {
public func columnsForPrimaryKey(
_ db: DatabaseBase<some SQLiteAPI>,
inView view: DatabaseObjectID
) throws -> [String]? {
nil
}
}
// MARK: - Combined2SchemaSource
extension DatabaseSchemaSource {
/// Returns a schema source that queries `other` when this source does
/// not perform a customization.
///
/// For example:
///
/// ```swift
/// let schemaSource1 = SomeSchemaSource()
/// let schemaSource2 = AnotherSchemaSource()
/// let schemaSource = schemaSource1.then(schemaSource2)
///
/// var config = Configuration()
/// config.schemaSource = schemaSource
/// let dbQueue = try DatabaseQueue(path: "...", configuration: config)
/// ```
public func then(_ other: some DatabaseSchemaSource) -> some DatabaseSchemaSource {
Chained2SchemaSource(first: self, second: other)
}
}
// TODO: move to parameter packs eventually. Parameter packs in generic types
// are only available in macOS 14.0.0 or newer.
// This schema source is designed to tame bad citizens that customize tables
// and views they do not own (such as insufficienly robust schema sources
// exposed by external libraries). We should NEVER MERGE the results of the
// schema sources.
struct Chained2SchemaSource<Source1, Source2>: DatabaseSchemaSource
where Source1: DatabaseSchemaSource,
Source2: DatabaseSchemaSource
{
var first: Source1
var second: Source2
func columnsForPrimaryKey(_ db: DatabaseBase<some SQLiteAPI>, 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
}
}
+9 -14
View File
@@ -113,13 +113,8 @@ public final class DatabaseSnapshot {
deinit {
// Leave snapshot isolation
reader.reentrantSync { db in
// Commit or rollback, but make sure we leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
assert(!db.isInsideTransaction)
}
}
@@ -154,24 +149,24 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
// MARK: - Reading from Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T {
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
try reader.sync(block)
}
public func read<T: Sendable>(
_ value: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await reader.execute(value)
}
public func asyncRead(
_ value: @escaping @Sendable (Result<DatabaseBase<some SQLiteAPI>, Error>) -> Void
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
) {
reader.async { value(.success($0)) }
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T {
public func unsafeRead<T>(_ value: (Database) throws -> T) rethrows -> T {
try reader.sync(value)
}
@@ -180,18 +175,18 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
// `DatabaseSnapshotReader`, because of
// <https://github.com/apple/swift/issues/74469>.
public func unsafeRead<T: Sendable>(
_ value: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await read(value)
}
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<DatabaseBase<some SQLiteAPI>, Error>) -> Void
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
) {
reader.async { value(.success($0)) }
}
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T {
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
try reader.reentrantSync(value)
}
+17 -20
View File
@@ -1,15 +1,12 @@
#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
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#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 +129,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: DatabaseBase<some SQLiteAPI>, configuration: Configuration? = nil) throws {
public init(_ db: Database, configuration: Configuration? = nil) throws {
let path = db.path
var configuration = Self.configure(configuration ?? db.configuration)
@@ -273,7 +270,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ value: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T {
public func read<T>(_ value: (Database) throws -> T) throws -> T {
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
@@ -297,7 +294,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
public func read<T: Sendable>(
_ value: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
@@ -319,7 +316,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
public func asyncRead(
_ value: @escaping @Sendable (Result<DatabaseBase<some SQLiteAPI>, Error>) -> Void
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
@@ -345,12 +342,12 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
// `DatabaseSnapshotReader`, because of
// <https://github.com/apple/swift/issues/74469>.
public func unsafeRead<T: Sendable>(
_ value: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await read(value)
}
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T {
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
if let reader = currentReader {
return try reader.reentrantSync { db in
let result = try value(db)
@@ -399,11 +396,11 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
return readers.first { $0.onValidQueue }
}
private func poolCompletion(_ db: DatabaseBase<some SQLiteAPI>) -> PoolCompletion {
private func poolCompletion(_ db: Database) -> PoolCompletion {
snapshotIsLost(db) ? .discard : .reuse
}
private func snapshotIsLost(_ db: DatabaseBase<some SQLiteAPI>) -> Bool {
private func snapshotIsLost(_ db: Database) -> Bool {
do {
let currentSnapshot = try WALSnapshot(db)
if currentSnapshot.compare(walSnapshot) == 0 {
+10 -13
View File
@@ -1,14 +1,11 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
@@ -162,7 +159,7 @@ public struct DatabaseValue: Hashable {
}
/// Creates a `DatabaseValue` initialized from a raw SQLite statement pointer.
public init(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
public init(sqliteStatement: SQLiteStatement, index: CInt) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_NULL:
storage = .null
@@ -187,7 +184,7 @@ public struct DatabaseValue: Hashable {
}
extension DatabaseValue: StatementBinding {
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
switch storage {
case .null:
return sqlite3_bind_null(sqliteStatement, index)
+17 -17
View File
@@ -80,7 +80,7 @@ extension DatabaseValueConvertible {
.databaseValue(databaseValue)
}
public func bind(to sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, at index: CInt) -> CInt {
public func bind(to sqliteStatement: SQLiteStatement, 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: StatementBase<some SQLiteAPI>,
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> DatabaseValueCursor<Self>
@@ -307,7 +307,7 @@ extension DatabaseValueConvertible {
/// - returns: An array.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ statement: StatementBase<some SQLiteAPI>,
_ statement: Statement,
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: StatementBase<some SQLiteAPI>,
_ statement: Statement,
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: StatementBase<some SQLiteAPI>,
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Set<Self>
@@ -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: DatabaseBase<some SQLiteAPI>,
_ db: Database,
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: DatabaseBase<some SQLiteAPI>,
_ db: Database,
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: DatabaseBase<some SQLiteAPI>,
_ db: Database,
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: DatabaseBase<some SQLiteAPI>,
_ db: Database,
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: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> DatabaseValueCursor<Self> {
public static func fetchCursor(_ db: Database, _ request: some FetchRequest) throws -> DatabaseValueCursor<Self> {
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: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> [Self] {
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchAll(request.statement, adapter: request.adapter)
}
@@ -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: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> Self? {
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
let request = try request.makePreparedRequest(db, forSingleResult: true)
return try fetchOne(request.statement, adapter: request.adapter)
}
@@ -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: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> Set<Self> {
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchSet(request.statement, adapter: request.adapter)
}
@@ -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: DatabaseBase<some SQLiteAPI>) throws -> DatabaseValueCursor<RowDecoder> {
public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder> {
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: DatabaseBase<some SQLiteAPI>) throws -> [RowDecoder] {
public func fetchAll(_ db: Database) 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: DatabaseBase<some SQLiteAPI>) throws -> RowDecoder? {
public func fetchOne(_ db: Database) 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: DatabaseBase<some SQLiteAPI>) throws -> Set<RowDecoder> {
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
try RowDecoder.fetchSet(db, self)
}
}
+32 -32
View File
@@ -61,7 +61,7 @@ import Dispatch
/// ### Supporting Types
///
/// - ``AnyDatabaseWriter``
public protocol DatabaseWriterBase: DatabaseReaderBase {
public protocol DatabaseWriter: DatabaseReader {
// MARK: - Writing in Database
@@ -98,7 +98,7 @@ public protocol DatabaseWriterBase: DatabaseReaderBase {
/// - 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<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T
func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -130,7 +130,7 @@ public protocol DatabaseWriterBase: DatabaseReaderBase {
/// database access, or the error thrown by `updates`, or
/// `CancellationError` if the task is cancelled.
func writeWithoutTransaction<T: Sendable>(
_ updates: @Sendable (DatabaseBase<API>) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T
/// Executes database operations, and returns their result after they have
@@ -171,7 +171,7 @@ public protocol DatabaseWriterBase: DatabaseReaderBase {
/// - 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<T>(_ updates: (DatabaseBase<API>) throws -> T) throws -> T
func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -213,7 +213,7 @@ public protocol DatabaseWriterBase: DatabaseReaderBase {
/// database access, or the error thrown by `updates`, or
/// `CancellationError` if the task is cancelled.
func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @Sendable (DatabaseBase<API>) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T
/// Schedules database operations for execution, and returns immediately.
@@ -256,7 +256,7 @@ public protocol DatabaseWriterBase: DatabaseReaderBase {
/// 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<DatabaseBase<API>, Error>) -> Void
_ updates: @escaping @Sendable (Result<Database, Error>) -> Void
)
/// Schedules database operations for execution, and returns immediately.
@@ -290,7 +290,7 @@ public protocol DatabaseWriterBase: DatabaseReaderBase {
///
/// - parameter updates: A closure which accesses the database.
func asyncWriteWithoutTransaction(
_ updates: @escaping @Sendable (DatabaseBase<API>) -> Void
_ updates: @escaping @Sendable (Database) -> Void
)
/// Executes database operations, and returns their result after they have
@@ -325,7 +325,7 @@ public protocol DatabaseWriterBase: DatabaseReaderBase {
///
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`.
func unsafeReentrantWrite<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T
func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T
// MARK: - Reading from Database
@@ -374,7 +374,7 @@ public protocol DatabaseWriterBase: DatabaseReaderBase {
/// 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<DatabaseBase<API>, Error>) -> Void
_ value: @escaping @Sendable (Result<Database, 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<T>(_ updates: (DatabaseBase<API>) throws -> T) throws -> T {
public func write<T>(_ updates: (Database) 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<T>(
_ updates: @escaping @Sendable (DatabaseBase<API>) throws -> T,
_ updates: @escaping @Sendable (Database) throws -> T,
completion: @escaping @Sendable (Database, Result<T, Error>) -> Void
) {
asyncWriteWithoutTransaction { db in
@@ -502,7 +502,7 @@ extension DatabaseWriter {
/// is deallocated).
public func add(
transactionObserver: some TransactionObserver,
extent: DatabaseTransactionObservationExtent = .observerLifetime)
extent: Database.TransactionObservationExtent = .observerLifetime)
{
writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) }
}
@@ -552,7 +552,7 @@ extension DatabaseWriter {
// This method is declared on DatabaseWriter instead of DatabaseReader,
// so that it is not available on DatabaseSnaphot. VACUUM INTO is not
// available inside the transaction that is kept open by DatabaseSnaphot.
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Creates a new database file at the specified path with a minimum
/// amount of disk space.
///
@@ -640,7 +640,7 @@ extension DatabaseWriter {
/// database access, or the error thrown by `updates`, or
/// `CancellationError` if the task is cancelled.
public func write<T: Sendable>(
_ updates: @Sendable (DatabaseBase<API>) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await writeWithoutTransaction { db in
var result: T?
@@ -665,7 +665,7 @@ extension DatabaseWriter {
try await writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
}
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Creates a new database file at the specified path with a minimum
/// amount of disk space.
///
@@ -733,7 +733,7 @@ extension DatabaseWriter {
/// - parameter updates: A closure which accesses the database.
public func writePublisher<Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
updates: @escaping @Sendable (DatabaseBase<API>) throws -> Output
updates: @escaping @Sendable (Database) throws -> Output
) -> DatabasePublishers.Write<Output> {
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<T: Sendable, Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
updates: @escaping @Sendable (DatabaseBase<API>) throws -> T,
updates: @escaping @Sendable (Database) throws -> T,
thenRead value: @escaping @Sendable (Database, T) throws -> Output
) -> DatabasePublishers.Write<Output> {
OnDemandFuture { fulfill in
@@ -880,40 +880,40 @@ extension AnyDatabaseWriter: DatabaseReader {
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
public func read<T>(_ value: (Database) throws -> T) throws -> T {
try base.read(value)
}
public func read<T: Sendable>(
_ value: @Sendable (DatabaseBase<API>) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await base.read(value)
}
public func asyncRead(
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
) {
base.asyncRead(value)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
try base.unsafeRead(value)
}
public func unsafeRead<T: Sendable>(
_ value: @Sendable (DatabaseBase<API>) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await base.unsafeRead(value)
}
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
) {
base.asyncUnsafeRead(value)
}
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
public func unsafeReentrantRead<T>(_ value: (Database) 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<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
try base.writeWithoutTransaction(updates)
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: @Sendable (DatabaseBase<API>) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await base.writeWithoutTransaction(updates)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func barrierWriteWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) throws -> T {
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
try base.barrierWriteWithoutTransaction(updates)
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @Sendable (DatabaseBase<API>) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await base.barrierWriteWithoutTransaction(updates)
}
public func asyncBarrierWriteWithoutTransaction(
_ updates: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
_ updates: @escaping @Sendable (Result<Database, Error>) -> Void
) {
base.asyncBarrierWriteWithoutTransaction(updates)
}
public func asyncWriteWithoutTransaction(
_ updates: @escaping @Sendable (DatabaseBase<API>) -> Void
_ updates: @escaping @Sendable (Database) -> Void
) {
base.asyncWriteWithoutTransaction(updates)
}
public func unsafeReentrantWrite<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
try base.unsafeReentrantWrite(updates)
}
public func spawnConcurrentRead(
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
) {
base.spawnConcurrentRead(value)
}
-4
View File
@@ -43,7 +43,3 @@ private final class DispatchQueueExecutor: SerialExecutor {
dispatchPrecondition(condition: .onQueue(queue))
}
}
#if os(Linux)
extension DispatchQueueExecutor: @unchecked Sendable {}
#endif
+25 -25
View File
@@ -87,20 +87,20 @@ public protocol FetchRequest<RowDecoder>: SQLSubqueryable, DatabaseRegionConvert
/// - parameter db: A database connection.
/// - parameter singleResult: A hint that a single result row will be
/// consumed.
func makePreparedRequest<API>(_ db: DatabaseBase<API>, forSingleResult singleResult: Bool) throws -> PreparedRequestBase<API>
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
/// 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: DatabaseBase<some SQLiteAPI>) throws -> Int
func fetchCount(_ db: Database) throws -> Int
}
extension FetchRequest {
/// Returns the database region that the request feeds from.
///
/// - parameter db: A database connection.
public func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion {
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
try makePreparedRequest(db, forSingleResult: false).statement.databaseRegion
}
}
@@ -123,28 +123,28 @@ typealias WillExecuteSupplementaryRequest = (_ request: AnyFetchRequest<Row>, _
/// - parameter rows: The rows that are modified by the supplementary fetch.
/// - parameter willExecuteSupplementaryRequest: A closure to execute before
/// performing supplementary fetches.
typealias SupplementaryFetch<API: SQLiteAPI> = (
_ db: DatabaseBase<API>,
typealias SupplementaryFetch = (
_ db: Database,
_ rows: [Row],
_ willExecuteSupplementaryRequest: WillExecuteSupplementaryRequest?)
throws -> Void
/// A `PreparedRequest` is a request that is ready to be executed.
public struct PreparedRequestBase<API: SQLiteAPI> {
public struct PreparedRequest {
/// A prepared statement with bound parameters.
public var statement: StatementBase<API>
public var statement: Statement
/// 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<API>?
var supplementaryFetch: SupplementaryFetch?
init(
statement: StatementBase<API>,
statement: Statement,
adapter: (any RowAdapter)?,
supplementaryFetch: SupplementaryFetch<API>? = 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 (DatabaseBase<some SQLiteAPI>) throws -> any RowAdapter
_ adapter: @escaping @Sendable (Database) throws -> any RowAdapter
) -> AdaptedFetchRequest<Self> {
AdaptedFetchRequest(self, adapter)
}
@@ -183,11 +183,11 @@ extension FetchRequest {
/// See ``FetchRequest/adapted(_:)``.
public struct AdaptedFetchRequest<Base: FetchRequest> {
let base: Base
let adapter: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> any RowAdapter
let adapter: @Sendable (Database) throws -> any RowAdapter
/// Creates an adapted request from a base request and a closure that builds
/// a row adapter from a database connection.
init(_ base: Base, _ adapter: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> any RowAdapter) {
init(_ base: Base, _ adapter: @escaping @Sendable (Database) 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: DatabaseBase<some SQLiteAPI>) throws -> Int {
public func fetchCount(_ db: Database) throws -> Int {
try base.fetchCount(db)
}
public func makePreparedRequest<API>(
_ db: DatabaseBase<API>,
public func makePreparedRequest(
_ db: Database,
forSingleResult singleResult: Bool = false)
throws -> PreparedRequestBase<API>
throws -> PreparedRequest
{
var preparedRequest = try base.makePreparedRequest(db, forSingleResult: singleResult)
@@ -262,14 +262,14 @@ extension AnyFetchRequest: SQLSubqueryable {
}
extension AnyFetchRequest: FetchRequest {
public func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
public func fetchCount(_ db: Database) throws -> Int {
try request.fetchCount(db)
}
public func makePreparedRequest<API>(
_ db: DatabaseBase<API>,
public func makePreparedRequest(
_ db: Database,
forSingleResult singleResult: Bool = false)
throws -> PreparedRequestBase<API>
throws -> PreparedRequest
{
try request.makePreparedRequest(db, forSingleResult: singleResult)
}
@@ -283,11 +283,11 @@ private class FetchRequestEraser: FetchRequest, @unchecked Sendable {
fatalError("subclass must override")
}
func makePreparedRequest<API>(_ db: DatabaseBase<API>, forSingleResult singleResult: Bool) throws -> PreparedRequestBase<API> {
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
fatalError("subclass must override")
}
func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
func fetchCount(_ db: Database) throws -> Int {
fatalError("subclass must override")
}
}
@@ -303,11 +303,11 @@ private final class ConcreteFetchRequestEraser<Request: FetchRequest>: FetchRequ
request.sqlSubquery
}
override func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
override func fetchCount(_ db: Database) throws -> Int {
try request.fetchCount(db)
}
override func makePreparedRequest<API>(_ db: DatabaseBase<API>, forSingleResult singleResult: Bool) throws -> PreparedRequestBase<API> {
override func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
try request.makePreparedRequest(db, forSingleResult: singleResult)
}
}
+28 -31
View File
@@ -1,14 +1,11 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
@@ -234,7 +231,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: StatementBase<some SQLiteAPI>) {
init(statement: Statement) {
self.statement = statement
self.sqliteStatement = statement.sqliteStatement
self.impl = StatementRowImpl(sqliteStatement: statement.sqliteStatement, statement: statement)
@@ -243,7 +240,7 @@ public final class Row {
/// Creates a row that maps an SQLite statement. Further calls to
/// sqlite3_step() modify the row.
init(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>) {
init(sqliteStatement: SQLiteStatement) {
self.statement = nil
self.sqliteStatement = sqliteStatement
self.impl = SQLiteStatementRowImpl(sqliteStatement: sqliteStatement)
@@ -257,8 +254,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: SQLiteStatementBase<some SQLiteAPI>,
statement: StatementBase<some SQLiteAPI>)
copiedFromSQLiteStatement sqliteStatement: SQLiteStatement,
statement: Statement)
{
self.init(impl: StatementCopyRowImpl(
sqliteStatement: sqliteStatement,
@@ -1736,7 +1733,7 @@ extension Row {
/// - returns: A ``RowCursor`` over fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(
_ statement: StatementBase<some SQLiteAPI>,
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> RowCursor
@@ -1764,7 +1761,7 @@ extension Row {
/// - returns: An array of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ statement: StatementBase<some SQLiteAPI>,
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> [Row]
@@ -1793,7 +1790,7 @@ extension Row {
/// - returns: A set of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
_ statement: StatementBase<some SQLiteAPI>,
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Set<Row>
@@ -1822,7 +1819,7 @@ extension Row {
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ statement: StatementBase<some SQLiteAPI>,
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Row?
@@ -1877,7 +1874,7 @@ extension Row {
/// - returns: A ``RowCursor`` over fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(
_ db: DatabaseBase<some SQLiteAPI>,
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -1906,7 +1903,7 @@ extension Row {
/// - returns: An array of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ db: DatabaseBase<some SQLiteAPI>,
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -1935,7 +1932,7 @@ extension Row {
/// - returns: A set of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
_ db: DatabaseBase<some SQLiteAPI>,
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -1964,7 +1961,7 @@ extension Row {
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ db: DatabaseBase<some SQLiteAPI>,
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -2027,7 +2024,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: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> RowCursor {
public static func fetchCursor(_ db: Database, _ 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 +2061,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: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> [Row] {
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Row] {
let request = try request.makePreparedRequest(db, forSingleResult: false)
let rows = try fetchAll(request.statement, adapter: request.adapter)
try request.supplementaryFetch?(db, rows, nil)
@@ -2102,7 +2099,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: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> Set<Row> {
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Row> {
let request = try request.makePreparedRequest(db, forSingleResult: false)
if let supplementaryFetch = request.supplementaryFetch {
let rows = try fetchAll(request.statement, adapter: request.adapter)
@@ -2144,7 +2141,7 @@ extension Row {
/// - request: A fetch request.
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> Row? {
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Row? {
let request = try request.makePreparedRequest(db, forSingleResult: true)
guard let row = try fetchOne(request.statement, adapter: request.adapter) else {
return nil
@@ -2193,7 +2190,7 @@ extension FetchRequest<Row> {
/// - parameter db: A database connection.
/// - returns: A ``RowCursor`` over fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> RowCursor {
public func fetchCursor(_ db: Database) throws -> RowCursor {
try Row.fetchCursor(db, self)
}
@@ -2214,7 +2211,7 @@ extension FetchRequest<Row> {
/// - parameter db: A database connection.
/// - returns: An array of fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: DatabaseBase<some SQLiteAPI>) throws -> [Row] {
public func fetchAll(_ db: Database) throws -> [Row] {
try Row.fetchAll(db, self)
}
@@ -2235,7 +2232,7 @@ extension FetchRequest<Row> {
/// - parameter db: A database connection.
/// - returns: A set of fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: DatabaseBase<some SQLiteAPI>) throws -> Set<Row> {
public func fetchSet(_ db: Database) throws -> Set<Row> {
try Row.fetchSet(db, self)
}
@@ -2256,7 +2253,7 @@ extension FetchRequest<Row> {
/// - parameter db: A database connection.
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: DatabaseBase<some SQLiteAPI>) throws -> Row? {
public func fetchOne(_ db: Database) throws -> Row? {
try Row.fetchOne(db, self)
}
}
+8 -11
View File
@@ -1,14 +1,11 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A key that is used to decode a value in a row
@usableFromInline
+1 -1
View File
@@ -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: DatabaseBase<some SQLiteAPI>) throws -> (sql: String, arguments: StatementArguments) {
public func build(_ db: Database) throws -> (sql: String, arguments: StatementArguments) {
let context = SQLGenerationContext(db)
let sql = try self.sql(context)
return (sql: sql, arguments: context.arguments)
+4 -4
View File
@@ -191,14 +191,14 @@ extension SQLRequest: FetchRequest {
.literal(sqlLiteral)
}
public func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
public func fetchCount(_ db: Database) throws -> Int {
try SQLRequest<Int>("SELECT COUNT(*) FROM (\(self))").fetchOne(db)!
}
public func makePreparedRequest<API>(
_ db: DatabaseBase<API>,
public func makePreparedRequest(
_ db: Database,
forSingleResult singleResult: Bool = false)
throws -> PreparedRequestBase<API>
throws -> PreparedRequest
{
let context = SQLGenerationContext(db)
let sql = try sqlLiteral.sql(context)
-20
View File
@@ -1,20 +0,0 @@
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<CChar>?, _: 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<CChar>?
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<CChar>?, UnsafePointer<CChar>?, Int64) -> Void)?, _: UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer?
}
public typealias sqlite3_destructor_type = @convention(c) (UnsafeMutableRawPointer?) -> Void
+3 -3
View File
@@ -59,7 +59,7 @@ final class SchedulingWatchdog: @unchecked Sendable {
}
static func preconditionValidQueue(
_ db: DatabaseBase<some SQLiteAPI>,
_ db: Database,
_ 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: DatabaseBase<some SQLiteAPI>) -> Bool {
static func allows(_ db: Database) -> Bool {
current?.allows(db) ?? false
}
func allows(_ db: DatabaseBase<some SQLiteAPI>) -> Bool {
func allows(_ db: Database) -> Bool {
allowedDatabases.contains { $0 === db }
}
+10 -10
View File
@@ -1,9 +1,9 @@
import Foundation
/// A class that serializes accesses to an SQLite connection.
final class SerializedDatabaseBase<API: SQLiteAPI> {
final class SerializedDatabase {
/// The database connection
private let db: DatabaseBase<API>
private let db: Database
/// The actor that performs asynchronous accesses
private let actor: DispatchQueueActor
@@ -92,7 +92,7 @@ final class SerializedDatabaseBase<API: SQLiteAPI> {
/// - parameter allowingLongLivedTransaction: When true, the
/// ``Configuration/allowsUnsafeTransactions`` configuration flag is
/// ignored until this method is called again with false.
func sync<T>(allowingLongLivedTransaction: Bool, _ body: (DatabaseBase<API>) throws -> T) rethrows -> T {
func sync<T>(allowingLongLivedTransaction: Bool, _ body: (Database) throws -> T) rethrows -> T {
try sync { db in
self.allowsUnsafeTransactions = allowingLongLivedTransaction
return try body(db)
@@ -103,7 +103,7 @@ final class SerializedDatabaseBase<API: SQLiteAPI> {
/// have finished executing.
///
/// This method is not reentrant.
func sync<T>(_ block: (DatabaseBase<API>) throws -> T) rethrows -> T {
func sync<T>(_ block: (Database) 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 SerializedDatabaseBase<API: SQLiteAPI> {
/// - parameter allowingLongLivedTransaction: When true, the
/// ``Configuration/allowsUnsafeTransactions`` configuration flag is
/// ignored until this method is called again with false.
func reentrantSync<T>(allowingLongLivedTransaction: Bool, _ body: (DatabaseBase<API>) throws -> T) rethrows -> T {
func reentrantSync<T>(allowingLongLivedTransaction: Bool, _ body: (Database) throws -> T) rethrows -> T {
try reentrantSync { db in
self.allowsUnsafeTransactions = allowingLongLivedTransaction
return try body(db)
@@ -164,7 +164,7 @@ final class SerializedDatabaseBase<API: SQLiteAPI> {
/// have finished executing.
///
/// This method is reentrant.
func reentrantSync<T>(_ block: (DatabaseBase<API>) throws -> T) rethrows -> T {
func reentrantSync<T>(_ block: (Database) 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 SerializedDatabaseBase<API: SQLiteAPI> {
}
/// Schedules database operations for execution, and returns immediately.
func async(_ block: @escaping @Sendable (DatabaseBase<API>) -> Void) {
func async(_ block: @escaping @Sendable (Database) -> Void) {
queue.async {
block(self.db)
self.preconditionNoUnsafeTransactionLeft(self.db)
@@ -243,14 +243,14 @@ final class SerializedDatabaseBase<API: SQLiteAPI> {
/// Executes the block in the current queue.
///
/// - precondition: the current dispatch queue is valid.
func execute<T>(_ block: (DatabaseBase<API>) throws -> T) rethrows -> T {
func execute<T>(_ block: (Database) throws -> T) rethrows -> T {
preconditionValidQueue()
return try block(db)
}
/// Asynchrously executes the block.
func execute<T: Sendable>(
_ block: @Sendable (DatabaseBase<API>) throws -> T
_ block: @Sendable (Database) throws -> T
) async throws -> T {
let cancelMutex = Mutex<(@Sendable () -> Void)?>(nil)
return try await withTaskCancellationHandler {
@@ -295,7 +295,7 @@ final class SerializedDatabaseBase<API: SQLiteAPI> {
/// Fatal error if a transaction has been left opened.
private func preconditionNoUnsafeTransactionLeft(
_ db: DatabaseBase<API>,
_ db: Database,
_ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access",
file: StaticString = #file,
line: UInt = #line)
+14 -20
View File
@@ -1,22 +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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A raw SQLite statement, suitable for the SQLite C API.
//public typealias SQLiteStatement = OpaquePointer
public struct SQLiteStatementBase<API: SQLiteAPI> {
public let rawValue: OpaquePointer
}
public typealias SQLiteStatement = OpaquePointer
extension String {
/// SQL statements are separated by semicolons and white spaces.
@@ -40,7 +34,7 @@ extension String {
}
}
public final class StatementBase<API: SQLiteAPI> {
public final class Statement {
enum TransactionEffect: Equatable {
case beginTransaction
case commitTransaction
@@ -51,7 +45,7 @@ public final class StatementBase<API: SQLiteAPI> {
}
/// The raw SQLite statement, suitable for the SQLite C API.
public let sqliteStatement: SQLiteStatementBase<API>
public let sqliteStatement: SQLiteStatement
/// The SQL query.
public var sql: String {
@@ -147,7 +141,7 @@ public final class StatementBase<API: SQLiteAPI> {
let authorizer = database.authorizer
authorizer.reset()
var sqliteStatement: SQLiteStatement?
var sqliteStatement: SQLiteStatement? = nil
let code = sqlite3_prepare_v3(
database.sqliteConnection, statementStart, -1, prepFlags,
&sqliteStatement, statementEnd)
@@ -842,11 +836,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: SQLiteStatementBase<some SQLiteAPI>, at index: CInt) -> CInt
func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt
}
/// Helper function for `withBinding(to:at:do:)` methods.
func checkBindingSuccess(code: CInt, sqliteStatement: SQLiteStatementBase<some SQLiteAPI>) throws {
func checkBindingSuccess(code: CInt, sqliteStatement: SQLiteStatement) throws {
if code == SQLITE_OK { return }
let message = String(cString: sqlite3_errmsg(sqlite3_db_handle(sqliteStatement)))
let sql = String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
+8 -11
View File
@@ -1,14 +1,11 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
#if canImport(string_h)
import string_h
+31 -37
View File
@@ -1,14 +1,11 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A type that can decode itself from the low-level C interface to
/// SQLite results.
@@ -92,10 +89,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<API>(
_ sqliteStatement: SQLiteStatementBase<API>,
atUncheckedIndex index: CInt
) -> Self?
static func fromStatement(
_ sqliteStatement: SQLiteStatement,
atUncheckedIndex index: CInt)
-> Self?
/// Creates an instance from a raw SQLite statement pointer, if possible.
///
@@ -107,7 +104,7 @@ public protocol StatementColumnConvertible {
///
/// ```swift
/// extension Int64: StatementColumnConvertible {
/// public init(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
/// public init(sqliteStatement: SQLiteStatement, index: CInt) {
/// self = sqlite3_column_int64(sqliteStatement, index)
/// }
/// }
@@ -120,7 +117,7 @@ public protocol StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt)
init?(sqliteStatement: SQLiteStatement, index: CInt)
}
extension StatementColumnConvertible {
@@ -128,10 +125,7 @@ extension StatementColumnConvertible {
/// Default implementation fails on decoding NULL.
@inline(__always)
@inlinable
public static func fromStatement<API>(
_ sqliteStatement: SQLiteStatementBase<API>,
atUncheckedIndex index: CInt
) -> Self? {
public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt) -> Self? {
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
return nil
}
@@ -301,7 +295,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: StatementBase<some SQLiteAPI>,
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> FastDatabaseValueCursor<Self>
@@ -332,7 +326,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ statement: StatementBase<some SQLiteAPI>,
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> [Self]
@@ -366,7 +360,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ statement: StatementBase<some SQLiteAPI>,
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Self?
@@ -404,7 +398,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: StatementBase<some SQLiteAPI>,
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Set<Self>
@@ -449,7 +443,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: DatabaseBase<some SQLiteAPI>,
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -481,7 +475,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ db: DatabaseBase<some SQLiteAPI>,
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -516,7 +510,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ db: DatabaseBase<some SQLiteAPI>,
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -550,7 +544,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: DatabaseBase<some SQLiteAPI>,
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -609,7 +603,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: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest)
public static func fetchCursor(_ db: Database, _ request: some FetchRequest)
throws -> FastDatabaseValueCursor<Self>
{
let request = try request.makePreparedRequest(db, forSingleResult: false)
@@ -652,7 +646,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: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> [Self] {
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchAll(request.statement, adapter: request.adapter)
}
@@ -696,7 +690,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: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> Self? {
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
let request = try request.makePreparedRequest(db, forSingleResult: true)
return try fetchOne(request.statement, adapter: request.adapter)
}
@@ -739,7 +733,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: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> Set<Self> {
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchSet(request.statement, adapter: request.adapter)
}
@@ -792,7 +786,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: DatabaseBase<some SQLiteAPI>) throws -> FastDatabaseValueCursor<RowDecoder> {
public func fetchCursor(_ db: Database) throws -> FastDatabaseValueCursor<RowDecoder> {
try RowDecoder.fetchCursor(db, self)
}
@@ -830,7 +824,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: DatabaseBase<some SQLiteAPI>) throws -> [RowDecoder] {
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
try RowDecoder.fetchAll(db, self)
}
@@ -871,7 +865,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: DatabaseBase<some SQLiteAPI>) throws -> RowDecoder? {
public func fetchOne(_ db: Database) throws -> RowDecoder? {
try RowDecoder.fetchOne(db, self)
}
}
@@ -911,7 +905,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: DatabaseBase<some SQLiteAPI>) throws -> Set<RowDecoder> {
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
try RowDecoder.fetchSet(db, self)
}
}
+10 -13
View File
@@ -1,20 +1,17 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// Data is convertible to and from DatabaseValue.
extension Data: DatabaseValueConvertible, StatementColumnConvertible {
public init(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
public init(sqliteStatement: SQLiteStatement, 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 +46,7 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
}
}
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
withUnsafeBytes {
sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
}
@@ -1,14 +1,11 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
@@ -81,7 +78,7 @@ extension DatabaseDateComponents: StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
guard let cString = sqlite3_column_text(sqliteStatement, index) else {
return nil
}
+9 -12
View File
@@ -1,14 +1,11 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
@@ -136,7 +133,7 @@ extension Date: StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_INTEGER, SQLITE_FLOAT:
self.init(timeIntervalSince1970: sqlite3_column_double(sqliteStatement, index))
+9 -12
View File
@@ -1,15 +1,12 @@
#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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
@@ -50,7 +47,7 @@ extension Decimal: DatabaseValueConvertible {
extension Decimal: StatementColumnConvertible {
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_INTEGER:
self.init(sqlite3_column_int64(sqliteStatement, index))
+9 -12
View File
@@ -1,14 +1,11 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
@@ -81,7 +78,7 @@ extension UUID: DatabaseValueConvertible {
extension UUID: StatementColumnConvertible {
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_TEXT:
let string = String(cString: sqlite3_column_text(sqliteStatement, index)!)
@@ -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: SQLiteStatementBase<some SQLiteAPI>, at index: CInt) -> CInt {
public func bind(to sqliteStatement: SQLiteStatement, 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: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
guard let rawValue = RawValue(sqliteStatement: sqliteStatement, index: index) else {
return nil
}
@@ -1,20 +1,17 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
extension Optional: StatementBinding where Wrapped: StatementBinding {
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
switch self {
case .none:
return API.sqlite3_bind_null(sqliteStatement.rawValue, index)
return sqlite3_bind_null(sqliteStatement, index)
case let .some(value):
return value.bind(to: sqliteStatement, at: index)
}
@@ -87,11 +84,11 @@ extension Optional: DatabaseValueConvertible where Wrapped: DatabaseValueConvert
extension Optional: StatementColumnConvertible where Wrapped: StatementColumnConvertible {
@inline(__always)
@inlinable
public static func fromStatement<API>(_ sqliteStatement: SQLiteStatementBase<API>, atUncheckedIndex index: CInt) -> Self? {
public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt) -> Self? {
if let value = Wrapped.fromStatement(sqliteStatement, atUncheckedIndex: index) {
// Valid value
return value
} else if API.sqlite3_column_type(sqliteStatement.rawValue, index) == API.SQLITE_NULL {
} else if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
// NULL
return .some(.none)
} else {
@@ -100,7 +97,7 @@ extension Optional: StatementColumnConvertible where Wrapped: StatementColumnCon
}
}
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
guard let value = Wrapped(sqliteStatement: sqliteStatement, index: index) else {
return nil
}
@@ -1,14 +1,11 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
// MARK: - Value Types
@@ -20,8 +17,8 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
self = API.sqlite3_column_int64(sqliteStatement.rawValue, index) != 0
public init(sqliteStatement: SQLiteStatement, index: CInt) {
self = sqlite3_column_int64(sqliteStatement, index) != 0
}
/// Returns an INTEGER database value.
@@ -102,8 +99,8 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
}
}
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, self ? 1 : 0)
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, self ? 1 : 0)
}
}
@@ -117,8 +114,8 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
guard let v = Int(exactly: int64) else { return nil }
self = v
}
@@ -141,8 +138,8 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { Int(exactly: $0) }
}
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
}
}
@@ -156,8 +153,8 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
guard let v = Int8(exactly: int64) else { return nil }
self = v
}
@@ -180,8 +177,8 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { Int8(exactly: $0) }
}
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
}
}
@@ -195,8 +192,8 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
guard let v = Int16(exactly: int64) else { return nil }
self = v
}
@@ -219,8 +216,8 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { Int16(exactly: $0) }
}
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
}
}
@@ -234,8 +231,8 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
guard let v = Int32(exactly: int64) else { return nil }
self = v
}
@@ -258,8 +255,8 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { Int32(exactly: $0) }
}
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
}
}
@@ -271,8 +268,8 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
self = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
public init(sqliteStatement: SQLiteStatement, index: CInt) {
self = sqlite3_column_int64(sqliteStatement, index)
}
/// Returns an INTEGER database value.
@@ -301,8 +298,8 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
}
}
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, self)
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, self)
}
}
@@ -316,8 +313,8 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
guard let v = UInt(exactly: int64) else { return nil }
self = v
}
@@ -340,8 +337,8 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { UInt(exactly: $0) }
}
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
}
}
@@ -355,8 +352,8 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
guard let v = UInt8(exactly: int64) else { return nil }
self = v
}
@@ -379,8 +376,8 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { UInt8(exactly: $0) }
}
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
}
}
@@ -394,8 +391,8 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
guard let v = UInt16(exactly: int64) else { return nil }
self = v
}
@@ -418,8 +415,8 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { UInt16(exactly: $0) }
}
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
}
}
@@ -433,8 +430,8 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
guard let v = UInt32(exactly: int64) else { return nil }
self = v
}
@@ -457,8 +454,8 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { UInt32(exactly: $0) }
}
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
}
}
@@ -472,8 +469,8 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
guard let v = UInt64(exactly: int64) else { return nil }
self = v
}
@@ -496,8 +493,8 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { UInt64(exactly: $0) }
}
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
}
}
@@ -509,8 +506,8 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
self = API.sqlite3_column_double(sqliteStatement.rawValue, index)
public init(sqliteStatement: SQLiteStatement, index: CInt) {
self = sqlite3_column_double(sqliteStatement, index)
}
/// Returns a REAL database value.
@@ -536,8 +533,8 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
}
}
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_double(sqliteStatement.rawValue, index, self)
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_double(sqliteStatement, index, self)
}
}
@@ -549,8 +546,8 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
self = Float(API.sqlite3_column_double(sqliteStatement.rawValue, index))
public init(sqliteStatement: SQLiteStatement, index: CInt) {
self = Float(sqlite3_column_double(sqliteStatement, index))
}
/// Returns a REAL database value.
@@ -576,8 +573,8 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
}
}
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_double(sqliteStatement.rawValue, index, Double(self))
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_double(sqliteStatement, index, Double(self))
}
}
@@ -589,8 +586,8 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
self = String(cString: API.sqlite3_column_text(sqliteStatement.rawValue, index)!)
public init(sqliteStatement: SQLiteStatement, index: CInt) {
self = String(cString: sqlite3_column_text(sqliteStatement, index)!)
}
/// Returns a TEXT database value.
@@ -619,8 +616,8 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
}
}
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_text(sqliteStatement.rawValue, index, self, -1, SQLITE_TRANSIENT)
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_text(sqliteStatement, index, self, -1, SQLITE_TRANSIENT)
}
/// Calls the given closure after binding a statement argument.
@@ -630,9 +627,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<API, T>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt, do body: () throws -> T) throws -> T {
func withBinding<T>(to sqliteStatement: SQLiteStatement, at index: CInt, do body: () throws -> T) throws -> T {
try withCString {
let code = API.sqlite3_bind_text(sqliteStatement.rawValue, index, $0, -1, nil /* SQLITE_STATIC */)
let code = sqlite3_bind_text(sqliteStatement, index, $0, -1, nil /* SQLITE_STATIC */)
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
return try body()
}
+24 -28
View File
@@ -10,9 +10,7 @@ import Foundation
///
/// - ``DefaultTransactionClock``
/// - ``CustomTransactionClock``
public protocol TransactionClock<API>: Sendable {
associatedtype API: SQLiteAPI
public protocol TransactionClock: Sendable {
/// Returns the date of the current transaction.
///
/// This function is called whenever a transaction starts - precisely
@@ -22,33 +20,31 @@ public protocol TransactionClock<API>: Sendable {
/// called, and the database connection is not in a transaction.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/get_autocommit.html>
func now(_ db: DatabaseBase<API>) throws -> Date
func now(_ db: Database) throws -> Date
}
#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 == DefaultTransactionClock {
/// Returns the default clock.
public static var `default`: Self { DefaultTransactionClock() }
}
#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)
// }
//}
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<API: SQLiteAPI>: TransactionClock {
public struct DefaultTransactionClock: TransactionClock {
/// Returns the start date of the current transaction.
public func now(_ db: DatabaseBase<API>) throws -> Date {
public func now(_ db: Database) throws -> Date {
// An opportunity to fetch transaction time from the database when
// SQLite supports the feature.
Date()
@@ -56,14 +52,14 @@ public struct DefaultTransactionClock<API: SQLiteAPI>: TransactionClock {
}
/// A custom transaction clock.
public struct CustomTransactionClock<API: SQLiteAPI>: TransactionClock {
let _now: @Sendable (DatabaseBase<API>) throws -> Date
public struct CustomTransactionClock: TransactionClock {
let _now: @Sendable (Database) throws -> Date
public init(_ now: @escaping @Sendable (DatabaseBase<API>) throws -> Date) {
public init(_ now: @escaping @Sendable (Database) throws -> Date) {
self._now = now
}
public func now(_ db: DatabaseBase<API>) throws -> Date {
public func now(_ db: Database) throws -> Date {
try _now(db)
}
}
+82 -90
View File
@@ -1,16 +1,13 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
extension DatabaseBase {
extension Database {
// MARK: - Database Observation
@@ -33,8 +30,8 @@ extension DatabaseBase {
/// the observer lifetime (observation lasts until observer
/// is deallocated).
public func add(
transactionObserver: some TransactionObserverBase<API>,
extent: DatabaseTransactionObservationExtent = .observerLifetime)
transactionObserver: some TransactionObserver,
extent: TransactionObservationExtent = .observerLifetime)
{
SchedulingWatchdog.preconditionValidQueue(self)
guard let observationBroker else { return }
@@ -57,7 +54,7 @@ extension DatabaseBase {
/// db.remove(transactionObserver: myObserver)
/// }
/// ```
public func remove(transactionObserver: some TransactionObserverBase<API>) {
public func remove(transactionObserver: some TransactionObserver) {
SchedulingWatchdog.preconditionValidQueue(self)
guard let observationBroker else { return }
@@ -82,7 +79,7 @@ extension DatabaseBase {
/// ```swift
/// /// Inserts a region in the database, and start monitoring upon
/// /// successful insertion.
/// func startMonitoring(_ db: DatabaseBase<some SQLiteAPI>, region: CLRegion) throws {
/// func startMonitoring(_ db: Database, region: CLRegion) throws {
/// // Make sure database is inside a transaction
/// try db.inSavepoint {
///
@@ -113,9 +110,34 @@ extension DatabaseBase {
/// - parameter onCommit: A closure executed on transaction commit.
/// - parameter onRollback: A closure executed on transaction rollback.
public func afterNextTransaction(
onCommit: @escaping @Sendable (DatabaseBase<API>) -> Void,
onRollback: @escaping @Sendable (DatabaseBase<API>) -> Void = { _ in })
onCommit: @escaping @Sendable (Database) -> Void,
onRollback: @escaping @Sendable (Database) -> 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")
@@ -123,42 +145,16 @@ extension DatabaseBase {
transactionObserver: TransactionHandler(onCommit: onCommit, onRollback: onRollback),
extent: .nextTransaction)
}
}
fileprivate class TransactionHandler<API: SQLiteAPI>: TransactionObserverBase {
let onCommit: @Sendable (DatabaseBase<API>) -> Void
let onRollback: @Sendable (DatabaseBase<API>) -> Void
init(
onCommit: @escaping @Sendable (DatabaseBase<API>) -> Void,
onRollback: @escaping @Sendable (DatabaseBase<API>) -> 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<API>) {
onCommit(db)
/// 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
}
func databaseDidRollback(_ db: DatabaseBase<API>) {
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
@@ -171,8 +167,8 @@ public enum DatabaseTransactionObservationExtent: Sendable {
/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
/// func databaseDidChange(with event: DatabaseEvent)
/// func databaseWillCommit() throws
/// func databaseDidCommit(_ db: DatabaseBase<some SQLiteAPI>)
/// func databaseDidRollback(_ db: DatabaseBase<some SQLiteAPI>)
/// func databaseDidCommit(_ db: Database)
/// func databaseDidRollback(_ db: Database)
/// }
///
/// First observer is added, and a transaction is started. At this point,
@@ -245,8 +241,8 @@ public enum DatabaseTransactionObservationExtent: Sendable {
///
/// After the statement *has been executed*, the broker calls
/// observer.databaseDidCommit().
class DatabaseObservationBroker<API: SQLiteAPI> {
private unowned let database: DatabaseBase<API>
class DatabaseObservationBroker {
private unowned let database: Database
/// The savepoint stack allows us to hold database event notifications until
/// all savepoints are released. The goal is to only tell transaction
@@ -259,10 +255,10 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
private var transactionCompletion = TransactionCompletion.none
/// The registered transaction observers.
private var transactionObservations: [TransactionObservation<API>] = []
private var transactionObservations: [TransactionObservation] = []
/// The observers for an individual statement execution.
private var statementObservations: [StatementObservation<API>] = [] {
private var statementObservations: [StatementObservation] = [] {
didSet {
let isEmpty = statementObservations.isEmpty
if isEmpty != oldValue.isEmpty {
@@ -276,22 +272,22 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
}
}
init(_ database: DatabaseBase<API>) {
init(_ database: Database) {
self.database = database
}
// MARK: - Transaction observers
func add(transactionObserver: some TransactionObserverBase<API>, extent: DatabaseTransactionObservationExtent) {
func add(transactionObserver: some TransactionObserver, extent: Database.TransactionObservationExtent) {
transactionObservations.append(TransactionObservation(observer: transactionObserver, extent: extent))
}
func remove(transactionObserver: some TransactionObserverBase<API>) {
func remove(transactionObserver: some TransactionObserver) {
transactionObservations.removeFirst { $0.isWrapping(transactionObserver) }
}
/// Called from ``TransactionObserver/stopObservingDatabaseChangesUntilNextTransaction()``.
func disableUntilNextTransaction(transactionObserver: some TransactionObserverBase<API>) {
func disableUntilNextTransaction(transactionObserver: some TransactionObserver) {
if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver) }) {
observation.isEnabled = false
statementObservations.removeFirst { $0.transactionObservation === observation }
@@ -323,7 +319,7 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
}
/// Prepares observation of changes that are about to be performed by the statement.
func statementWillExecute(_ statement: StatementBase<API>) {
func statementWillExecute(_ statement: Statement) {
if !database.isReadOnly && !transactionObservations.isEmpty {
// As statement executes, it may trigger database changes that will
// be notified to transaction observers. As a consequence, observers
@@ -399,7 +395,7 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
/// May throw the user-provided cancelled commit error, if a transaction
/// observer has cancelled a transaction.
func statementDidFail(_ statement: StatementBase<API>) throws {
func statementDidFail(_ statement: Statement) throws {
// Undo statementWillExecute
statementObservations = []
SchedulingWatchdog.current!.databaseObservationBroker = nil
@@ -426,7 +422,7 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
/// 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: StatementBase<API>) throws {
func statementDidExecute(_ statement: Statement) throws {
// Undo statementWillExecute
if transactionObservations.isEmpty == false {
statementObservations = []
@@ -712,7 +708,7 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
func installCommitAndRollbackHooks() {
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
API.sqlite3_commit_hook(database.sqliteConnection, { brokerPointer in
sqlite3_commit_hook(database.sqliteConnection, { brokerPointer in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
do {
try broker.databaseWillCommit()
@@ -726,7 +722,7 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
}
}, brokerPointer)
API.sqlite3_rollback_hook(database.sqliteConnection, { brokerPointer in
sqlite3_rollback_hook(database.sqliteConnection, { brokerPointer in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
switch broker.transactionCompletion {
case .cancelledCommit:
@@ -742,7 +738,7 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
private func installUpdateHook() {
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
API.sqlite3_update_hook(
sqlite3_update_hook(
database.sqliteConnection,
{ (brokerPointer, updateKind, databaseNameCString, tableNameCString, rowID) in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
@@ -775,7 +771,7 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
}
private func uninstallUpdateHook() {
API.sqlite3_update_hook(database.sqliteConnection, nil, nil)
sqlite3_update_hook(database.sqliteConnection, nil, nil)
#if SQLITE_ENABLE_PREUPDATE_HOOK
sqlite3_preupdate_hook(database.sqliteConnection, nil, nil)
#endif
@@ -801,8 +797,7 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
// MARK: - TransactionObserver
public protocol TransactionObserverBase<API>: AnyObject {
associatedtype API: SQLiteAPI
public protocol TransactionObserver: AnyObject {
/// Returns whether specific kinds of database changes should be notified
/// to the observer.
@@ -866,10 +861,10 @@ public protocol TransactionObserverBase<API>: AnyObject {
func databaseWillCommit() throws
/// Called when a transaction has been committed on disk.
func databaseDidCommit(_ db: DatabaseBase<API>)
func databaseDidCommit(_ db: Database)
/// Called when a transaction has been rollbacked.
func databaseDidRollback(_ db: DatabaseBase<API>)
func databaseDidRollback(_ db: Database)
#if SQLITE_ENABLE_PREUPDATE_HOOK
/// Called when the database is changed by an insert, update, or
@@ -903,7 +898,7 @@ public protocol TransactionObserverBase<API>: AnyObject {
#endif
}
extension TransactionObserverBase {
extension TransactionObserver {
/// The default implementation does nothing.
public func databaseWillCommit() throws { }
@@ -965,25 +960,22 @@ extension TransactionObserverBase {
// MARK: - TransactionObservation
/// This class manages the observation extent of a transaction observer
final class TransactionObservation<API: SQLiteAPI> {
let extent: DatabaseTransactionObservationExtent
final class TransactionObservation {
let extent: Database.TransactionObservationExtent
/// 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 TransactionObserverBase<API>)?
private var strongObserver: (any TransactionObserverBase<API>)?
private var observer: (any TransactionObserverBase<API>)? {
if let strongObserver { return strongObserver }
return weakObserver
}
private weak var weakObserver: (any TransactionObserver)?
private var strongObserver: (any TransactionObserver)?
private var observer: (any TransactionObserver)? { strongObserver ?? weakObserver }
fileprivate var isObserving: Bool {
observer != nil
}
init(observer: some TransactionObserverBase<API>, extent: DatabaseTransactionObservationExtent) {
init(observer: some TransactionObserver, extent: Database.TransactionObservationExtent) {
self.extent = extent
switch extent {
case .observerLifetime:
@@ -996,7 +988,7 @@ final class TransactionObservation<API: SQLiteAPI> {
}
}
func isWrapping(_ observer: some TransactionObserverBase<API>) -> Bool {
func isWrapping(_ observer: some TransactionObserver) -> Bool {
self.observer === observer
}
@@ -1025,7 +1017,7 @@ final class TransactionObservation<API: SQLiteAPI> {
try observer?.databaseWillCommit()
}
func databaseDidCommit(_ db: DatabaseBase<API>) {
func databaseDidCommit(_ db: Database) {
switch extent {
case .observerLifetime, .databaseLifetime:
observer?.databaseDidCommit(db)
@@ -1041,7 +1033,7 @@ final class TransactionObservation<API: SQLiteAPI> {
}
}
func databaseDidRollback(_ db: DatabaseBase<API>) {
func databaseDidRollback(_ db: Database) {
switch extent {
case .observerLifetime, .databaseLifetime:
observer?.databaseDidRollback(db)
@@ -1060,8 +1052,8 @@ final class TransactionObservation<API: SQLiteAPI> {
/// The observation of one particular statement, by a particular
/// transaction observer.
struct StatementObservation<API: SQLiteAPI> {
var transactionObservation: TransactionObservation<API>
struct StatementObservation {
var transactionObservation: TransactionObservation
/// A predicate that filters database events that should be notified.
///
@@ -1072,7 +1064,7 @@ struct StatementObservation<API: SQLiteAPI> {
/// ```
var tracksEvent: DatabaseEventPredicate
init(transactionObservation: TransactionObservation<API>, trackingEvents predicate: DatabaseEventPredicate) {
init(transactionObservation: TransactionObservation, trackingEvents predicate: DatabaseEventPredicate) {
self.transactionObservation = transactionObservation
self.tracksEvent = predicate
}
@@ -1502,7 +1494,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt)
-> DatabaseValue?
{
var value: SQLiteValue?
var value: SQLiteValue? = nil
guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil }
if let value {
return DatabaseValue(sqliteValue: value)
+23 -14
View File
@@ -1,15 +1,12 @@
#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
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// An instance of WALSnapshot records the state of a WAL mode database for some
/// specific point in history.
@@ -19,18 +16,30 @@
/// actual observation. This class has no other purpose, and is not intended to
/// become public.
///
/// It does not work with SQLCipher, because SQLCipher does not support
/// `SQLITE_ENABLE_SNAPSHOT` correctly: we have linker errors.
/// See <https://github.com/ericsink/SQLitePCL.raw/issues/452>.
///
/// With custom SQLite builds, it only works if `SQLITE_ENABLE_SNAPSHOT`
/// is defined.
///
/// With system SQLite, it works because the SDK exposes the C apis and
/// since XCode 14.
///
/// Yes, this is an awfully complex logic.
///
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
final class WALSnapshot: @unchecked Sendable {
// @unchecked because sqlite3_snapshot has no threading requirements.
// <https://www.sqlite.org/c3ref/snapshot.html>
let sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>
init(_ db: DatabaseBase<some SQLiteAPI>) throws {
init(_ db: Database) throws {
var sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>?
let code = withUnsafeMutablePointer(to: &sqliteSnapshot) {
return sqlite3_snapshot_get(db.sqliteConnection, "main", $0)
}
guard code == API.SQLITE_OK else {
guard code == SQLITE_OK else {
// <https://www.sqlite.org/c3ref/snapshot_get.html>
//
// > The following must be true for sqlite3_snapshot_get() to succeed. [...]
+7 -13
View File
@@ -1,13 +1,13 @@
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
/// A long-live read-only WAL transaction.
///
/// `WALSnapshotTransaction` **takes ownership** of its reader
/// `SerializedDatabase` (TODO: make it a move-only type eventually).
final class WALSnapshotTransactionBase<API: SQLiteAPI>: @unchecked Sendable {
final class WALSnapshotTransaction: @unchecked Sendable {
// @unchecked because `databaseAccess` is protected by a mutex.
private struct DatabaseAccess {
let reader: SerializedDatabaseBase<API>
let reader: SerializedDatabase
let release: @Sendable (_ isInsideTransaction: Bool) -> Void
// MUST be called only once
@@ -15,13 +15,7 @@ final class WALSnapshotTransactionBase<API: SQLiteAPI>: @unchecked Sendable {
// WALSnapshotTransaction may be deinitialized in the dispatch
// queue of its reader: allow reentrancy.
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
// Commit or rollback, but try hard to leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
try? db.commit()
return db.isInsideTransaction
}
release(isInsideTransaction)
@@ -60,7 +54,7 @@ final class WALSnapshotTransactionBase<API: SQLiteAPI>: @unchecked Sendable {
/// - parameter release: A closure to call when the read-only connection
/// is no longer used.
init(
onReader reader: SerializedDatabaseBase<API>,
onReader reader: SerializedDatabase,
release: @escaping @Sendable (_ isInsideTransaction: Bool) -> Void)
throws
{
@@ -90,7 +84,7 @@ final class WALSnapshotTransactionBase<API: SQLiteAPI>: @unchecked Sendable {
/// Executes database operations in the snapshot transaction, and
/// returns their result after they have finished executing.
func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
func read<T>(_ value: (Database) throws -> T) throws -> T {
try databaseAccessMutex.withLock { databaseAccess in
guard let databaseAccess else {
throw DatabaseError.snapshotIsLost()
@@ -103,7 +97,7 @@ final class WALSnapshotTransactionBase<API: SQLiteAPI>: @unchecked Sendable {
/// Schedules database operations for execution, and
/// returns immediately.
func asyncRead(_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void) {
func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
databaseAccessMutex.withLock { databaseAccess in
guard let databaseAccess else {
value(.failure(DatabaseError.snapshotIsLost()))
@@ -29,8 +29,6 @@ Get information about schema objects such as tables, columns, indexes, foreign k
### Supporting Types
- ``DatabaseSchemaID``
- ``DatabaseObjectID``
- ``ColumnInfo``
- ``ForeignKeyInfo``
- ``IndexInfo``
@@ -96,7 +96,6 @@ do {
- ``persistentReadOnlyConnections``
- ``prepareDatabase(_:)``
- ``publicStatementArguments``
- ``schemaSource``
- ``transactionClock``
- ``TransactionClock``
@@ -107,7 +106,3 @@ do {
- ``writeQoS``
- ``targetQueue``
- ``writeTargetQueue``
### Supporting Types
- ``DatabaseSchemaSource``
@@ -128,7 +128,7 @@ For example:
```swift
extension EvenInteger: StatementColumnConvertible {
init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
init?(sqliteStatement: SQLiteStatement, 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)
-1
View File
@@ -94,7 +94,6 @@ let players: [Player] = try dbQueue.read { db in
- <doc:RecordRecommendedPractices>
- <doc:RecordTimestamps>
- <doc:SingleRowTables>
- <doc:ViewRecords>
### Application Tools
+8 -8
View File
@@ -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: DatabaseBase<some SQLiteAPI>) throws {
mutating func willInsert(_ db: Database) 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: DatabaseBase<some SQLiteAPI>) throws {
mutating func willInsert(_ db: Database) 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: DatabaseBase<some SQLiteAPI>) throws {
mutating func saveWithTimestamp(_ db: Database) 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: DatabaseBase<some SQLiteAPI>) throws {
mutating func willInsert(_ db: Database) 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: DatabaseBase<some SQLiteAPI>) throws {
mutating func initializeTimestamps(_ db: Database) 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: DatabaseBase<some SQLiteAPI>, modificationDate: Date? = nil) throws {
mutating func updateWithTimestamp(_ db: Database, 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: DatabaseBase<some SQLiteAPI>,
_ db: Database,
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: DatabaseBase<some SQLiteAPI>, modificationDate: Date? = nil) throws {
mutating func touch(_ db: Database, modificationDate: Date? = nil) throws {
try updateChanges(db) {
$0.modificationDate = try modificationDate ?? db.transactionDate
}
+4 -4
View File
@@ -128,7 +128,7 @@ We have seen in the <doc:SingleRowTables#The-Single-Row-Table> section that by d
```swift
// Customize the default PersistableRecord behavior
func willUpdate(_ db: DatabaseBase<some SQLiteAPI>, columns: Set<String>) throws {
func willUpdate(_ db: Database, columns: Set<String>) 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: DatabaseBase<some SQLiteAPI>) throws -> AppConfiguration {
static func find(_ db: Database) 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: DatabaseBase<some SQLiteAPI>, columns: Set<String>) throws {
func willUpdate(_ db: Database, columns: Set<String>) 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: DatabaseBase<some SQLiteAPI>) throws -> AppConfiguration {
static func find(_ db: Database) throws -> AppConfiguration {
try fetchOne(db) ?? .default
}
}
+1 -7
View File
@@ -55,7 +55,7 @@ let count = try await writer.read { db in
}
// Shorthand notation:
// ⚠️ Converting non-sendable function value to '@Sendable (DatabaseBase<some SQLiteAPI>)
// ⚠️ Converting non-sendable function value to '@Sendable (Database)
// throws -> Int' may introduce data races.
let count = try await writer.read(Player.fetchCount)
```
@@ -229,11 +229,5 @@ Task {
}
```
## Topics
### Supporting Types
- ``GRDBSendableMetatype``
[demo apps]: https://github.com/groue/GRDB.swift/tree/master/Documentation/DemoApps
[Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide/
+2 -2
View File
@@ -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: DatabaseBase<some SQLiteAPI>) throws {
func myCriticalMethod(_ db: Database) throws {
precondition(db.isInsideTransaction, "This method requires a transaction")
try ...
}
@@ -169,7 +169,7 @@ func myCriticalMethod(_ db: DatabaseBase<some SQLiteAPI>) throws {
Yet, there is a better option than checking for transactions. Critical database sections should use savepoints, described below:
```swift
func myCriticalMethod(_ db: DatabaseBase<some SQLiteAPI>) throws {
func myCriticalMethod(_ db: Database) throws {
try db.inSavepoint {
// Here the database is guaranteed to be inside a transaction.
try ...
-383
View File
@@ -1,383 +0,0 @@
# View Records
Define record types that target database views.
## Overview
A record type targets a [database view] as soon as its ``TableRecord/databaseTableName-3tcw2`` is the name of a view.
With such a record, some GRDB features will work out of the box, and some will throw errors without extra configuration:
```swift
// OK: Works out of the box
let captains = try Captain.fetchAll(db)
let captainCount = try Captain.fetchCount(db)
// KO: Requires extra configuration
// SQLite error 1: database view captain has no primary key
var bob = try Captain.find(db, id: "bob")
bob.name = "Bobby"
// SQLite error 1: cannot modify captain because it is a view
try bob.update(db)
```
This article explains how to solve those errors:
- How to provide a primary key to a view.
- How to define INSTEAD OF triggers that insert, update, and delete through a database view.
> important: GRDB is impacted by some SQLite limitations regarding INSTEAD OF triggers:
>
> - **Auto-incremented primary keys are not supported.** To be precise, SQLite won't expose the rowid of rows inserted via an INSTEAD OF trigger, so GRDB won't know the id of newly inserted rows. This has various nefarious consequences—see for example the important notice in the ``MutablePersistableRecord/didInsert(_:)`` callback. For more information, check this [SQLite forum thread](https://sqlite.org/forum/forumpost/707e7ed932).
> - **INSTEAD OF triggers and the RETURNING clause do not play well together.** Those are SQLite bugs. All GRDB record methods with `andFetch` in their name may return unexpected or wrong results, depending on the SQLite version. For example, the SQLite version that ships with iOS 18 has bugs, and even more in iOS 17. If you intend to use the `RETURNING` clause, it is recommended that you write tests and run them in various target operation systems.
## Preliminary Setup
To support this documentation, we need a database that contains a view. The sample code below uses <doc:Migrations> and <doc:DatabaseSchemaModifications> methods.
The database schema contains teams and players. Some players are the captain of their team. We enforce in the database schema that a given team can't have multiple captains:
```swift
var migrator = DatabaseMigrator()
migrator.registerMigration("Teams and players") { db in
try db.create(table: "team") { t in
t.primaryKey("id", .text)
t.column("name", .text).notNull()
}
try db.create(table: "player") { t in
t.primaryKey("id", .text)
t.column("name", .text).notNull()
t.belongsTo("team", onDelete: .setNull)
t.column("isCaptain", .boolean).notNull()
}
// One unique captain per team
try db.create(
indexOn: "player", columns: ["teamId"],
options: .unique,
condition: Column("isCaptain"))
}
```
We define record types for the `team` and `player` tables, as described in <doc:RecordRecommendedPractices>:
```swift
struct Team: Codable, Identifiable, FetchableRecord, PersistableRecord {
var id: String
var name: String
}
struct Player: Codable, Identifiable, FetchableRecord, PersistableRecord {
var id: String
var name: String
var teamId: String?
var isCaptain: Bool
}
```
Let's define a view and a record type for captains. At this point, both the view and the record are read-only:
```swift
migrator.registerMigration("Read-only captains") { db in
try db.execute(sql: """
CREATE VIEW captain AS
SELECT id, name, teamId
FROM player
WHERE isCaptain AND teamId IS NOT NULL;
""")
}
struct Captain: Decodable, Identifiable, FetchableRecord {
var id: String
var name: String
var teamId: String
}
```
✅ From now on, we can use the `Captain` record:
```swift
let dbQueue = try DatabaseQueue()
try migrator.migrate(dbQueue)
try dbQueue.write { db in
try Team(id: "red", name: "Red").insert(db)
try Team(id: "blue", name: "Blue").insert(db)
try Player(id: "alice", name: "Alice", teamId: "red", isCaptain: true).insert(db)
try Player(id: "bob", name: "Bob", teamId: "blue", isCaptain: true).insert(db)
try Player(id: "craig", name: "Craig", teamId: "blue", isCaptain: false).insert(db)
let captains = try Captain.fetchAll(db)
// Prints:
// Captain(id: "alice", name: "Alice", teamId: "red")
// Captain(id: "bob", name: "Bob", teamId: "blue")
print(captains)
}
```
## Specifying the primary key of a view
SQLite views do not have any primary key, so GRDB cannot introspect the database schema and automatically find the eventual primary key.
To instruct GRDB about the primary key, define a **schema source**, a type that conforms to ``DatabaseSchemaSource``. In this sample code, the schema only contains the "captain" view, so our schema source does not need to be very complicated. Check the documentation of the protocol for more detailed instructions:
```swift
struct GameSchemaSource: DatabaseSchemaSource {
/// Returns the names of the columns for the primary key in the
/// provided database view.
func columnsForPrimaryKey(_ db: DatabaseBase<some SQLiteAPI>, inView view: DatabaseObjectID) throws -> [String]? {
["id"]
}
}
```
We configure the database connection with this schema source:
```swift
var config = Configuration()
config.schemaSource = GameSchemaSource()
let dbQueue = try DatabaseQueue(configuration: config)
try migrator.migrate(dbQueue)
```
✅ We can now use the primary key of captains:
```swift
try dbQueue.read { db in
// [Insert some teams and players...]
let captains = try Captain.orderByPrimaryKey().fetchAll(db)
let alice = try Captain.find(db, id: "alice")
}
```
## Associations between views
To define [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) between record types that target database views, the foreign key must be explicitly provided. We define the foreign key from `captain` to `team` with a column declared as recommended in <doc:RecordRecommendedPractices>:
```swift
extension Captain {
// Time to define some columns
enum Columns {
static let teamId = Column(CodingKeys.teamId)
}
// The captain view has a foreign key to teams,
// from the teamId column to the team primary key.
// SQLite does not know about it, so we declare it explicitly:
static let teamForeignKey = ForeignKey([Columns.teamId])
// A captain belongs to a team.
static let team = belongsTo(Team.self, using: teamForeignKey)
}
extension Team {
// A team has a captain.
static let captain = hasOne(Captain.self, using: Captain.teamForeignKey)
}
```
✅ We can now use those associations:
```swift
try dbQueue.read { db in
// All teams with a captain
let teamsWithCaptain: [Team] = try Team
.joining(required: Team.captain)
.fetchAll(db)
// All (captain, team) pairs
struct CaptainWithTeam: Decodable, FetchableRecord {
var captain: Captain
var team: Team
}
let captainsWithTeam: [CaptainWithTeam] = try Captain
.including(required: Captain.team)
.asRequest(of: CaptainWithTeam.self)
.fetchAll(db)
}
```
## Inserting rows into a view
SQLite views are read-only unless we define an [INSTEAD OF trigger] that specifies which statements to run when we insert a row into a view.
INSTEAD OF triggers are very versatile, and applications can define the behavior that best fits their needs. In our sample code, inserting a captain will insert a player with the `isCaptain` flag set, and we'll also remove the `isCaptain` flag of the previous captain, if any:
```swift
migrator.registerMigration("Captain insert") { db in
try db.execute(sql: """
-- Insert trigger
CREATE TRIGGER captain_insert
INSTEAD OF INSERT ON captain
BEGIN
-- Remove previous captain
UPDATE player SET isCaptain = 0
WHERE teamId = NEW.teamId AND isCaptain;
-- Insert new captain
INSERT INTO player(id, name, teamId, isCaptain)
VALUES (NEW.id, NEW.name, NEW.teamId, 1);
END;
""")
}
// Apply the new migration
try migrator.migrate(dbQueue)
```
Let's also give an `insert()` method to the Captain record, with the ``PersistableRecord`` protocol:
```swift
extension Captain: Encodable, PersistableRecord { }
```
- note: Remember that auto-incremented primary keys are not supported, as described at the beginning of this article. Our captain view is backed by the player table which has a string primary key, so we're fine.
✅ We can directly insert captains:
```swift
try dbQueue.write {
try Team(id: "green", name: "Green").insert(db)
// Diane is the captain
try Captain(id: "diane", name: "Diane", teamId: "green").insert(db)
// Well, no: Eugene is the captain
try Captain(id: "eugene", name: "Eugene", teamId: "green").insert(db)
// Prints:
// team player captain
// green|Green diane|Diane|green|0 eugene|Eugene|green
// eugene|Eugene|green|1
try db.dumpTables(["team", "player", "captain"])
}
```
## Updating rows in a view
Just like for inserts, an INSTEAD OF trigger can specify how to update rows in a view.
In our sample code, updating a captain will update the player with the same id, and remove the `isCaptain` flag from the previous captain of the team, if any:
```swift
migrator.registerMigration("Captain update") { db in
try db.execute(sql: """
-- Update trigger
CREATE TRIGGER captain_update
INSTEAD OF UPDATE ON captain
BEGIN
-- Remove previous captain
UPDATE player SET isCaptain = 0
WHERE teamId = NEW.teamId AND isCaptain AND id <> NEW.id;
-- Update captain
UPDATE player SET name = NEW.name, teamId = NEW.teamId, isCaptain = 1
WHERE id = NEW.id;
END;
""")
}
// Apply the new migration
try migrator.migrate(dbQueue)
```
✅ Let's update captains:
```swift
try dbQueue.write {
try Team(id: "red", name: "Red").insert(db)
try Team(id: "blue", name: "Blue").insert(db)
try Captain(id: "alice", name: "Alice", teamId: "red").insert(db)
// Bob is the Blue captain.
var bob = Captain(id: "bob", name: "Bob", teamId: "blue")
try bob.insert(db)
// Bob is now Bobby, the Red captain.
// Alice is no longer the Red captain.
try bob.updateChanges(db) {
$0.name = "Bobby"
$0.teamId = "red"
}
// Prints:
// team player captain
// blue|Blue alice|Alice|red|0 bob|Bobby|red
// red|Red bob|Bobby|red|1
try db.dumpTables(["team", "player", "captain"])
}
```
## Deleting rows from a view
The last missing INSTEAD OF trigger deals with deletes:
```swift
migrator.registerMigration("Captain delete") { db in
try db.execute(sql: """
-- Delete trigger
CREATE TRIGGER captain_delete
INSTEAD OF DELETE ON captain
BEGIN
DELETE FROM player WHERE id = OLD.id;
END;
""")
}
// Apply the new migration
try migrator.migrate(dbQueue)
```
✅ Let's delete some captains:
```swift
try dbQueue.write {
// Delete Alice
try Captain.deleteOne(db, id: "alice")
// Delete Bob
let bob = try Captain.find(db, id: "bob")
try bob.delete(db)
// Delete all captains
try Captain.deleteAll()
}
```
## Going further
To exercise the techniques described here, try to define record types for these other views:
- The `enrolledPlayer` view that only contains players that belong to a team:
```swift
try db.execute(sql: """
CREATE VIEW enrolledPlayer AS
SELECT id, name, teamId, isCaptain
FROM player
WHERE teamId IS NOT NULL;
""")
```
- The `teamWithCaptainId` view that contains a `captainId` column:
```swift
try db.execute(sql: """
CREATE VIEW teamWithCaptainId AS
SELECT team.id, team.name, player.id AS captainId
FROM team
JOIN player ON player.teamId = team.id AND player.isCaptain;
""")
```
- A refactored `captain` view whose primary key is the team id—this is valid, since the schema enforces that there's a single captain for each team:
```swift
try db.execute(sql: """
CREATE VIEW captain AS
SELECT teamId, name
FROM player
WHERE isCaptain AND teamId IS NOT NULL;
""")
```
[database view]: https://www.sqlite.org/lang_createview.html
[INSTEAD OF trigger]: https://sqlite.org/lang_createtrigger.html#instead_of_triggers
+5 -5
View File
@@ -2,7 +2,7 @@ import Foundation
// MARK: - Dump
extension DatabaseBase {
extension Database {
/// Prints the results of all statements in the provided SQL.
///
/// For example:
@@ -183,7 +183,7 @@ extension DatabaseBase {
// MARK: -
extension DatabaseBase {
extension Database {
func _dumpStatements(
_ statements: some Cursor<Statement>,
format: some DumpFormat,
@@ -317,14 +317,14 @@ extension DatabaseBase {
}
private func ignoresObject(named name: String) throws -> Bool {
if Self.isSQLiteInternalTable(name) { return true }
if Self.isGRDBInternalTable(name) { return true }
if Database.isSQLiteInternalTable(name) { return true }
if Database.isGRDBInternalTable(name) { return true }
if try isShadowTable(name) { return true }
return false
}
private func isShadowTable(_ tableName: String) throws -> Bool {
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// Maybe SQLCipher is too old: check actual version
if Database.sqliteLibVersionNumber >= 3037000 {
guard let table = try table(tableName) else {
+1 -1
View File
@@ -1,4 +1,4 @@
extension DatabaseReaderBase {
extension DatabaseReader {
/// Prints the results of all statements in the provided SQL.
///
/// For example:
+6 -8
View File
@@ -33,28 +33,26 @@
/// - ``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<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
mutating func writeRow(
_ db: Database,
statement: Statement,
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<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
mutating func finalize(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
}
+15 -18
View File
@@ -1,14 +1,11 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
@@ -61,9 +58,9 @@ public struct DebugDumpFormat: Sendable {
}
extension DebugDumpFormat: DumpFormat {
public mutating func writeRow<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
public mutating func writeRow(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
{
if firstRow {
@@ -91,15 +88,15 @@ extension DebugDumpFormat: DumpFormat {
stream.write("\n")
}
public mutating func finalize<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
public mutating func finalize(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
{
firstRow = true
}
private func formattedValue(_ db: DatabaseBase<some SQLiteAPI>, in sqliteStatement: SQLiteStatement, at index: CInt) -> String {
private func formattedValue(_ db: Database, in sqliteStatement: SQLiteStatement, at index: CInt) -> String {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_NULL:
return nullValue
+15 -18
View File
@@ -1,14 +1,11 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
@@ -80,9 +77,9 @@ public struct JSONDumpFormat: Sendable {
}
extension JSONDumpFormat: DumpFormat {
public mutating func writeRow<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
public mutating func writeRow(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
throws {
if firstRow {
@@ -127,9 +124,9 @@ extension JSONDumpFormat: DumpFormat {
stream.write("}")
}
public mutating func finalize<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
public mutating func finalize(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
{
if firstRow {
@@ -145,7 +142,7 @@ extension JSONDumpFormat: DumpFormat {
firstRow = true
}
private func formattedValue(_ db: DatabaseBase<some SQLiteAPI>, in sqliteStatement: SQLiteStatement, at index: CInt) throws -> String {
private func formattedValue(_ db: Database, in sqliteStatement: SQLiteStatement, at index: CInt) throws -> String {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_NULL:
return "null"
+15 -18
View File
@@ -1,14 +1,11 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
@@ -43,9 +40,9 @@ public struct LineDumpFormat: Sendable {
}
extension LineDumpFormat: DumpFormat {
public mutating func writeRow<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
public mutating func writeRow(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
{
var lines: [(column: String, value: String)] = []
@@ -76,9 +73,9 @@ extension LineDumpFormat: DumpFormat {
}
}
public mutating func finalize<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
public mutating func finalize(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
{
if firstRow == false {
@@ -88,7 +85,7 @@ extension LineDumpFormat: DumpFormat {
}
func formattedValue(
_ db: DatabaseBase<some SQLiteAPI>,
_ db: Database,
in sqliteStatement: SQLiteStatement,
at index: CInt)
-> String
+15 -18
View File
@@ -1,14 +1,11 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
@@ -58,9 +55,9 @@ public struct ListDumpFormat: Sendable {
}
extension ListDumpFormat: DumpFormat {
public mutating func writeRow<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
public mutating func writeRow(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
{
if firstRow {
@@ -88,16 +85,16 @@ extension ListDumpFormat: DumpFormat {
stream.write("\n")
}
public mutating func finalize<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
public mutating func finalize(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
{
firstRow = true
}
func formattedValue(
_ db: DatabaseBase<some SQLiteAPI>,
_ db: Database,
in sqliteStatement: SQLiteStatement,
at index: CInt)
-> String
+14 -17
View File
@@ -1,14 +1,11 @@
//// 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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A format that prints one line per database row, formatting values
/// as SQL literals.
@@ -47,9 +44,9 @@ public struct QuoteDumpFormat: Sendable {
}
extension QuoteDumpFormat: DumpFormat {
public mutating func writeRow<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
public mutating func writeRow(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
{
if firstRow {
@@ -81,9 +78,9 @@ extension QuoteDumpFormat: DumpFormat {
stream.write("\n")
}
public mutating func finalize<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
public mutating func finalize(
_ db: Database,
statement: Statement,
to stream: inout DumpStream)
{
firstRow = true
+7 -9
View File
@@ -40,11 +40,11 @@ public struct FTS3 {
/// the `remove_diacritics=1` tokenizer argument.
case removeLegacy
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
#if GRDBCUSTOMSQLITE
/// Remove diacritics from Latin script characters. This option matches
/// the `remove_diacritics=2` tokenizer argument.
case remove
#else
#elseif !GRDBCIPHER
/// Remove diacritics from Latin script characters. This option matches
/// the `remove_diacritics=2` tokenizer argument.
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.27+
@@ -66,7 +66,6 @@ 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:
@@ -95,13 +94,12 @@ public struct FTS3 {
/// - <https://www.sqlite.org/fts3.html#querying_tokenizers>
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func tokenize<API: SQLiteAPI>(
public static func tokenize(
_ string: String,
withTokenizer tokenizer: FTS3TokenizerDescriptor = .simple,
api: API.Type)
withTokenizer tokenizer: FTS3TokenizerDescriptor = .simple)
throws -> [String]
{
try DatabaseQueueBase<API>().inDatabase { db in
try DatabaseQueue().inDatabase { db in
var tokenizerChunks: [String] = []
tokenizerChunks.append(tokenizer.name)
for option in tokenizer.arguments {
@@ -123,7 +121,7 @@ extension FTS3: VirtualTableModule {
FTS3TableDefinition()
}
public func moduleArguments(for definition: FTS3TableDefinition, in db: DatabaseBase<some SQLiteAPI>) -> [String] {
public func moduleArguments(for definition: FTS3TableDefinition, in db: Database) -> [String] {
var arguments = definition.columns
if let tokenizer = definition.tokenizer {
if tokenizer.arguments.isEmpty {
@@ -138,7 +136,7 @@ extension FTS3: VirtualTableModule {
return arguments
}
public func database(_ db: DatabaseBase<some SQLiteAPI>, didCreate tableName: String, using definition: FTS3TableDefinition) { }
public func database(_ db: Database, didCreate tableName: String, using definition: FTS3TableDefinition) { }
}
/// A `FTS3TableDefinition` lets you define the components of an FTS3
+14 -34
View File
@@ -22,7 +22,6 @@ 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 <https://www.sqlite.org/fts3.html#full_text_index_queries>
@@ -38,17 +37,14 @@ public struct FTS3Pattern: Sendable {
/// ```
///
/// - throws: A ``DatabaseError`` if the pattern has an invalid syntax.
public init<API: SQLiteAPI>(
rawPattern: String,
api: API.Type
) throws {
public init(rawPattern: String) 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 DatabaseQueueBase<API>().inDatabase { db in
try DatabaseQueue().inDatabase { db in
try db.execute(literal: """
CREATE VIRTUAL TABLE documents USING fts3();
SELECT * FROM documents WHERE content MATCH \(rawPattern);
@@ -63,7 +59,6 @@ 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.
@@ -76,17 +71,13 @@ public struct FTS3Pattern: Sendable {
/// ```
///
/// - parameter string: The string to turn into an FTS3 pattern.
public init?<API: SQLiteAPI>(
matchingAnyTokenIn string: String,
api: API.Type
) {
guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple, api: api),
public init?(matchingAnyTokenIn string: String) {
guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple),
!tokens.isEmpty
else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " OR "), api: api)
try? self.init(rawPattern: tokens.joined(separator: " OR "))
}
#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.
@@ -99,17 +90,13 @@ public struct FTS3Pattern: Sendable {
/// ```
///
/// - parameter string: The string to turn into an FTS3 pattern.
public init?<API: SQLiteAPI>(
matchingAllTokensIn string: String,
api: API.Type
) {
guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple, api: api),
public init?(matchingAllTokensIn string: String) {
guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple),
!tokens.isEmpty
else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " "), api: api)
try? self.init(rawPattern: tokens.joined(separator: " "))
}
#warning("TODO: expose a version with default api")
/// Creates a pattern that matches all token prefixes found in the input
/// string.
///
@@ -123,17 +110,13 @@ public struct FTS3Pattern: Sendable {
/// ```
///
/// - parameter string: The string to turn into an FTS3 pattern.
public init?<API: SQLiteAPI>(
matchingAllPrefixesIn string: String,
api: API.Type
) {
guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple, api: api),
public init?(matchingAllPrefixesIn string: String) {
guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple),
!tokens.isEmpty
else { return nil }
try? self.init(rawPattern: tokens.map { "\($0)*" }.joined(separator: " "), api: api)
try? self.init(rawPattern: tokens.map { "\($0)*" }.joined(separator: " "))
}
#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.
@@ -146,14 +129,11 @@ public struct FTS3Pattern: Sendable {
/// ```
///
/// - parameter string: The string to turn into an FTS3 pattern.
public init?<API: SQLiteAPI>(
matchingPhrase string: String,
api: API.Type
) {
guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple, api: api),
public init?(matchingPhrase string: String) {
guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple),
!tokens.isEmpty
else { return nil }
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"", api: api)
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
}
}
+2 -2
View File
@@ -95,10 +95,10 @@ public struct FTS3TokenizerDescriptor: Sendable {
break
case .keep:
arguments.append("remove_diacritics=0")
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
#if GRDBCUSTOMSQLITE
case .remove:
arguments.append("remove_diacritics=2")
#else
#elseif !GRDBCIPHER
case .remove:
arguments.append("remove_diacritics=2")
#endif
+3 -6
View File
@@ -42,10 +42,7 @@ extension FTS4: VirtualTableModule {
FTS4TableDefinition(configuration: configuration)
}
public func moduleArguments(
for definition: FTS4TableDefinition,
in db: DatabaseBase<some SQLiteAPI>
) -> [String] {
public func moduleArguments(for definition: FTS4TableDefinition, in db: Database) -> [String] {
var arguments: [String] = []
for column in definition.columns {
@@ -98,7 +95,7 @@ extension FTS4: VirtualTableModule {
return arguments
}
public func database(_ db: DatabaseBase<some SQLiteAPI>, didCreate tableName: String, using definition: FTS4TableDefinition) throws {
public func database(_ db: Database, didCreate tableName: String, using definition: FTS4TableDefinition) throws {
switch definition.contentMode {
case .raw:
break
@@ -400,7 +397,7 @@ public final class FTS4ColumnDefinition {
@available(*, unavailable)
extension FTS4ColumnDefinition: Sendable { }
extension DatabaseBase {
extension Database {
/// Deletes the synchronization triggers for a synchronized FTS4 table.
///
/// See ``FTS4TableDefinition/synchronize(withTable:)``.
+16 -22
View File
@@ -1,15 +1,12 @@
#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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
@@ -63,12 +60,12 @@ public struct FTS5 {
/// Remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=1" tokenizer argument.
case removeLegacy
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
#if GRDBCUSTOMSQLITE
/// Remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=2" tokenizer argument,
/// available from SQLite 3.27.0
case remove
#else
#elseif !GRDBCIPHER
/// Remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=2" tokenizer argument,
/// available from SQLite 3.27.0
@@ -119,9 +116,9 @@ public struct FTS5 {
/// Returns a pointer to the `fts5_api` structure.
///
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#extending_fts5>
public static func api(_ db: DatabaseBase<some SQLiteAPI>) -> UnsafePointer<fts5_api> {
var statement: SQLiteStatement?
var api: UnsafePointer<fts5_api>?
public static func api(_ db: Database) -> UnsafePointer<fts5_api> {
var statement: SQLiteStatement? = nil
var api: UnsafePointer<fts5_api>? = nil
let type: StaticString = "fts5_api_ptr"
let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil)
@@ -152,10 +149,7 @@ extension FTS5: VirtualTableModule {
}
/// Don't use this method.
public func moduleArguments(
for definition: FTS5TableDefinition,
in db: DatabaseBase<some SQLiteAPI>
) throws -> [String] {
public func moduleArguments(for definition: FTS5TableDefinition, in db: Database) throws -> [String] {
var arguments: [String] = []
if definition.columns.isEmpty {
@@ -226,7 +220,7 @@ extension FTS5: VirtualTableModule {
/// Reserved; part of the VirtualTableModule protocol.
///
/// See Database.create(virtualTable:options:using:_:)
public func database(_ db: DatabaseBase<some SQLiteAPI>, didCreate tableName: String, using definition: FTS5TableDefinition) throws {
public func database(_ db: Database, didCreate tableName: String, using definition: FTS5TableDefinition) throws {
switch definition.contentMode {
case .raw:
break
@@ -534,7 +528,7 @@ extension Column {
public static let rank = Column("rank")
}
extension DatabaseBase {
extension Database {
/// Deletes the synchronization triggers for a synchronized FTS5 table.
public func dropFTS5SynchronizationTriggers(forTable tableName: String) throws {
try execute(sql: """
+11 -14
View File
@@ -1,15 +1,12 @@
#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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A type that implements a custom tokenizer for the ``FTS5`` full-text engine.
///
@@ -34,7 +31,7 @@ public protocol FTS5CustomTokenizer: FTS5Tokenizer {
///
/// - parameter db: A Database connection
/// - parameter arguments: An array of string arguments
init(db: DatabaseBase<some SQLiteAPI>, arguments: [String]) throws
init(db: Database, arguments: [String]) throws
}
extension FTS5CustomTokenizer {
@@ -52,12 +49,12 @@ extension FTS5CustomTokenizer {
}
}
extension DatabaseBase {
extension Database {
// MARK: - FTS5
private class FTS5TokenizerConstructor {
let db: DatabaseBase<some SQLiteAPI>
let db: Database
let constructor: (Database, [String], UnsafeMutablePointer<OpaquePointer?>?) -> CInt
init(
+1 -1
View File
@@ -173,7 +173,7 @@ public struct FTS5Pattern: Sendable {
}
}
extension DatabaseBase {
extension Database {
// MARK: - FTS5
+10 -13
View File
@@ -1,15 +1,12 @@
#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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
@@ -194,7 +191,7 @@ extension FTS5Tokenizer {
}
}
extension DatabaseBase {
extension Database {
// MARK: - FTS5
@@ -211,7 +208,7 @@ extension DatabaseBase {
self.xTokenizer = xTokenizer
var tokenizerPointer: OpaquePointer?
var tokenizerPointer: OpaquePointer? = nil
let code: CInt
if arguments.isEmpty {
code = xCreate(contextPointer, nil, 0, &tokenizerPointer)
+2 -2
View File
@@ -182,10 +182,10 @@ public struct FTS5TokenizerDescriptor: Sendable {
break
case .keep:
components.append(contentsOf: ["remove_diacritics", "0"])
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
#if GRDBCUSTOMSQLITE
case .remove:
components.append(contentsOf: ["remove_diacritics", "2"])
#else
#elseif !GRDBCIPHER
case .remove:
components.append(contentsOf: ["remove_diacritics", "2"])
#endif
+8 -11
View File
@@ -1,15 +1,12 @@
#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 SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
+1 -1
View File
@@ -14,7 +14,7 @@ public class DatabaseFuture<Value> { }
extension DatabasePool {
@available(*, unavailable, message: "concurrentRead has been removed. Use `asyncConcurrentRead` instead.")
public func concurrentRead<T>(_ value: @escaping (DatabaseBase<some SQLiteAPI>) throws -> T) -> DatabaseFuture<T> { preconditionFailure() }
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> { preconditionFailure() }
}
// swiftlint:enable all
+1 -1
View File
@@ -154,7 +154,7 @@ extension SQLSpecificExpressible {
}
}
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
#if GRDBCUSTOMSQLITE || GRDBCIPHER
extension SQLJSONExpressible {
/// The `->>` SQL operator.
///
+4 -4
View File
@@ -1,7 +1,7 @@
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// MARK: - JSON
extension DatabaseBase {
extension Database {
/// Validates and minifies a JSON string, with the `JSON` SQL function.
///
/// For example:
@@ -453,7 +453,7 @@ extension DatabaseBase {
// MARK: - JSONB
extension DatabaseBase {
extension Database {
public struct JSONValidationOptions: OptionSet, Sendable {
public let rawValue: Int
@@ -791,7 +791,7 @@ extension DatabaseBase {
#else
// MARK: - JSON
extension DatabaseBase {
extension Database {
/// Validates and minifies a JSON string, with the `JSON` SQL function.
///
/// For example:
+24 -166
View File
@@ -18,7 +18,6 @@ import Foundation
/// ### Registering Migrations
///
/// - ``registerMigration(_:foreignKeyChecks:migrate:)``
/// - ``registerMigration(_:foreignKeyChecks:merging:migrate:)``
/// - ``ForeignKeyChecks``
///
/// ### Configuring a DatabaseMigrator
@@ -162,8 +161,9 @@ public struct DatabaseMigrator: Sendable {
/// Registers a migration.
///
/// The registered migration is appended to the list of migrations. It
/// will execute after previously registered migrations.
/// The registered migration is appended to the list of migrations to run:
/// it will execute after previously registered migrations, and before
/// migrations that are registered later.
///
/// For example:
///
@@ -213,108 +213,7 @@ public struct DatabaseMigrator: Sendable {
public mutating func registerMigration(
_ identifier: String,
foreignKeyChecks: ForeignKeyChecks = .deferred,
migrate: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> Void)
{
registerMigration(identifier, foreignKeyChecks: foreignKeyChecks, merging: []) { db, ids in
precondition(ids.isEmpty)
try migrate(db)
}
}
/// Registers a merged migration.
///
/// Like migrations registered with ``registerMigration(_:foreignKeyChecks:migrate:)``,
/// the merged migration is appended to the list of migrations. It
/// will execute after previously registered migrations.
///
/// A merged migration merges and replaces a set of migrations defined
/// in a previous version of the application. For example, to merge the
/// migrations "v1", "v2" and "v3", redefine the "v3" migration so that
/// it merges "v1" and "v2", as in the example below.
///
/// The second argument of the `migrate` closure is the subset of merged
/// migrations that have already been applied when the merged
/// migration runs.
///
/// ```swift
/// // Old code
/// migrator.registerMigration("v1") { db in
/// // Apply schema version 1
/// }
/// migrator.registerMigration("v2") { db in
/// // Apply schema version 2
/// }
/// migrator.registerMigration("v3") { db in
/// // Apply schema version 3
/// }
///
/// // New code:
/// // - Migrations v1 and v2 are deleted.
/// // - Migration v3 is redefined and merges v1 and v2:
/// migrator.registerMigration("v3", merging: ["v1", "v2"]) { db, appliedIDs in
/// if !appliedIDs.contains("v1") {
/// // Apply schema version 1
/// }
/// if !appliedIDs.contains("v2") {
/// // Apply schema version 2
/// }
/// // Apply schema version 3
/// }
/// ```
///
/// In the above sample code, the merged migration is named like the
/// last one of the merged set. You can also give it a brand new name,
/// as in the alternative below. Notice the different logic in the
/// migration code.
///
/// **In all cases avoid naming the merged migration like the first
/// elements in the merged set** (`v1` or `v2` in our example).
///
/// ```swift
/// // Alternative new code:
/// // - Migrations v1, v2 and v3 are deleted.
/// // - The new migration v3-new merges v1, v2 and v3:
/// migrator.registerMigration("v3-new", merging: ["v1", "v2", "v3"]) { db, appliedIDs in
/// if !appliedIDs.contains("v1") {
/// // Apply schema version 1
/// }
/// if !appliedIDs.contains("v2") {
/// // Apply schema version 2
/// }
/// if !appliedIDs.contains("v3") {
/// // Apply schema version 3
/// }
/// }
/// ```
///
/// - parameters:
/// - identifier: The migration identifier.
/// - mergedIdentifiers: A set of previous migration identifiers
/// that are merged in this migration.
/// - foreignKeyChecks: This parameter is ignored if the database
/// ``Configuration`` has disabled foreign keys.
///
/// The default `.deferred` checks have the migration run with
/// disabled foreign keys, until foreign keys are checked right before
/// changes are committed on disk. These deferred checks are not
/// executed if the migrator is the result of
/// ``disablingDeferredForeignKeyChecks()``.
///
/// The `.immediate` checks have the migration run with foreign
/// keys enabled. Make sure you only use `.immediate` if the migration
/// does not perform schema changes described in
/// <https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes>
/// - migrate: A closure that performs database operations. The
/// first argument is a database connection. The second argument
/// is the set of previous migrations that has been applied when
/// the merged migration runs.
/// - precondition: No migration with the same identifier as already
/// been registered.
public mutating func registerMigration(
_ identifier: String,
foreignKeyChecks: ForeignKeyChecks = .deferred,
merging mergedIdentifiers: Set<String> = [],
migrate: @escaping @Sendable (_ db: DatabaseBase<some SQLiteAPI>, _ appliedIdentifiers: Set<String>) throws -> Void)
migrate: @escaping @Sendable (Database) throws -> Void)
{
let migrationChecks: Migration.ForeignKeyChecks
switch foreignKeyChecks {
@@ -327,18 +226,7 @@ public struct DatabaseMigrator: Sendable {
case .immediate:
migrationChecks = .immediate
}
// Remove the migration identifier from the list of merged identifiers.
// Arguably, the semantics are ambiguous. And raising a fatal error
// is a high price when we can just fix the input.
var mergedIdentifiers = mergedIdentifiers
mergedIdentifiers.remove(identifier)
registerMigration(Migration(
identifier: identifier,
mergedIdentifiers: mergedIdentifiers,
foreignKeyChecks: migrationChecks,
migrate: migrate))
registerMigration(Migration(identifier: identifier, foreignKeyChecks: migrationChecks, migrate: migrate))
}
// MARK: - Applying Migrations
@@ -382,7 +270,7 @@ public struct DatabaseMigrator: Sendable {
/// from succeeding.
public func asyncMigrate(
_ writer: any DatabaseWriter,
completion: @escaping @Sendable (Result<DatabaseBase<some SQLiteAPI>, Error>) -> Void)
completion: @escaping @Sendable (Result<Database, Error>) -> Void)
{
writer.asyncBarrierWriteWithoutTransaction { dbResult in
do {
@@ -424,7 +312,7 @@ public struct DatabaseMigrator: Sendable {
/// try migrator.migrate(dbQueue)
/// ```
///
public func hasSchemaChanges(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool {
public func hasSchemaChanges(_ db: Database) throws -> Bool {
let appliedIdentifiers = try appliedIdentifiers(db)
let knownIdentifiers = Set(_migrations.map { $0.identifier })
if !appliedIdentifiers.isSubset(of: knownIdentifiers) {
@@ -500,7 +388,7 @@ public struct DatabaseMigrator: Sendable {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func appliedMigrations(_ db: DatabaseBase<some SQLiteAPI>) throws -> [String] {
public func appliedMigrations(_ db: Database) throws -> [String] {
let appliedIdentifiers = try self.appliedIdentifiers(db)
return _migrations.map { $0.identifier }.filter { appliedIdentifiers.contains($0) }
}
@@ -509,7 +397,7 @@ public struct DatabaseMigrator: Sendable {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func appliedIdentifiers(_ db: DatabaseBase<some SQLiteAPI>) throws -> Set<String> {
public func appliedIdentifiers(_ db: Database) throws -> Set<String> {
do {
return try String.fetchSet(db, sql: "SELECT identifier FROM grdb_migrations")
} catch {
@@ -529,7 +417,7 @@ public struct DatabaseMigrator: Sendable {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func completedMigrations(_ db: DatabaseBase<some SQLiteAPI>) throws -> [String] {
public func completedMigrations(_ db: Database) throws -> [String] {
let appliedIdentifiers = try appliedMigrations(db)
let knownIdentifiers = _migrations.map(\.identifier)
return zip(appliedIdentifiers, knownIdentifiers)
@@ -542,7 +430,7 @@ public struct DatabaseMigrator: Sendable {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func hasCompletedMigrations(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool {
public func hasCompletedMigrations(_ db: Database) throws -> Bool {
try completedMigrations(db).last == _migrations.last?.identifier
}
@@ -554,7 +442,7 @@ public struct DatabaseMigrator: Sendable {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func hasBeenSuperseded(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool {
public func hasBeenSuperseded(_ db: Database) throws -> Bool {
let appliedIdentifiers = try self.appliedIdentifiers(db)
let knownIdentifiers = _migrations.map(\.identifier)
return appliedIdentifiers.contains { !knownIdentifiers.contains($0) }
@@ -562,16 +450,6 @@ public struct DatabaseMigrator: Sendable {
// MARK: - Non public
private struct Execution {
enum Mode {
case run(mergedIdentifiers: Set<String>)
case deleteMergedIdentifiers
}
var migration: Migration
var mode: Mode
}
private mutating func registerMigration(_ migration: Migration) {
GRDBPrecondition(
!_migrations.map({ $0.identifier }).contains(migration.identifier),
@@ -579,8 +457,8 @@ public struct DatabaseMigrator: Sendable {
_migrations.append(migration)
}
/// Returns unapplied migration executions
private func unappliedExecutions(upTo targetIdentifier: String, appliedIdentifiers: Set<String>) -> [Execution] {
/// Returns unapplied migration identifier,
private func unappliedMigrations(upTo targetIdentifier: String, appliedIdentifiers: [String]) -> [Migration] {
var expectedMigrations: [Migration] = []
for migration in _migrations {
expectedMigrations.append(migration)
@@ -594,56 +472,36 @@ public struct DatabaseMigrator: Sendable {
expectedMigrations.last?.identifier == targetIdentifier,
"undefined migration: \(String(reflecting: targetIdentifier))")
return expectedMigrations.compactMap { migration in
if appliedIdentifiers.contains(migration.identifier) {
if migration.mergedIdentifiers.isDisjoint(with: appliedIdentifiers) {
// Nothing to do
return nil
} else {
// Migration is applied, but we have some merged identifiers to delete
return Execution(migration: migration, mode: .deleteMergedIdentifiers)
}
} else {
// Migration is not applied yet.
let appliedMergedIdentifiers = migration.mergedIdentifiers.intersection(appliedIdentifiers)
return Execution(migration: migration, mode: .run(mergedIdentifiers: appliedMergedIdentifiers))
}
}
return expectedMigrations.filter { !appliedIdentifiers.contains($0.identifier) }
}
private func runMigrations(_ db: DatabaseBase<some SQLiteAPI>, upTo targetIdentifier: String) throws {
private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws {
try db.execute(sql: "CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)")
let appliedIdentifiers = try self.appliedMigrations(db)
// Subsequent migration must not be applied
let appliedMigrations = try self.appliedMigrations(db) // Only known ids
if let targetIndex = _migrations.firstIndex(where: { $0.identifier == targetIdentifier }),
let lastAppliedMigration = appliedMigrations.last,
let lastAppliedIndex = _migrations.firstIndex(where: { $0.identifier == lastAppliedMigration }),
let lastAppliedIdentifier = appliedIdentifiers.last,
let lastAppliedIndex = _migrations.firstIndex(where: { $0.identifier == lastAppliedIdentifier }),
targetIndex < lastAppliedIndex
{
fatalError("database is already migrated beyond migration \(String(reflecting: targetIdentifier))")
}
let appliedIdentifiers = try self.appliedIdentifiers(db) // All ids, even unknown ones
let unappliedExecutions = self.unappliedExecutions(
let unappliedMigrations = self.unappliedMigrations(
upTo: targetIdentifier,
appliedIdentifiers: appliedIdentifiers)
if unappliedExecutions.isEmpty {
if unappliedMigrations.isEmpty {
return
}
for execution in unappliedExecutions {
switch execution.mode {
case .run(let mergedIdentifiers):
try execution.migration.run(db, mergedIdentifiers: mergedIdentifiers)
case .deleteMergedIdentifiers:
try execution.migration.deleteMergedIdentifiers(db)
}
for migration in unappliedMigrations {
try migration.run(db)
}
}
private func migrate(_ db: DatabaseBase<some SQLiteAPI>, upTo targetIdentifier: String) throws {
private func migrate(_ db: Database, upTo targetIdentifier: String) throws {
if eraseDatabaseOnSchemaChange {
var needsErase = false
try db.inTransaction(.deferred) {
+23 -52
View File
@@ -6,68 +6,40 @@ struct Migration: Sendable {
case disabled
}
typealias Migrate = @Sendable (_ db: DatabaseBase<some SQLiteAPI>, _ mergedIdentifiers: Set<String>) throws -> Void
let identifier: String
let mergedIdentifiers: Set<String>
var foreignKeyChecks: ForeignKeyChecks
// Private so that the guarantees of `run(_:)` are enforced.
private let migrate: Migrate
let migrate: @Sendable (Database) throws -> Void
init(
identifier: String,
mergedIdentifiers: Set<String>,
foreignKeyChecks: ForeignKeyChecks,
migrate: @escaping Migrate
) {
self.identifier = identifier
self.mergedIdentifiers = mergedIdentifiers
self.foreignKeyChecks = foreignKeyChecks
self.migrate = migrate
}
func run(_ db: DatabaseBase<some SQLiteAPI>, mergedIdentifiers: Set<String>) 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.
try db.withSchemaSource(nil) {
if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false {
switch foreignKeyChecks {
case .deferred:
try runWithDeferredForeignKeysChecks(db, mergedIdentifiers: mergedIdentifiers)
case .immediate:
try runWithImmediateForeignKeysChecks(db, mergedIdentifiers: mergedIdentifiers)
case .disabled:
try runWithDisabledForeignKeysChecks(db, mergedIdentifiers: mergedIdentifiers)
}
} else {
try runWithImmediateForeignKeysChecks(db, mergedIdentifiers: mergedIdentifiers)
func run(_ db: Database) throws {
if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false {
switch foreignKeyChecks {
case .deferred:
try runWithDeferredForeignKeysChecks(db)
case .immediate:
try runWithImmediateForeignKeysChecks(db)
case .disabled:
try runWithDisabledForeignKeysChecks(db)
}
} else {
try runWithImmediateForeignKeysChecks(db)
}
}
func deleteMergedIdentifiers(_ db: DatabaseBase<some SQLiteAPI>) throws {
if mergedIdentifiers.isEmpty == false {
try db.execute(literal: "DELETE FROM grdb_migrations WHERE identifier IN \(mergedIdentifiers)")
}
}
private func runWithImmediateForeignKeysChecks(_ db: DatabaseBase<some SQLiteAPI>, mergedIdentifiers: Set<String>) throws {
private func runWithImmediateForeignKeysChecks(_ db: Database) throws {
try db.inTransaction(.immediate) {
try migrate(db, mergedIdentifiers)
try updateAppliedIdentifier(db)
try migrate(db)
try insertAppliedIdentifier(db)
return .commit
}
}
private func runWithDisabledForeignKeysChecks(_ db: DatabaseBase<some SQLiteAPI>, mergedIdentifiers: Set<String>) throws {
private func runWithDisabledForeignKeysChecks(_ db: Database) throws {
try db.execute(sql: "PRAGMA foreign_keys = OFF")
try throwingFirstError(
execute: {
try db.inTransaction(.immediate) {
try migrate(db, mergedIdentifiers)
try updateAppliedIdentifier(db)
try migrate(db)
try insertAppliedIdentifier(db)
return .commit
}
},
@@ -76,7 +48,7 @@ struct Migration: Sendable {
})
}
private func runWithDeferredForeignKeysChecks(_ db: DatabaseBase<some SQLiteAPI>, mergedIdentifiers: Set<String>) throws {
private func runWithDeferredForeignKeysChecks(_ db: Database) throws {
// Support for database alterations described at
// https://www.sqlite.org/lang_altertable.html#otheralter
//
@@ -88,8 +60,8 @@ struct Migration: Sendable {
execute: {
// > 2. Start a transaction.
try db.inTransaction(.immediate) {
try migrate(db, mergedIdentifiers)
try updateAppliedIdentifier(db)
try migrate(db)
try insertAppliedIdentifier(db)
// > 10. If foreign key constraints were originally enabled
// > then run PRAGMA foreign_key_check to verify that the
@@ -108,8 +80,7 @@ struct Migration: Sendable {
})
}
private func updateAppliedIdentifier(_ db: DatabaseBase<some SQLiteAPI>) throws {
try deleteMergedIdentifiers(db)
try db.execute(literal: "INSERT INTO grdb_migrations (identifier) VALUES (\(identifier))")
private func insertAppliedIdentifier(_ db: Database) throws {
try db.execute(sql: "INSERT INTO grdb_migrations (identifier) VALUES (?)", arguments: [identifier])
}
}
@@ -173,10 +173,8 @@ extension Association {
// SelectionRequest conformance
extension Association {
#warning("TODO: expose a version with default api")
public func selectWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ selection: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLSelectable]
public func selectWhenConnected(
_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]
) -> Self {
withDestinationRelation { relation in
relation = relation.selectWhenConnected { db in
@@ -185,10 +183,8 @@ extension Association {
}
}
#warning("TODO: expose a version with default api")
public func annotatedWhenConnected<API: SQLiteAPI>(
api: API.Type,
with selection: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLSelectable]
public func annotatedWhenConnected(
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]
) -> Self {
withDestinationRelation { relation in
relation = relation.annotatedWhenConnected { db in
@@ -200,10 +196,8 @@ extension Association {
// FilteredRequest conformance
extension Association {
#warning("TODO: expose a version with default api")
public func filterWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ predicate: @escaping @Sendable (DatabaseBase<API>) throws -> any SQLExpressible
public func filterWhenConnected(
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible
) -> Self {
withDestinationRelation { relation in
relation = relation.filterWhenConnected { db in
@@ -215,10 +209,8 @@ extension Association {
// OrderedRequest conformance
extension Association {
#warning("TODO: expose a version with default api")
public func orderWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ orderings: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLOrderingTerm]
public func orderWhenConnected(
_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm]
) -> Self {
withDestinationRelation { relation in
relation = relation.orderWhenConnected { db in
@@ -255,10 +247,8 @@ extension Association {
// AggregatingRequest conformance
extension Association {
#warning("TODO: expose a version with default api")
public func groupWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ expressions: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLExpressible]
public func groupWhenConnected(
_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible]
) -> Self {
withDestinationRelation { relation in
relation = relation.groupWhenConnected { db in
@@ -267,10 +257,8 @@ extension Association {
}
}
#warning("TODO: expose a version with default api")
public func havingWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ predicate: @escaping @Sendable (DatabaseBase<API>) throws -> any SQLExpressible
public func havingWhenConnected(
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible
) -> Self {
withDestinationRelation { relation in
relation = relation.havingWhenConnected { db in
@@ -636,7 +636,7 @@ public struct AssociationAggregate<RowDecoder> {
fileprivate let preparation: AssociationAggregatePreparation<RowDecoder>
/// The SQL name for the value of this aggregate. See forKey(_:).
var key: String?
var key: String? = nil
/// Extends the request with the associated records used to compute the
/// aggregate, and returns the aggregated expression.
@@ -1131,7 +1131,7 @@ public func abs<RowDecoder>(_ aggregate: AssociationAggregate<RowDecoder>)
/// Related SQLite documentation: <https://www.sqlite.org/lang_expr.html#castexpr>
public func cast<RowDecoder>(
_ aggregate: AssociationAggregate<RowDecoder>,
as storageClass: DatabaseStorageClass)
as storageClass: Database.StorageClass)
-> AssociationAggregate<RowDecoder>
{
aggregate
@@ -333,7 +333,7 @@ struct SQLCTE {
var isRecursive: Bool
/// The number of columns in the common table expression.
func columnCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
func columnCount(_ db: Database) throws -> Int {
if let columns {
// No need to hit the database
return columns.count
@@ -106,14 +106,14 @@ extension QueryInterfaceRequest: FetchRequest {
.relation(relation)
}
public func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
public func fetchCount(_ db: Database) throws -> Int {
try relation.fetchCount(db)
}
public func makePreparedRequest<API>(
_ db: DatabaseBase<API>,
public func makePreparedRequest(
_ db: Database,
forSingleResult singleResult: Bool = false)
throws -> PreparedRequestBase<API>
throws -> PreparedRequest
{
let generator = SQLQueryGenerator(relation: relation, forSingleResult: singleResult)
var preparedRequest = try generator.makePreparedRequest(db)
@@ -136,10 +136,8 @@ extension QueryInterfaceRequest: FetchRequest {
// MARK: - Request Derivation
extension QueryInterfaceRequest: SelectionRequest {
#warning("TODO: expose a version with default api")
public func selectWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ selection: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLSelectable])
public func selectWhenConnected(
_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
-> Self
{
with {
@@ -362,23 +360,19 @@ extension QueryInterfaceRequest: SelectionRequest {
/// .fetchSet(db)
/// ```
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
where RowDecoder: Identifiable
where RowDecoder: Identifiable & SendableMetatype
{
let databaseTableName = self.databaseTableName
return selectWhenConnected { db in
let primaryKey = try db.primaryKey(databaseTableName)
selectWhenConnected { db in
let primaryKey = try db.primaryKey(self.databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"selectID requires a single-column primary key in the table \(databaseTableName)")
"selectID requires a single-column primary key in the table \(self.databaseTableName)")
return [Column(primaryKey.columns[0])]
}.asRequest(of: RowDecoder.ID.self)
}
#warning("TODO: expose a version with default api")
public func annotatedWhenConnected<API: SQLiteAPI>(
api: API.Type,
with selection: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLSelectable])
public func annotatedWhenConnected(
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
-> Self
{
with {
@@ -390,10 +384,8 @@ extension QueryInterfaceRequest: SelectionRequest {
}
extension QueryInterfaceRequest: FilteredRequest {
#warning("TODO: expose a version with default api")
public func filterWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ predicate: @escaping @Sendable (DatabaseBase<API>) throws -> any SQLExpressible)
public func filterWhenConnected(
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible)
-> Self
{
with {
@@ -405,10 +397,8 @@ extension QueryInterfaceRequest: FilteredRequest {
}
extension QueryInterfaceRequest: OrderedRequest {
#warning("TODO: expose a version with default api")
public func orderWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ orderings: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLOrderingTerm])
public func orderWhenConnected(
_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm])
-> Self
{
with {
@@ -475,10 +465,8 @@ extension QueryInterfaceRequest: OrderedRequest {
}
extension QueryInterfaceRequest: AggregatingRequest {
#warning("TODO: expose a version with default api")
public func groupWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ expressions: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLExpressible])
public func groupWhenConnected(
_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible])
-> Self
{
with {
@@ -488,10 +476,8 @@ extension QueryInterfaceRequest: AggregatingRequest {
}
}
#warning("TODO: expose a version with default api")
public func havingWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ predicate: @escaping @Sendable (DatabaseBase<API>) throws -> any SQLExpressible)
public func havingWhenConnected(
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible)
-> Self
{
with {
@@ -631,7 +617,7 @@ extension QueryInterfaceRequest {
/// ```
///
/// - parameter db: A database connection.
public func isEmpty(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool {
public func isEmpty(_ db: Database) throws -> Bool {
try !SQLRequest("SELECT \(exists())").fetchOne(db)!
}
}
@@ -645,20 +631,17 @@ extension QueryInterfaceRequest {
/// - returns: The number of deleted rows
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@discardableResult
public func deleteAll(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
public func deleteAll(_ db: Database) throws -> Int {
let statement = try SQLQueryGenerator(relation: relation).makeDeleteStatement(db)
var changesCount = 0
try db.countChanges(&changesCount, forTable: relation.source.tableName) {
try statement.execute()
}
return changesCount
try statement.execute()
return db.changesCount
}
}
// MARK: - Batch Delete and Fetch
extension QueryInterfaceRequest {
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Returns a `DELETE RETURNING` prepared statement.
///
/// For example:
@@ -680,10 +663,11 @@ extension QueryInterfaceRequest {
/// - returns: A prepared statement.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: `selection` is not empty.
public func deleteAndFetchStatement<API>(
_ db: DatabaseBase<API>,
selection: [any SQLSelectable]
) throws -> StatementBase<API> {
public func deleteAndFetchStatement(
_ db: Database,
selection: [any SQLSelectable])
throws -> Statement
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection)
}
@@ -717,7 +701,7 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The result of `select` is not empty.
public func deleteAndFetchStatement(
_ db: DatabaseBase<some SQLiteAPI>,
_ db: Database,
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> Statement
where RowDecoder: TableRecord
@@ -747,7 +731,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: DatabaseBase<some SQLiteAPI>)
public func deleteAndFetchCursor(_ db: Database)
throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
{
@@ -774,7 +758,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: DatabaseBase<some SQLiteAPI>)
public func deleteAndFetchAll(_ db: Database)
throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
{
@@ -800,7 +784,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: DatabaseBase<some SQLiteAPI>)
public func deleteAndFetchSet(_ db: Database)
throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
{
@@ -826,7 +810,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: DatabaseBase<some SQLiteAPI>)
public func deleteAndFetchIds(_ db: Database)
throws -> Set<RowDecoder.ID>
where RowDecoder: TableRecord & Identifiable,
RowDecoder.ID: Hashable & DatabaseValueConvertible & StatementColumnConvertible
@@ -863,10 +847,11 @@ 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<API>(
_ db: DatabaseBase<API>,
selection: [any SQLSelectable]
) throws -> StatementBase<API> {
public func deleteAndFetchStatement(
_ db: Database,
selection: [any SQLSelectable])
throws -> Statement
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection)
}
@@ -901,7 +886,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: DatabaseBase<some SQLiteAPI>,
_ db: Database,
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> Statement
where RowDecoder: TableRecord
@@ -932,7 +917,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: DatabaseBase<some SQLiteAPI>)
public func deleteAndFetchCursor(_ db: Database)
throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
{
@@ -960,7 +945,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: DatabaseBase<some SQLiteAPI>)
public func deleteAndFetchAll(_ db: Database)
throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
{
@@ -987,7 +972,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: DatabaseBase<some SQLiteAPI>)
public func deleteAndFetchSet(_ db: Database)
throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
{
@@ -1014,7 +999,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: DatabaseBase<some SQLiteAPI>)
public func deleteAndFetchIds(_ db: Database)
throws -> Set<RowDecoder.ID>
where RowDecoder: TableRecord & Identifiable,
RowDecoder.ID: Hashable & DatabaseValueConvertible & StatementColumnConvertible
@@ -1035,7 +1020,7 @@ extension QueryInterfaceRequest {
extension QueryInterfaceRequest {
/// The conflict resolution to use for batch updates
private var defaultConflictResolutionForUpdate: DatabaseConflictResolution {
private var defaultConflictResolutionForUpdate: Database.ConflictResolution {
// 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
@@ -1072,8 +1057,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@discardableResult
public func updateAll(
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignment: (DatabaseComponents) throws -> ColumnAssignment
) throws -> Int
where RowDecoder: TableRecord
@@ -1107,8 +1092,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@discardableResult
public func updateAll(
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> Int
where RowDecoder: TableRecord
@@ -1135,8 +1120,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@discardableResult
public func updateAll(
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment]) throws -> Int
{
let conflictResolution = conflictResolution ?? defaultConflictResolutionForUpdate
@@ -1148,11 +1133,8 @@ extension QueryInterfaceRequest {
// database not hit
return 0
}
var changesCount = 0
try db.countChanges(&changesCount, forTable: relation.source.tableName) {
try updateStatement.execute()
}
return changesCount
try updateStatement.execute()
return db.changesCount
}
/// Updates matching rows, and returns the number of updated rows.
@@ -1174,8 +1156,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@discardableResult
public func updateAll(
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: ColumnAssignment...)
throws -> Int
{
@@ -1186,7 +1168,7 @@ extension QueryInterfaceRequest {
// MARK: - Batch Update and Fetch
extension QueryInterfaceRequest {
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Returns an `UPDATE RETURNING` prepared statement.
///
/// For example:
@@ -1224,8 +1206,8 @@ extension QueryInterfaceRequest {
/// - precondition: The results of `select` and `assignments` results
/// are not empty.
public func updateAndFetchStatement(
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment],
select: (DatabaseComponents) -> [any SQLSelectable]
) throws -> Statement
@@ -1265,8 +1247,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: `selection` and `assignments` are not empty.
public func updateAndFetchStatement(
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment],
selection: [any SQLSelectable])
throws -> Statement
@@ -1319,8 +1301,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The result of `assignments` is not empty.
public func updateAndFetchCursor(
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
@@ -1354,8 +1336,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: `assignments` is not empty.
public func updateAndFetchCursor(
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
@@ -1398,8 +1380,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The result of `assignments` is not empty.
public func updateAndFetchAll(
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
@@ -1430,8 +1412,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: `assignments` is not empty.
public func updateAndFetchAll(
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
@@ -1469,8 +1451,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The result of `assignments` is not empty.
public func updateAndFetchSet(
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
@@ -1501,8 +1483,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: `assignments` is not empty.
public func updateAndFetchSet(
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
@@ -1548,8 +1530,8 @@ extension QueryInterfaceRequest {
/// are not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetchStatement(
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment],
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> Statement
@@ -1590,8 +1572,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: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment],
selection: [any SQLSelectable])
throws -> Statement
@@ -1645,8 +1627,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: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
@@ -1681,8 +1663,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: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
@@ -1726,8 +1708,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: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
@@ -1759,8 +1741,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: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
@@ -1799,8 +1781,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: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
@@ -1832,8 +1814,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: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
@@ -2154,7 +2136,7 @@ extension ColumnExpression {
/// - parameter willExecuteSupplementaryRequest: A closure executed before a
/// supplementary fetch is performed.
private func prefetch(
_ db: DatabaseBase<some SQLiteAPI>,
_ db: Database,
associations: [_SQLAssociation],
from originRelation: SQLRelation,
into originRows: [Row],
@@ -2321,7 +2303,7 @@ func makePrefetchRequest(
// CAUTION: Keep this code in sync with prefetch(_:associations:in:)
/// Returns the region of prefetched associations
func prefetchedRegion(
_ db: DatabaseBase<some SQLiteAPI>,
_ db: Database,
associations: [_SQLAssociation],
from originTable: String)
throws -> DatabaseRegion
@@ -2343,7 +2325,7 @@ throws -> DatabaseRegion
// CAUTION: Keep this code in sync with prefetch(_:associations:in:)
func prefetchedRegion(
_ db: DatabaseBase<some SQLiteAPI>,
_ db: Database,
association: _SQLAssociation,
pivotMapping: JoinMapping)
throws -> DatabaseRegion
@@ -40,7 +40,6 @@ public protocol TypedRequest<RowDecoder> {
/// - ``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
@@ -68,12 +67,10 @@ public protocol SelectionRequest {
///
/// - parameter selection: A closure that accepts a database connection and
/// returns an array of result columns.
func selectWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ selection: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLSelectable]
func selectWhenConnected(
_ selection: @escaping @Sendable (Database) 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
@@ -92,9 +89,8 @@ public protocol SelectionRequest {
///
/// - parameter selection: A closure that accepts a database connection and
/// returns an array of result columns.
func annotatedWhenConnected<API: SQLiteAPI>(
api: API.Type,
with selection: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLSelectable]
func annotatedWhenConnected(
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]
) -> Self
}
@@ -362,7 +358,6 @@ 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
@@ -382,9 +377,8 @@ public protocol FilteredRequest {
///
/// - parameter predicate: A closure that accepts a database connection and
/// returns a boolean SQL expression.
func filterWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ predicate: @escaping @Sendable (DatabaseBase<$API>) throws -> any SQLExpressible
func filterWhenConnected(
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible
) -> Self
}
@@ -753,10 +747,7 @@ 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<API: SQLiteAPI>(
api: API.Type,
keys: @escaping @Sendable (DatabaseBase<API>) throws -> [SQLExpression]
) -> Self {
fileprivate func filterWhenConnected(keys: @escaping @Sendable (Database) 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
@@ -835,17 +826,10 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
// ("foo", "bar") do not contain a unique key (primary key
// or unique index).
guard let columns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else {
if (try? db.viewExists(databaseTableName)) == true {
fatalError("""
database view \(databaseTableName) has no unique key on column(s) \
\(key.keys.sorted().joined(separator: ", "))
""")
} else {
fatalError("""
table \(databaseTableName) has no unique key on column(s) \
\(key.keys.sorted().joined(separator: ", "))
""")
}
fatalError("""
table \(databaseTableName) has no unique key on column(s) \
\(key.keys.sorted().joined(separator: ", "))
""")
}
let lowercaseColumns = columns.map { $0.lowercased() }
@@ -1001,7 +985,6 @@ 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
@@ -1024,12 +1007,10 @@ public protocol AggregatingRequest {
///
/// - parameter expressions: A closure that accepts a database connection
/// and returns an array of SQL expressions.
func groupWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ expressions: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLExpressible]
func groupWhenConnected(
_ expressions: @escaping @Sendable (Database) 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
@@ -1052,9 +1033,8 @@ public protocol AggregatingRequest {
///
/// - parameter predicate: A closure that accepts a database connection and
/// returns a boolean SQL expression.
func havingWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ predicate: @escaping @Sendable (DatabaseBase<API>) throws -> any SQLExpressible
func havingWhenConnected(
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible
) -> Self
}
@@ -1283,7 +1263,6 @@ 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
@@ -1311,9 +1290,8 @@ public protocol OrderedRequest {
///
/// - parameter orderings: A closure that accepts a database connection and
/// returns an array of SQL ordering terms.
func orderWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ orderings: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLOrderingTerm]
func orderWhenConnected(
_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm]
) -> Self
/// Returns a request with reversed ordering.
@@ -23,7 +23,7 @@
/// see SQLRelation.filterPromise.
struct DatabasePromise<T> {
/// Returns the resolved value.
let resolve: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> T
let resolve: @Sendable (Database) throws -> T
/// Creates a promise that resolves to a value.
init(value: T) where T: Sendable {
@@ -31,7 +31,7 @@ struct DatabasePromise<T> {
}
/// Creates a promise from a closure.
init(_ resolve: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> T) {
init(_ resolve: @escaping @Sendable (Database) throws -> T) {
self.resolve = resolve
}
+14 -14
View File
@@ -99,7 +99,7 @@ public struct SQLExpression: Sendable {
/// The `CAST(expr AS storage-class)` expression.
///
/// See <https://www.sqlite.org/lang_expr.html#castexpr>.
indirect case cast(SQLExpression, DatabaseStorageClass)
indirect case cast(SQLExpression, Database.StorageClass)
/// The `BETWEEN` and `NOT BETWEEN` operators.
///
@@ -517,7 +517,7 @@ public struct SQLExpression: Sendable {
/// The `>>` bitwise right shift operator
static let rightShift = BinaryOperator(">>")
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `->` SQL operator
static let jsonExtractJSON = BinaryOperator("->", isJSONValue: true)
@@ -1135,7 +1135,7 @@ extension SQLExpression {
/// The `CAST(expr AS storage-class)` expression.
///
/// See <https://www.sqlite.org/lang_expr.html#castexpr>.
static func cast(_ expression: SQLExpression, as storageClass: DatabaseStorageClass) -> Self {
static func cast(_ expression: SQLExpression, as storageClass: Database.StorageClass) -> 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: DatabaseBase<some SQLiteAPI>) throws -> String {
func quotedSQL(_ db: Database) 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: DatabaseBase<some SQLiteAPI>, for alias: TableAliasBase, acceptsBijection: Bool = false) throws -> String? {
func column(_ db: Database, 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: DatabaseBase<some SQLiteAPI>, for alias: TableAliasBase) throws -> Set<String> {
func identifyingColums(_ db: Database, for alias: TableAliasBase) throws -> Set<String> {
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: DatabaseBase<some SQLiteAPI>, for alias: TableAliasBase) throws -> Set<Int64>? {
func identifyingRowIDs(_ db: Database, for alias: TableAliasBase) throws -> Set<Int64>? {
switch impl {
case let .databaseValue(dbValue):
if dbValue.isNull || dbValue == false.databaseValue {
@@ -1592,7 +1592,7 @@ extension SQLExpression {
case let .associativeBinary(op, expressions):
assert(expressions.count > 1)
if op == .and {
var result: Set<Int64>?
var result: Set<Int64>? = nil
for expression in expressions {
if let expressionRowIDs = try expression.identifyingRowIDs(db, for: alias) {
if var rowIDs = result {
@@ -1993,7 +1993,7 @@ struct SQLSimpleFunctionInvocation {
isJSONValue: isJSONValue)
}
func column(_ db: DatabaseBase<some SQLiteAPI>, for alias: TableAliasBase) throws -> String? {
func column(_ db: Database, 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)
@@ -2020,8 +2020,8 @@ struct SQLAggregateFunctionInvocation {
var name: String
var arguments: [SQLExpression]
var isDistinct = false
var ordering: SQLOrdering? // SQLite 3.44.0+
var filter: SQLExpression? // @available(iOS 14, macOS 10.16, tvOS 14, *) SQLite 3.30+
var ordering: SQLOrdering? = nil // SQLite 3.44.0+
var filter: SQLExpression? = nil // @available(iOS 14, macOS 10.16, tvOS 14, *) SQLite 3.30+
/// A boolean value indicating if a function is known to return a
/// JSON value.
@@ -2121,7 +2121,7 @@ extension SQLExpression {
}
}
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Returns an expression suitable in JSON building contexts.
var jsonBuilderExpression: SQLExpression {
switch preferredJSONInterpretation {
@@ -2373,7 +2373,7 @@ extension SQLSpecificExpressible {
.desc(sqlExpression)
}
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
#if GRDBCUSTOMSQLITE
/// An ordering term for ascending order (nulls last).
public var ascNullsLast: SQLOrdering {
.ascNullsLast(sqlExpression)
@@ -2383,7 +2383,7 @@ extension SQLSpecificExpressible {
public var descNullsFirst: SQLOrdering {
.descNullsFirst(sqlExpression)
}
#else
#elseif !GRDBCIPHER
/// An ordering term for ascending order (nulls last).
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+
public var ascNullsLast: SQLOrdering {
@@ -21,7 +21,7 @@ struct SQLForeignKeyRequest {
}
/// The (origin, destination) column pairs that join a left table to a right table.
func fetchForeignKeyMapping(_ db: DatabaseBase<some SQLiteAPI>) throws -> ForeignKeyMapping {
func fetchForeignKeyMapping(_ db: Database) 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,8 +122,8 @@ struct SQLForeignKeyRequest {
var isView: Bool
}
private func tableType(_ db: DatabaseBase<some SQLiteAPI>, for name: String) throws -> TableType? {
for schemaID in try db.fetchSchemaIdentifiers() {
private func tableType(_ db: Database, for name: String) throws -> TableType? {
for schemaID in try db.schemaIdentifiers() {
if try db.schema(schemaID).containsObjectNamed(name, ofType: .table) {
return TableType(isView: false)
}
+6 -6
View File
@@ -10,7 +10,7 @@ public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression {
.function("ABS", [value.sqlExpression])
}
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `AVG` SQL aggregate function.
///
/// For example:
@@ -67,7 +67,7 @@ public func average(_ value: some SQLSpecificExpressible) -> SQLExpression {
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_expr.html#castexpr>
public func cast(_ expression: some SQLSpecificExpressible, as storageClass: DatabaseStorageClass) -> SQLExpression {
public func cast(_ expression: some SQLSpecificExpressible, as storageClass: Database.StorageClass) -> SQLExpression {
.cast(expression.sqlExpression, as: storageClass)
}
@@ -163,7 +163,7 @@ public func max(
.simpleFunction("MAX", [value1.sqlExpression, value2.sqlExpression] + values.map(\.sqlExpression))
}
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `MAX` SQL aggregate function.
///
/// For example:
@@ -224,7 +224,7 @@ public func min(
.simpleFunction("MIN", [value1.sqlExpression, value2.sqlExpression] + values.map(\.sqlExpression))
}
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `MIN` SQL aggregate function.
///
/// For example:
@@ -269,7 +269,7 @@ public func min(_ value: some SQLSpecificExpressible) -> SQLExpression {
}
#endif
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `SUM` SQL aggregate function.
///
/// For example:
@@ -333,7 +333,7 @@ public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression {
}
#endif
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `TOTAL` SQL aggregate function.
///
/// For example:
+17 -19
View File
@@ -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 (DatabaseBase<some SQLiteAPI>) -> [SQLSelection] = { _ in [.allColumns] })
selection: @escaping @Sendable (Database) -> [SQLSelection] = { _ in [.allColumns] })
-> Self
{
SQLRelation(
@@ -197,7 +197,7 @@ extension SQLRelation {
}
extension SQLRelation: Refinable {
func selectWhenConnected(_ selection: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> [SQLSelection]) -> Self {
func selectWhenConnected(_ selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self {
with {
$0.selectionPromise = DatabasePromise(selection)
}
@@ -228,7 +228,7 @@ extension SQLRelation: Refinable {
}
}
func annotatedWhenConnected(with selection: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> [SQLSelection]) -> Self {
func annotatedWhenConnected(with selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self {
with {
let old = $0.selectionPromise
$0.selectionPromise = DatabasePromise { db in
@@ -242,7 +242,7 @@ extension SQLRelation: Refinable {
annotatedWhenConnected(with: { _ in selection })
}
func filterWhenConnected(_ predicate: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> SQLExpression) -> Self {
func filterWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self {
with {
if let old = $0.filterPromise {
$0.filterPromise = DatabasePromise { db in
@@ -259,7 +259,7 @@ extension SQLRelation: Refinable {
filterWhenConnected { _ in predicate }
}
func orderWhenConnected(_ orderings: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> [SQLOrdering]) -> Self {
func orderWhenConnected(_ orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) -> Self {
with {
$0.ordering = SQLRelation.Ordering(orderings: orderings)
}
@@ -285,14 +285,12 @@ extension SQLRelation: Refinable {
func withStableOrder() -> Self {
with { relation in
relation.ordering = relation.ordering.appending(Ordering(orderings: { [relation] db in
do {
if try db.tableExists(source.tableName) {
// Order by primary key. Don't order by rowid because those are
// not stable: rowids can change after a vacuum.
return try db.primaryKey(source.tableName).columns.map { SQLExpression.column($0).sqlOrdering }
} catch {
// Could not find the primary key. Assume we're ordering
// a view that is not customized with the schemaSource.
// Create a stable order from all columns:
} else {
// Support for views: create a stable order from all columns:
// ORDER BY 1, 2, 3, ...
let columnCount = try SQLQueryGenerator(relation: relation).columnCount(db)
return (1...columnCount).map { SQL(sql: $0.description).sqlOrdering }
@@ -315,13 +313,13 @@ extension SQLRelation: Refinable {
}
}
func groupWhenConnected(_ expressions: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> [SQLExpression]) -> Self {
func groupWhenConnected(_ expressions: @escaping @Sendable (Database) throws -> [SQLExpression]) -> Self {
with {
$0.groupPromise = DatabasePromise(expressions)
}
}
func havingWhenConnected(_ predicate: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> SQLExpression) -> Self {
func havingWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self {
with {
if let old = $0.havingExpressionPromise {
$0.havingExpressionPromise = DatabasePromise { db in
@@ -602,7 +600,7 @@ extension SQLRelation {
}
extension SQLRelation {
func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
func fetchCount(_ db: Database) throws -> Int {
guard groupPromise == nil && limit == nil && ctes.isEmpty else {
// SELECT ... GROUP BY ...
// SELECT ... LIMIT ...
@@ -651,7 +649,7 @@ extension SQLRelation {
}
// SELECT COUNT(*) FROM (self)
private func fetchTrivialCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
private func fetchTrivialCount(_ db: Database) throws -> Int {
let countRequest: SQLRequest<Int> = "SELECT COUNT(*) FROM (\(SQLSubquery.relation(unordered())))"
return try countRequest.fetchOne(db)!
}
@@ -716,7 +714,7 @@ extension SQLRelation {
}
}
func resolve(_ db: DatabaseBase<some SQLiteAPI>) throws -> [SQLOrdering] {
func resolve(_ db: Database) throws -> [SQLOrdering] {
switch self {
case .terms(let terms):
return try terms.resolve(db)
@@ -742,7 +740,7 @@ extension SQLRelation {
isReversed: false)
}
init(orderings: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> [SQLOrdering]) {
init(orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) {
self.init(
elements: [.terms(DatabasePromise(orderings))],
isReversed: false)
@@ -766,7 +764,7 @@ extension SQLRelation {
isReversed: isReversed)
}
func resolve(_ db: DatabaseBase<some SQLiteAPI>) throws -> [SQLOrdering] {
func resolve(_ db: Database) throws -> [SQLOrdering] {
if isReversed {
return try elements.flatMap { try $0.reversed.resolve(db) }
} else {
@@ -832,7 +830,7 @@ enum SQLAssociationCondition: Sendable {
}
func joinExpression(
_ db: DatabaseBase<some SQLiteAPI>,
_ db: Database,
leftAlias: TableAliasBase,
rightAlias: TableAliasBase)
throws -> SQLExpression?
@@ -891,7 +889,7 @@ struct SQLForeignKeyCondition: Equatable {
/// Turns the foreign key condition into a `JoinMapping` that can feed an
/// SQL JOIN clause.
func joinMapping(_ db: DatabaseBase<some SQLiteAPI>, from originTable: String) throws -> JoinMapping {
func joinMapping(_ db: Database, from originTable: String) throws -> JoinMapping {
try foreignKeyRequest(from: originTable)
.fetchForeignKeyMapping(db)
.joinMapping(originIsLeft: originIsLeft)
+1 -1
View File
@@ -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<some SQLiteAPI>) 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:
+1 -1
View File
@@ -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: DatabaseBase<some SQLiteAPI>) throws -> Int {
func columnCount(_ db: Database) throws -> Int {
switch impl {
case let .literal(sqlLiteral):
// Compile request. We can freely use the statement cache because we
Loaded 100 of 245 files, more files were not shown because too many files have changed in this diff. Show more