Compare commits

...
Author SHA1 Message Date
Gwendal Roué 3777ba0df2 Generic connection WIP 2025-11-12 18:04:31 +01:00
Gwendal Roué b31be05ee3 Do not use traits, since they are not supported by Xcode
This pull request fixes #1826, which broke `make test_GRDBDemo` with Xcode 26.0.1.

To reproduce the failure:

- Remove from ~/Library/Developer/Xcode/DerivedData all previous builds of GRDB and related stuff
- Run `make distclean test_GRDBDemo`

We expect a success, but it fails with error "Unable to find module dependency: 'GRDBSQLite'".
2025-10-27 13:37:21 +01:00
Gwendal Roué a60810f28e Merge pull request #1819 from groue/dev/SQLCipher-cleanup
Accept multiple SQLCipher libraries
2025-10-12 15:46:52 +02:00
Gwendal Roué c35095c6da Enable more tests 2025-10-12 14:58:06 +02:00
Gwendal Roué f878d99733 Use SQLITE_HAS_CODEC instead of GRDBCIPHER when testing for SQLCipher availability
GRDBCIPHER is now just a marker for importing SQLCipher with CocoaPods.

Also, enable all APIs that used to be disabled with SQLCipher, and skip tests that require a specific SQLite version.
2025-10-12 14:49:59 +02:00
Gwendal Roué 48a17ce490 Merge pull request #1826 from groue/dev/snapshot-cleanup
Simplify the compiler checks for the availability of SQLite snapshots
2025-10-12 14:27:06 +02:00
Gwendal Roué 361a482b1e Enable SQLITE_ENABLE_SNAPSHOT by default and introduce SQLITE_DISABLE_SNAPSHOT 2025-10-12 14:03:09 +02:00
Gwendal Roué 8cba324d6e Refactor the SQLite import
We can not use `#if Trait` because Xcode does not enable those compiler flags. Always count on Apple for delivering the best quality software.

So now we import the default SPM SQLite last, after all other cases have been excluded.

The GRDB framework (GRDB.xcodeproj and GRDB via CocoaPods) is distinct from the default SPM trait, so we detect it with GRDBFRAMEWORK.
2025-10-04 17:56:06 +02:00
Gwendal Roué 17e1683b66 Bump CI to macOS 15 and Xcode 16.4 2025-10-04 17:56:06 +02:00
Gwendal Roué b1b83abd8b Simplify the compiler checks for the availability of SQLite snapshots 2025-10-04 14:15:13 +02:00
Gwendal Roué d06c9ed6b5 Enable SQLITE_ENABLE_SNAPSHOT in the Xcode GRDB framework 2025-10-04 14:15:13 +02:00
Gwendal Roué 9a98ed6292 Enable SQLITE_ENABLE_SNAPSHOT in the GRDBSQLite trait, on Darwin platforms 2025-10-04 14:15:13 +02:00
Gwendal Roué 5cc85a98f3 Only depend on GRDBSQLite when the default GRDBSQLite trait is active. 2025-10-04 13:53:38 +02:00
Gwendal Roué edc1d646f0 [BREAKING] Bump minimum Swift version to 6.1 2025-10-04 13:53:38 +02:00
Gwendal Roué ab09078842 Fix failing test for merged migration that merges itself 2025-10-03 09:36:22 +02:00
Gwendal Roué 267e1ea5a6 Add failing test for merged migration that merges itself 2025-10-03 09:34:26 +02:00
Gwendal Roué 18497b68fd Merge branch 'development' 2025-10-02 08:11:07 +02:00
Gwendal Roué 19e33e2e7d v7.8.0 2025-10-02 08:10:52 +02:00
Gwendal Roué 76e0815907 Merge pull request #1818 from groue/dev/obsolete-migrations
Merged Migrations
2025-10-02 08:06:24 +02:00
Gwendal Roué 85ad232b0b Support for migrations that merge previous migrations 2025-10-01 17:24:00 +02:00
Gwendal Roué db695cf7dc Merge branch 'development' 2025-09-29 21:14:01 +02:00
Gwendal Roué 76a7be8404 v7.7.1 2025-09-29 20:29:44 +02:00
Gwendal Roué 196c33ba63 Merge pull request #1822 from groue/dev/issue-1820
Fix the save() method for record types with attached triggers
2025-09-29 20:26:12 +02:00
Gwendal Roué 50a74f7b03 Cleanup 2025-09-29 19:43:41 +02:00
Gwendal Roué 3f27fb9289 Fix #1820
The regression was introduced by c7bbebc
2025-09-29 19:35:00 +02:00
Gwendal Roué 62fdd41d75 Failing regression test for #1820 2025-09-29 19:34:15 +02:00
Gwendal Roué c5d02eac32 Merge branch 'development' 2025-09-23 20:14:27 +02:00
Gwendal Roué d1bfce829b v7.7.0 2025-09-23 19:30:13 +02:00
Gwendal Roué edd292bcbd CHANGELOG 2025-09-23 17:44:05 +02:00
Gwendal Roué a0e101e683 Merge pull request #1810 from groue/dev/persistable-views
Persistable Database Views
2025-09-23 17:38:30 +02:00
Gwendal Roué 9ef5e2c8eb Simplify error messages 2025-09-23 17:12:27 +02:00
Gwendal Roué f5dc68fc6f Fix typos 2025-09-23 17:12:27 +02:00
Gwendal Roué b210ec7428 View Records guide 2025-09-23 17:12:27 +02:00
Gwendal Roué a7e3acf409 Remove TODO warnings 2025-09-23 17:12:27 +02:00
Gwendal Roué ca27f75760 Test the stable order of views with a primary key 2025-09-23 17:12:27 +02:00
Gwendal Roué 99ecf76a77 Support primary key when testing the existence of an association to a view 2025-09-23 17:12:27 +02:00
Gwendal Roué f4991273c2 DatabaseSchemaSource tests 2025-09-23 17:12:27 +02:00
Gwendal Roué 1b98a964d7 Documentation 2025-09-23 17:12:27 +02:00
Gwendal Roué 1095d21abd Default implementation for schema source chaining.
When GRDB eventually adds methods to the DatabaseSchemaSource protocol, our chained schema source will implement chaining on those new methods.

When users write their own custom chaining schema source, the compiler will not tell them that they have to chain the new methods when they upgrade GRDB. The built-in (and correct) implementation of chaining helps avoiding this scenario.
2025-09-23 17:12:27 +02:00
Gwendal Roué eb2378a741 DatabaseSchemaSource documentation 2025-09-23 17:12:27 +02:00
Gwendal Roué 37dde39557 Public Database.schemaSource and withSchemaSource(_:execute:) 2025-09-23 17:12:27 +02:00
Gwendal Roué 5786391dc9 RecordMappedOnMutableViewTests 2025-09-23 17:12:27 +02:00
Gwendal Roué e1abafaae3 Ignore schema source during migrations 2025-09-23 17:12:27 +02:00
Gwendal Roué 93d0baeade The stable order for views is provided by the schemaSource, if any 2025-09-23 17:12:27 +02:00
Gwendal Roué 26ebd7e147 Update outdated comments 2025-09-23 17:12:27 +02:00
Gwendal Roué 75e99861af Update TableRecordUpdateTests with record types based on database views 2025-09-23 17:12:27 +02:00
Gwendal Roué 2e433a3cb2 Update TableRecordDeleteTests with record types based on database views 2025-09-23 17:12:27 +02:00
Gwendal Roué 9518d74fa6 Improve error message 2025-09-23 17:12:27 +02:00
Gwendal Roué c7bbebc80f Change the way we count changes in order to support INSTEAD OF triggers
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.

Since we want to support INSTEAD OF triggers well, so that record types can be based on views, we switch to sqlite3_total_changes().
2025-09-23 17:12:27 +02:00
Gwendal Roué 38f5226e95 Database.table(_:hasUniqueKey:) now accept views 2025-09-23 17:12:27 +02:00
Gwendal Roué 2b19803644 DatabaseSchemaSource tests 2025-09-23 17:12:27 +02:00
Gwendal Roué d7d61add23 DatabaseSchemaSource customizes the primary key of database views 2025-09-23 17:12:27 +02:00
Gwendal Roué d040588849 Database.fetchPrimitivePrimaryKey(forTable:)
This method is necessary for the customization of schema introspection: it must be possible to fallback on the primitive SQLite schema introspection when needed.
2025-09-23 17:12:27 +02:00
Gwendal Roué 30313623eb Make DatabaseSchemaID and DatabaseObjectID public
This is also a big cleanup opportunity.

We need public schema identifiers in order to support the customization of schema introspection.
2025-09-23 17:12:27 +02:00
alephao aab2664431 fix: DispatchQueueExecutor sendable conformance on Linux 2025-09-18 08:27:14 +02:00
Gwendal Roué f3acfecc16 DatabaseCollation no longer uses a deprecated String initializer 2025-09-13 12:21:36 +02:00
Gwendal Roué aa2cdb7ec3 Merge branch 'master' into development 2025-09-10 20:53:15 +02:00
Gwendal Roué d90ba851fe Merge pull request #1803 from groue/dependabot/github_actions/actions/checkout-5
Bump actions/checkout from 4 to 5
2025-09-10 20:52:19 +02:00
Gwendal Roué 7eea8ccb91 Merge pull request #1813 from groue/dev/SendableMetaType
Support for Xcode 26
2025-09-10 18:05:39 +02:00
Gwendal Roué 6a25b3538e DocC for GRDBSendableMetatype 2025-09-10 07:41:42 +02:00
Gwendal Roué 7ec88b76e0 Start an immediate observation
In the iOS 26 simulator the demo app would show a flash of missing content.
2025-09-10 07:12:53 +02:00
Gwendal Roué 1a3842e4bc Combine and concurrency: lol 2025-09-10 07:12:53 +02:00
Gwendal Roué 32ed290a1b EncodableRecord is GRDBSendableMetatype
This allows us to apply the encoding strategies for Data, Date, UUID when we know we need it, i.e. when we know the primary key, and this happens when we access the database - in a nonisolated fashion.
2025-09-10 07:12:53 +02:00
Gwendal Roué f88c7202cd TableRecord is GRDBSendableMetatype
This is required because the value of databaseSelection is not required to be Sendable. This forces TableRecord.relationForAll to postpone the definition of the selection until we access the database - in a nonisolated fashion.
2025-09-10 07:12:53 +02:00
Gwendal Roué 79ce0ff5f3 Avoid a compiler warning 2025-09-10 07:12:53 +02:00
Gwendal Roué f435715f75 ValueReducer is SendableMetatype
ValueReducer does not support isolated conformances: it must be able to reduce observed values when needed. This can happen in a nonisolated fashion.
2025-09-10 07:12:52 +02:00
Gwendal Roué cf1702630f DatabaseAggregate is SendableMetatype
DatabaseAggregate does not support isolated conformances: it must be able to aggregate values whenever a database access is performed. This can happen in a nonisolated fashion.
2025-09-10 07:12:52 +02:00
Gwendal Roué fd7adf7fb3 SendableMetatype for compiler >= 6.2 2025-09-10 07:12:52 +02:00
Gwendal Roué be0f0c6f25 Fix a compiler error
The error was:

> use of ‘@import’ in framework header is discouraged, including this header requires -fmodules

This commit applies the fix recommended at https://developer.apple.com/documentation/xcode/identifying-and-addressing-framework-module-issues
2025-09-10 07:12:52 +02:00
Gwendal Roué cd84db3873 Xcode 26 upgrade 2025-09-10 07:12:52 +02:00
Gwendal Roué 4cfa692ddd Fix race condition regarding Task cancellation
This complements #1797 by making sure read-only transactions complete correctly, even if the task is cancelled.
2025-09-10 07:12:11 +02:00
Gwendal Roué 8dfbbb50f6 TODO 2025-09-10 06:51:14 +02:00
Gwendal Roué 3f69614405 DatabaseFunction with raw xFunc
No use right now, but I was really bugged that we could not use raw sqlite3_result_xxx methods from custom functions.
2025-09-02 08:09:16 +02:00
Gwendal Roué b4f3a83755 Remove SwiftLint warning
If we don't have warnings about explicit nil initialization, then we have a warning about the name of a disabled rule which is now deprecated. In all cases, we have a warning.

So let's just write 2025 Swift, ignore that rule, and call it a day.
2025-09-02 08:07:16 +02:00
Gwendal Roué 7cd2a4563c Merge pull request #1807 from emmanuel-ferdman/development
Update `GRDB7MigrationGuide.md` reference
2025-08-31 13:52:09 +02:00
Emmanuel Ferdman 2698c55654 Update GRDB7MigrationGuide.md reference
Signed-off-by: Emmanuel Ferdman <emmanuelferdman@gmail.com>
2025-08-30 09:58:59 -07:00
Gwendal Roué 37065fb503 Regression test for #1797 2025-08-19 08:05:07 +02:00
Gwendal Roué 3801ab9ac6 Fix Base image link 2025-08-19 08:04:41 +02:00
Gwendal Roué 26abd8ad79 Merge branch 'dev/sponsor-base' 2025-08-18 17:52:58 +02:00
Gwendal Roué 827ab62bb6 Add link to our beloved sponsor Base 2025-08-18 17:39:03 +02:00
dependabot[bot] fdeb88a6bd Bump actions/checkout from 4 to 5
Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 5.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-08-18 09:08:53 +00:00
245 changed files with 6292 additions and 2733 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-14-Readme.md
# https://github.com/actions/runner-images/blob/main/images/macos/macos-15-Readme.md
name: "GRDB CI"
@@ -40,20 +40,20 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
destination: "platform=macOS"
name: "macOS"
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
destination: "OS=18.1,name=iPhone 16 Pro"
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
destination: "OS=18.5,name=iPhone 16 Pro"
name: "iOS"
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
destination: "OS=18.1,name=Apple TV"
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
destination: "OS=18.5,name=Apple TV"
name: "tvOS"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- 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.1.app"
runsOn: macOS-14
name: "Xcode 16.1"
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
name: "Xcode 16.4"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: ${{ matrix.name }}
run: make test_SPM test_install_SPM
SQLCipher3:
@@ -83,11 +83,11 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
name: "Xcode 16.1"
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
name: "Xcode 16.4"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher3Encrypted
SQLCipher4:
@@ -100,11 +100,11 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
name: "Xcode 16.1"
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
name: "Xcode 16.4"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher4Encrypted
CustomSQLite:
@@ -117,11 +117,11 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
name: "Xcode 16.1"
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
name: "Xcode 16.4"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: ${{ matrix.name }}
run: make test_framework_GRDBCustomSQLiteOSX
XCFramework:
@@ -134,11 +134,11 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
name: "Xcode 16.1"
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
name: "Xcode 16.4"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- 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.0
swift_version: 6.1
+136 -113
View File
@@ -7,6 +7,8 @@ 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)
@@ -138,6 +140,27 @@ 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
@@ -1708,7 +1731,7 @@ The [Advanced DatabasePool](README.md#advanced-databasepool) chapter has been ex
```diff
class DatabasePool {
+ func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
+ func barrierWriteWithoutTransaction<T>(_ updates: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T
+ func invalidateReadOnlyConnections()
}
@@ -1828,7 +1851,7 @@ The [ValueObservation](README.md#valueobservation) chapter has been updated so t
}
extension ValueObservation where Reducer == Void {
+ static func tracking<Value>(fetch: @escaping (Database) throws -> Value) -> ValueObservation<ValueReducers.Fetch<Value>>
+ static func tracking<Value>(fetch: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Value) -> ValueObservation<ValueReducers.Fetch<Value>>
}
```
@@ -1873,7 +1896,7 @@ The [ValueObservation Error Handling](README.md#valueobservation-error-handling)
+ var configuration: Configuration { get }
+
+ #if compiler(>=5.0)
+ func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void)
+ func asyncRead(_ block: @escaping (Result<DatabaseBase<some SQLiteAPI>, Error>) -> Void)
+ #endif
}
@@ -1881,7 +1904,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 (Database) throws -> T, completion: @escaping (Database, Result<T, Error>) -> Void)
+ func asyncWrite<T>(_ updates: @escaping (DatabaseBase<some SQLiteAPI>) throws -> T, completion: @escaping (Database, Result<T, Error>) -> Void)
+ #endif
}
```
@@ -1961,8 +1984,8 @@ The [ValueObservation Error Handling](README.md#valueobservation-error-handling)
protocol FetchRequest {
+ // deprecated
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
+ func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
func prepare(_ db: DatabaseBase<some SQLiteAPI>, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
+ func makePreparedRequest(_ db: DatabaseBase<some SQLiteAPI>, forSingleResult singleResult: Bool) throws -> PreparedRequest
}
```
@@ -2166,37 +2189,37 @@ It comes with new features, but also a few breaking changes. The [GRDB 4 Migrati
}
class Row {
- static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor
- static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row]
- static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row?
+ static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RowCursor
+ static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Row]
+ static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Row?
- static func fetchCursor(_ db: DatabaseBase<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?
}
extension FetchableRecord {
- 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?
- 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?
}
extension DatabaseValueConvertible {
- 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?
- 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?
}
extension Optional where Wrapped: DatabaseValueConvertible {
- 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?]
- 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?]
}
extension TableRecord {
@@ -2301,7 +2324,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 (Database) throws -> Value) -> ValueObservation<DistinctUntilChangedValueReducer<RawValueReducer<Value>>> where Value: Equatable
- static func tracking<Value>(_ regions: DatabaseRegionConvertible..., fetchDistinct fetch: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Value) -> ValueObservation<DistinctUntilChangedValueReducer<RawValueReducer<Value>>> where Value: Equatable
}
```
@@ -2444,12 +2467,12 @@ It comes with new features, but also a few breaking changes. The [GRDB 4 Migrati
+ class DatabaseFuture<Value> { }
protocol FetchRequest {
- func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
+ func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
- func prepare(_ db: DatabaseBase<some SQLiteAPI>) throws -> (SelectStatement, RowAdapter?)
+ func prepare(_ db: DatabaseBase<some SQLiteAPI>, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
}
struct AnyFetchRequest<T> : FetchRequest {
- init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?))
- init(_ prepare: @escaping (DatabaseBase<some SQLiteAPI>) throws -> (SelectStatement, RowAdapter?))
+ init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?))
}
@@ -2572,24 +2595,24 @@ This release comes with:
}
extension MutablePersistableRecord {
+ mutating func updateChanges(_ db: Database, with change: (inout Self) throws -> Void) throws -> Bool
+ mutating func updateChanges(_ db: DatabaseBase<some SQLiteAPI>, with change: (inout Self) throws -> Void) throws -> Bool
}
extension PersistableRecord {
+ func updateChanges(_ db: Database, with change: (Self) throws -> Void) throws -> Bool
+ func updateChanges(_ db: DatabaseBase<some SQLiteAPI>, with change: (Self) throws -> Void) throws -> Bool
}
struct ValueObservation<Reducer> {
+ static func tracking(
+ _ regions: [DatabaseRegionConvertible],
+ reducer: @escaping (Database) throws -> Reducer)
+ reducer: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Reducer)
+ -> ValueObservation
}
+extension ValueObservation where Reducer == Void {
+ static func tracking<Value>(
+ _ regions: [DatabaseRegionConvertible],
+ fetch: @escaping (Database) throws -> Value)
+ fetch: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Value)
+ -> ValueObservation<ValueReducers.Raw<Value>>
+ static func combine<R1: ValueReducer, ...>(_ o1: ValueObservation<R1>, ...)
+ -> ValueObservation<...>
@@ -2674,13 +2697,13 @@ It used to be possible to define custom types that adopt the [DatabaseReader and
}
+protocol DatabaseRegionConvertible {
+ func databaseRegion(_ db: Database) throws -> DatabaseRegion
+ func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
+}
+
+extension DatabaseRegion: DatabaseRegionConvertible { }
+
+struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
+ init(_ region: @escaping (Database) throws -> DatabaseRegion)
+ init(_ region: @escaping (DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion)
+ init(_ region: DatabaseRegionConvertible)
+}
@@ -2696,7 +2719,7 @@ It used to be possible to define custom types that adopt the [DatabaseReader and
+protocol ValueReducer {
+ associatedtype Fetched
+ associatedtype Value
+ func fetch(_ db: Database) throws -> Fetched
+ func fetch(_ db: DatabaseBase<some SQLiteAPI>) throws -> Fetched
+ mutating func value(_ fetched: Fetched) -> Value?
+}
+
@@ -2705,7 +2728,7 @@ It used to be possible to define custom types that adopt the [DatabaseReader and
+}
+
+struct AnyValueReducer<Fetched, Value>: ValueReducer {
+ init(fetch: @escaping (Database) throws -> Fetched, value: @escaping (Fetched) -> Value?)
+ init(fetch: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Fetched, value: @escaping (Fetched) -> Value?)
+ init<Reducer: ValueReducer>(_ reducer: Reducer) where Reducer.Fetched == Fetched, Reducer.Value == Value
+}
@@ -2728,12 +2751,12 @@ It used to be possible to define custom types that adopt the [DatabaseReader and
+extension ValueObservation where Reducer == Void {
+ static func tracking<Value>(
+ _ regions: DatabaseRegionConvertible...,
+ fetch: @escaping (Database) throws -> Value)
+ fetch: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Value)
+ -> ValueObservation<ValueReducers.Raw<Value>>
+
+ static func tracking<Value>(
+ _ regions: DatabaseRegionConvertible...,
+ fetchDistinct: @escaping (Database) throws -> Value)
+ fetchDistinct: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Value)
+ -> ValueObservation<ValueReducers.Distinct<Value>>
+ where Value: Equatable
+
@@ -2778,7 +2801,7 @@ This release comes with **Association Aggregates**. They let you compute values
```diff
protocol AggregatingRequest {
- func group(_ expressions: [SQLExpressible]) -> Self
+ func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self
+ func group(_ expressions: @escaping (DatabaseBase<some SQLiteAPI>) throws -> [SQLExpressible]) -> Self
}
+extension AggregatingRequest {
@@ -2856,7 +2879,7 @@ Released September 16, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/co
```diff
protocol DatabaseWriter : DatabaseReader {
+ func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> Future<T>
+ func concurrentRead<T>(_ block: @escaping (DatabaseBase<some SQLiteAPI>) throws -> T) -> Future<T>
+ @available(*, deprecated)
func readFromCurrentState(_ block: @escaping (Database) -> Void) throws
}
@@ -2915,10 +2938,10 @@ Fixes:
```diff
class DatabaseQueue {
- 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 {
- 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 {
}
```
@@ -3166,14 +3189,14 @@ Released February 25, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/com
extension MutablePersistable {
+ @discardableResult
+ func updateChanges(_ db: Database, from record: MutablePersistable) throws -> Bool
+ func updateChanges(_ db: DatabaseBase<some SQLiteAPI>, from record: MutablePersistable) throws -> Bool
+ func databaseEqual(_ record: Self) -> Bool
+ func databaseChanges(from record: MutablePersistable) -> [String: DatabaseValue]
}
class Record {
- final func updateChanges(_ db: Database) throws
- final func updateChanges(_ db: DatabaseBase<some SQLiteAPI>) throws
+ @discardableResult
+ final func updateChanges(_ db: Database) throws -> Bool
+ final func updateChanges(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
}
+@available(*, deprecated, message: "Prefer changes methods defined on the MutablePersistable protocol: databaseEqual(_:), databaseChanges(from:), updateChanges(from:)")
@@ -3189,7 +3212,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: Database) throws -> Int
+ static func numberOfSelectedColumns(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int
}
+struct EmptyRowAdapter: RowAdapter { }
@@ -3312,7 +3335,7 @@ Released January 18, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/comp
protocol Request {
+ // Default implementation
+ func fetchedRegion(_ db: Database) throws -> DatabaseRegion
+ func fetchedRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
}
+extension Row: RandomAccessCollection {
@@ -3379,8 +3402,8 @@ Released January 11, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/comp
}
extension RowConvertible where Self: TableMapping {
- static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Self?
+ static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]?) throws -> Self?
- static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, key: [String: DatabaseValueConvertible?]) throws -> Self?
+ static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, key: [String: DatabaseValueConvertible?]?) throws -> Self?
}
```
@@ -3510,7 +3533,7 @@ Released October 24, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/comp
```diff
extension Request {
+ func asSQLRequest(_ db: Database, cached: Bool = false) throws -> SQLRequest
+ func asSQLRequest(_ db: DatabaseBase<some SQLiteAPI>, cached: Bool = false) throws -> SQLRequest
}
struct SQLRequest {
+ let sql: String
@@ -3761,15 +3784,15 @@ New features have been added in order to plug a few holes and support the [RxGRD
-extension TableMapping {
+extension MutablePersistable {
@discardableResult static func deleteAll(_ db: Database) throws -> Int
@discardableResult static func deleteAll<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
@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
}
-extension QueryInterfaceRequest {
+extension QueryInterfaceRequest where RowDecoder: MutablePersistable {
@discardableResult func deleteAll(_ db: Database) throws -> Int
@discardableResult func deleteAll(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int
}
protocol TableMapping {
@@ -3839,30 +3862,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: Database) throws -> DatabaseCursor<RowDecoder>
+ func fetchCursor(_ db: Database) throws -> RecordCursor<RowDecoder>
- func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseCursor<RowDecoder>
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> RecordCursor<RowDecoder>
}
extension TypedRequest where RowDecoder: DatabaseValueConvertible {
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder>
+ func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder>
- func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseCursor<RowDecoder>
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseValueCursor<RowDecoder>
}
extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible {
+ func fetchCursor(_ db: Database) throws -> ColumnCursor<RowDecoder>
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> ColumnCursor<RowDecoder>
}
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible {
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder._Wrapped?>
+ func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped>
- func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseCursor<RowDecoder._Wrapped?>
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped>
}
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
+ func fetchCursor(_ db: Database) throws -> NullableColumnCursor<RowDecoder._Wrapped>
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> NullableColumnCursor<RowDecoder._Wrapped>
}
extension TypedRequest where RowDecoder: Row {
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<Row>
+ func fetchCursor(_ db: Database) throws -> RowCursor
- func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseCursor<Row>
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> RowCursor
}
extension TableMapping {
- @available(*, deprecated) static func primaryKeyRowComparator(_ db: Database) throws -> (Row, Row) -> Bool
- @available(*, deprecated) static func primaryKeyRowComparator(_ db: DatabaseBase<some SQLiteAPI>) throws -> (Row, Row) -> Bool
}
+final class AnyDatabaseReader : DatabaseReader {
@@ -4025,7 +4048,7 @@ Released July 13, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/compare
}
protocol DatabaseReader {
+ func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T
+ func unsafeReentrantRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T
}
```
@@ -4087,7 +4110,7 @@ Released July 1, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/compare/
extension TableMapping {
+ @available(*, deprecated)
static func primaryKeyRowComparator(_ db: Database) throws -> (Row, Row) -> Bool
static func primaryKeyRowComparator(_ db: DatabaseBase<some SQLiteAPI>) throws -> (Row, Row) -> Bool
}
```
@@ -4212,8 +4235,8 @@ It comes with breaking changes, but the good news is that they are the last (unt
}
extension Request {
- func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AnyRequest
+ func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedRequest<Self>
- func adapted(_ adapter: @escaping (DatabaseBase<some SQLiteAPI>) throws -> RowAdapter) -> AnyRequest
+ func adapted(_ adapter: @escaping (DatabaseBase<some SQLiteAPI>) throws -> RowAdapter) -> AdaptedRequest<Self>
}
protocol TypedRequest : Request {
@@ -4222,8 +4245,8 @@ protocol TypedRequest : Request {
}
extension TypedRequest {
- func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AnyTypedRequest<Fetched>
+ func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedTypedRequest<Self>
- func adapted(_ adapter: @escaping (DatabaseBase<some SQLiteAPI>) throws -> RowAdapter) -> AnyTypedRequest<Fetched>
+ func adapted(_ adapter: @escaping (DatabaseBase<some SQLiteAPI>) throws -> RowAdapter) -> AdaptedTypedRequest<Self>
}
```
@@ -4343,7 +4366,7 @@ Released April 3, 2017
- Support for [reactive](https://reactivex.io) extensions:
- `SelectStatement.SelectionInfo` is an opaque value that knows which database tables and columns are read by a [select statement](https://github.com/groue/GRDB.swift#prepared-statements).
- `DatabaseEventKind.impacts(_ selectionInfo:SelectStatement.SelectionInfo)` tells whether a database change has any impact on the results of a select statement. See [Database Changes Observation](https://github.com/groue/GRDB.swift#database-changes-observation)
- `TableMapping.primaryKeyRowComparator(_ db: Database)` returns a function that compares two database rows and return true if and only if they have the same non-null primary key.
- `TableMapping.primaryKeyRowComparator(_ db: DatabaseBase<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.
**Breaking Changes**
@@ -4661,19 +4684,19 @@ Many APIs were changed:
}
final class DatabasePool {
- func read<T>(_ block: (Database) throws -> T) rethrows -> T
- func nonIsolatedRead<T>(_ block: (Database) throws -> T) rethrows -> T
- func read<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T
- func nonIsolatedRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T
- func readFromWrite(_ block: @escaping (Database) -> Void)
+ func read<T>(_ block: (Database) throws -> T) throws -> T
+ func nonIsolatedRead<T>(_ block: (Database) throws -> T) throws -> T
+ func read<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T
+ func nonIsolatedRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T
+ func readFromWrite(_ block: @escaping (Database) -> Void) throws
}
protocol DatabaseReader {
- 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
- 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
}
protocol DatabaseWriter {
@@ -4724,13 +4747,13 @@ Many APIs were changed:
}
protocol MutablePersistable : TableMapping {
- func exists(_ db: Database) -> Bool
+ func exists(_ db: Database) throws -> Bool
- func exists(_ db: DatabaseBase<some SQLiteAPI>) -> Bool
+ func exists(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
}
extension MutablePersistable {
- func performExists(_ db: Database) -> Bool
+ func performExists(_ db: Database) throws -> Bool
- func performExists(_ db: DatabaseBase<some SQLiteAPI>) -> Bool
+ func performExists(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
}
extension QueryInterfaceRequest {
@@ -4757,8 +4780,8 @@ Many APIs were changed:
}
extension TableMapping {
- static func fetchCount(_ db: Database) -> Int
+ static func fetchCount(_ db: Database) throws -> Int
- static func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) -> Int
+ static func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int
}
```
@@ -4936,7 +4959,7 @@ Released October 16, 2016
protocol VirtualTableModule {
- func moduleArguments(_ definition: TableDefinition) -> [String]
+ func moduleArguments(for definition: TableDefinition, in db: Database) throws -> [String]
+ func database(_ db: Database, didCreate tableName: String, using definition: TableDefinition) throws
+ func database(_ db: DatabaseBase<some SQLiteAPI>, didCreate tableName: String, using definition: TableDefinition) throws
}
```
@@ -5009,7 +5032,7 @@ Released September 28, 2016
**Breaking Changes**
- The SQLForeignKeyAction, SQLColumnType, SQLConflictResolution, and SQLCollation types have been renamed Database.ForeignKeyAction, Database.ColumnType, Database.ConflictResolution, and Database.CollationName.
- The SQLForeignKeyAction, SQLColumnType, SQLConflictResolution, and SQLCollation types have been renamed Database.ForeignKeyAction, Database.ColumnType, DatabaseConflictResolution, and Database.CollationName.
## 0.84.0
@@ -5272,8 +5295,8 @@ Released September 11, 2016
- func databaseDidRollback(db: Database)
+ func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
+ func databaseDidChange(with event: DatabaseEvent)
+ func databaseDidCommit(_ db: Database)
+ func databaseDidRollback(_ db: Database)
+ func databaseDidCommit(_ db: DatabaseBase<some SQLiteAPI>)
+ func databaseDidRollback(_ db: DatabaseBase<some SQLiteAPI>)
#if SQLITE_ENABLE_PREUPDATE_HOOK
- func databaseWillChangeWithEvent(event: DatabasePreUpdateEvent)
+ func databaseWillChange(with event: DatabasePreUpdateEvent)
@@ -5296,19 +5319,19 @@ Released September 11, 2016
- func delete(db: Database) throws -> Bool
- func exists(db: Database) -> Bool
+ mutating func didInsert(with rowID: Int64, for column: String?)
+ mutating func insert(_ db: Database) throws
+ func update(_ db: Database, columns: Set<String>) throws
+ mutating func save(_ db: Database) throws
+ @discardableResult func delete(_ db: Database) throws -> Bool
+ func exists(_ db: Database) -> Bool
+ 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
}
protocol Persistable : MutablePersistable {
- func didInsertWithRowID(rowID: Int64, forColumn column: String?)
- func insert(db: Database) throws
- func save(db: Database) throws
+ func didInsert(with rowID: Int64, for column: String?)
+ func insert(_ db: Database) throws
+ func save(_ db: Database) throws
+ func insert(_ db: DatabaseBase<some SQLiteAPI>) throws
+ func save(_ db: DatabaseBase<some SQLiteAPI>) throws
}
protocol TableMapping {
- static func databaseTableName() -> String
@@ -5328,10 +5351,10 @@ Released September 11, 2016
+ class var databaseTableName: String
+ func awakeFromFetch(row: Row)
+ func didInsert(with rowID: Int64, for column: String?)
+ func update(_ db: Database, columns: Set<String>) throws
+ func insert(_ db: Database) throws
+ func save(_ db: Database) throws
+ @discardableResult func delete(_ db: Database) throws -> Bool
+ 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
}
```
@@ -5340,7 +5363,7 @@ Released September 11, 2016
```diff
protocol FetchRequest {
- func prepare(db: Database) throws -> (SelectStatement, RowAdapter?)
+ func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
+ func prepare(_ db: DatabaseBase<some SQLiteAPI>) throws -> (SelectStatement, RowAdapter?)
}
-struct SQLColumn {}
+struct Column {}
@@ -5920,10 +5943,10 @@ Released May 17, 2016
```diff
struct DatabaseMigrator {
- mutating func registerMigration(identifier: String, withDisabledForeignKeyChecks disabledForeignKeyChecks: Bool = false, migrate: (Database) throws -> Void)
+ mutating func registerMigration(identifier: String, migrate: (Database) throws -> Void)
- mutating func registerMigration(identifier: String, withDisabledForeignKeyChecks disabledForeignKeyChecks: Bool = false, migrate: (DatabaseBase<some SQLiteAPI>) throws -> Void)
+ mutating func registerMigration(identifier: String, migrate: (DatabaseBase<some SQLiteAPI>) throws -> Void)
+ @available(iOS 8.2, OSX 10.10, *)
+ mutating func registerMigrationWithDisabledForeignKeyChecks(identifier: String, migrate: (Database) throws -> Void)
+ mutating func registerMigrationWithDisabledForeignKeyChecks(identifier: String, migrate: (DatabaseBase<some SQLiteAPI>) throws -> Void)
```
@@ -158,7 +158,7 @@
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 1600;
LastUpgradeCheck = 2600;
TargetAttributes = {
56CFC6432C9F1DC9000B5023 = {
CreatedOnToolsVersion = 16.0;
@@ -293,6 +293,7 @@
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";
@@ -350,6 +351,7 @@
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;
@@ -380,7 +382,7 @@
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.0;
SWIFT_VERSION = 6.1;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
@@ -409,7 +411,7 @@
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.0;
SWIFT_VERSION = 6.1;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
@@ -425,7 +427,7 @@
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 6.0;
SWIFT_VERSION = 6.1;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/GRDBDemo";
};
@@ -442,7 +444,7 @@
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 6.0;
SWIFT_VERSION = 6.1;
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 = "1600"
LastUpgradeVersion = "2600"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
@@ -165,7 +165,7 @@ extension AppDatabase {
}
/// Support for `createRandomPlayersIfEmpty()` and `refreshPlayers()`.
private func createRandomPlayers(_ db: Database) throws {
private func createRandomPlayers(_ db: DatabaseBase<some SQLiteAPI>) 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) { error in
cancellable = observation.start(in: appDatabase.reader, scheduling: .immediate) { 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: Database) throws
func insert(_ db: DatabaseBase<some SQLiteAPI>) throws
func didInsert(with rowID: Int64, for column: String?)
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
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
```
- `insert(_:)`: customization is now made with [persistence callbacks].
@@ -204,12 +204,12 @@ The record protocols have been refactored. We tried to keep the amount of modifi
struct Link: PersistableRecord {
var url: URL
func insert(_ db: Database) throws {
func insert(_ db: DatabaseBase<some SQLiteAPI>) throws {
try validate()
try performInsert(db)
}
func update(_ db: Database, columns: Set<String>) throws {
func update(_ db: DatabaseBase<some SQLiteAPI>, 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: Database) throws {
func willSave(_ db: DatabaseBase<some SQLiteAPI>) throws {
if url.host == nil {
throw ValidationError("url must be absolute.")
}
@@ -249,7 +249,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi
class Link: Record {
var url: URL
override func willSave(_ db: Database) throws {
override func willSave(_ db: DatabaseBase<some SQLiteAPI>) 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: Database) {
func databaseDidCommit(_ db: DatabaseBase<some SQLiteAPI>) {
print("Changed table(s): \(changedTableNames.joined(separator: ", "))")
changedTableNames = []
}
func databaseDidRollback(_ db: Database) {
func databaseDidRollback(_ db: DatabaseBase<some SQLiteAPI>) {
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: Database) throws -> DatabaseRegion
func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) 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: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
func makePreparedRequest(_ db: DatabaseBase<some SQLiteAPI>, forSingleResult singleResult: Bool) throws -> PreparedRequest
/// Returns the number of rows fetched by the request.
func fetchCount(_ db: Database) throws -> Int
func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) 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: Database) throws {
static func deleteAllWithoutScore(_ db: DatabaseBase<some SQLiteAPI>) 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.6.1'
s.version = '7.8.0'
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']
s.swift_versions = ['6.1']
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',
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_ENABLE_FTS5 -D GRDBFRAMEWORK',
}
end
+18 -1
View File
@@ -81,6 +81,7 @@
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 */; };
@@ -223,6 +224,7 @@
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 */; };
@@ -288,6 +290,7 @@
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 */; };
@@ -503,6 +506,7 @@
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>"; };
@@ -674,6 +678,7 @@
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>"; };
@@ -792,6 +797,7 @@
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>"; };
@@ -997,6 +1003,7 @@
56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */,
563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */,
563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */,
568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */,
);
name = PersistableRecord;
sourceTree = "<group>";
@@ -1486,6 +1493,7 @@
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */,
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */,
568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */,
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */,
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */,
@@ -1592,6 +1600,7 @@
569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */,
564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */,
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */,
566A84192041146100E50BFD /* DatabaseSnapshot.swift */,
568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */,
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
@@ -1842,8 +1851,9 @@
DC3773EA19C8CBB3004FCF85 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = YES;
LastSwiftUpdateCheck = 0730;
LastUpgradeCheck = 1400;
LastUpgradeCheck = 2600;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
56E5D7F81B4D422D00430942 = {
@@ -2009,6 +2019,7 @@
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 */,
@@ -2113,6 +2124,7 @@
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 */,
@@ -2207,6 +2219,7 @@
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 */,
@@ -2539,6 +2552,7 @@
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 = (
@@ -2546,6 +2560,7 @@
"@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;
@@ -2570,6 +2585,7 @@
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 = (
@@ -2577,6 +2593,7 @@
"@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 = "1400"
LastUpgradeVersion = "2600"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
+34 -15
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
#if !canImport(Darwin)
@preconcurrency
@@ -87,7 +90,7 @@ public struct Configuration: Sendable {
/// with the number of snapshots.
///
/// The default configuration label is nil.
public var label: String? = nil
public var label: String?
/// A boolean value indicating whether SQLite 3.29+ interprets
/// double-quoted strings as string literals when they does not match any
@@ -198,7 +201,7 @@ public struct Configuration: Sendable {
// MARK: - Managing SQLite Connections
private var setups: [@Sendable (Database) throws -> Void] = []
private var setups: [@Sendable (DatabaseBase<some SQLiteAPI>) throws -> Void] = []
/// Defines a function to run whenever an SQLite connection is opened.
///
@@ -235,7 +238,7 @@ public struct Configuration: Sendable {
///
/// On newly created databases files, ``DatabasePool`` activates the WAL
/// mode after the preparation functions have run.
public mutating func prepareDatabase(_ setup: @escaping @Sendable (Database) throws -> Void) {
public mutating func prepareDatabase(_ setup: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> Void) {
setups.append(setup)
}
@@ -329,7 +332,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? = nil
var readonlyBusyMode: Database.BusyMode?
/// The maximum number of concurrent reader connections.
///
@@ -387,7 +390,7 @@ public struct Configuration: Sendable {
/// ``qos`` property.
///
/// The default is nil.
public var targetQueue: DispatchQueue? = nil
public var targetQueue: DispatchQueue?
/// The target dispatch queue for write database accesses.
///
@@ -395,7 +398,7 @@ public struct Configuration: Sendable {
/// by ``targetQueue``.
///
/// The default is nil.
public var writeTargetQueue: DispatchQueue? = nil
public var writeTargetQueue: DispatchQueue?
#if os(iOS)
/// A boolean value indicating whether the database connection releases
@@ -421,6 +424,22 @@ 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.
@@ -462,7 +481,7 @@ public struct Configuration: Sendable {
return threadingMode.SQLiteOpenFlags | flags
}
func setUp(_ db: Database) throws {
func setUp(_ db: DatabaseBase<some SQLiteAPI>) throws {
for f in setups {
try f(db)
}
File diff suppressed because it is too large. Load diff
+24 -21
View File
@@ -1,15 +1,18 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
extension Database {
extension DatabaseBase {
// MARK: - Statements
@@ -387,7 +390,7 @@ extension SQLStatementCursor: Cursor {
let baseAddress = buffer.baseAddress! // never nil because the buffer contains the trailing \0.
// Compile next statement
var statementEnd: UnsafePointer<CChar>? = nil
var statementEnd: UnsafePointer<CChar>?
let statement = try Statement(
database: database,
statementStart: baseAddress + offset,
@@ -431,10 +434,10 @@ extension SQLStatementCursor: Cursor {
}
}
extension Database {
extension DatabaseBase {
/// Makes sure statement can be executed, and prepares database observation.
@usableFromInline
func statementWillExecute(_ statement: Statement) throws {
func statementWillExecute(_ statement: StatementBase<API>) throws {
// Aborted transactions prevent statement execution (see the
// documentation of this method for more information).
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
@@ -455,7 +458,7 @@ extension Database {
/// May throw a cancelled commit error, if a transaction observer cancels
/// an empty transaction.
@usableFromInline
func statementDidExecute(_ statement: Statement) throws {
func statementDidExecute(_ statement: StatementBase<API>) throws {
if statement.invalidatesDatabaseSchemaCache {
clearSchemaCache()
}
@@ -468,7 +471,7 @@ extension Database {
/// Always throws an error
@usableFromInline
func statementDidFail(_ statement: Statement, withResultCode resultCode: CInt) throws -> Never {
func statementDidFail(_ statement: StatementBase<API>, 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
@@ -531,15 +534,15 @@ extension Database {
}
/// A thread-unsafe statement cache
struct StatementCache {
unowned let db: Database
private var statements: [String: Statement] = [:]
struct StatementCache<API: SQLiteAPI> {
unowned let db: DatabaseBase<API>
private var statements: [String: StatementBase<API>] = [:]
init(database: Database) {
init(database: DatabaseBase<API>) {
self.db = database
}
mutating func statement(_ sql: String) throws -> Statement {
mutating func statement(_ sql: String) throws -> StatementBase<API> {
if let statement = statements[sql] {
return statement
}
@@ -559,11 +562,11 @@ struct StatementCache {
statements = [:]
}
mutating func remove(_ statement: Statement) {
mutating func remove(_ statement: StatementBase<API>) {
statements.removeFirst { $0.value === statement }
}
mutating func removeAll(where shouldBeRemoved: (Statement) -> Bool) {
mutating func removeAll(where shouldBeRemoved: (StatementBase<API>) -> Bool) {
statements = statements.filter { (_, statement) in !shouldBeRemoved(statement) }
}
}
+145 -65
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -113,6 +116,11 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``resumeNotification``
/// - ``suspendNotification``
///
/// ### The Schema Source
///
/// - ``schemaSource``
/// - ``withSchemaSource(_:execute:)``
///
/// ### Other Database Operations
///
/// - ``add(tokenizer:)``
@@ -134,7 +142,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``StorageClass``
/// - ``TraceEvent``
/// - ``TracingOptions``
public final class Database: CustomStringConvertible, CustomDebugStringConvertible {
public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, CustomDebugStringConvertible {
// The Database class is not thread-safe. An instance should always be
// used through a SerializedDatabase.
@@ -169,7 +177,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// 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? = nil {
nonisolated(unsafe) public static var logError: LogErrorFunction? {
didSet {
if logError != nil {
_registerErrorLogCallback { (_, code, message) in
@@ -187,6 +195,19 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// 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``
@@ -294,7 +315,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
///
/// It is nil in read-only connections, because we do not report read-only
/// transactions to transaction observers.
private(set) var observationBroker: DatabaseObservationBroker?
private(set) var observationBroker: DatabaseObservationBroker<API>?
/// The list of compile options used when building SQLite
static func sqliteCompileOptions() throws -> Set<String> {
@@ -442,6 +463,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
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
@@ -459,7 +481,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
private static func openConnection(path: String, flags: CInt) throws -> SQLiteConnection {
// See <https://www.sqlite.org/c3ref/open.html>
var sqliteConnection: SQLiteConnection? = nil
var sqliteConnection: SQLiteConnection?
let code = sqlite3_open_v2(path, &sqliteConnection, flags, nil)
guard code == SQLITE_OK else {
// https://www.sqlite.org/c3ref/open.html
@@ -806,7 +828,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
collationPointer,
{ (collationPointer, length1, buffer1, length2, buffer2) in
let collation = Unmanaged<DatabaseCollation>.fromOpaque(collationPointer!).takeUnretainedValue()
return CInt(collation.function(length1, buffer1, length2, buffer2).rawValue)
return collation.xCompare(length1, buffer1.unsafelyUnwrapped, length2, buffer2.unsafelyUnwrapped)
}, nil)
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
@@ -1286,7 +1308,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// 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? = nil
var statement: SQLiteStatement?
let sql = "PRAGMA journal_mode"
sqlite3_prepare_v2(sqliteConnection, sql, -1, &statement, nil)
defer { sqlite3_finalize(statement) }
@@ -1469,7 +1491,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// either ``TransactionCompletion/commit`` or ``TransactionCompletion/rollback``.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the
/// error thrown by `operations`.
public func inTransaction(_ kind: TransactionKind? = nil, _ operations: () throws -> TransactionCompletion) throws {
public func inTransaction(_ kind: DatabaseTransactionKind? = nil, _ operations: () throws -> DatabaseTransactionCompletion) throws {
// Begin transaction
try beginTransaction(kind)
@@ -1483,7 +1505,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// Now that transaction has begun, we'll rollback in case of error.
// But we'll throw the first caught error, so that user knows
// what happened.
var firstError: Error? = nil
var firstError: Error?
let needsRollback: Bool
do {
let completion = try operations()
@@ -1626,7 +1648,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// Now that savepoint has begun, we'll rollback in case of error.
// But we'll throw the first caught error, so that user knows
// what happened.
var firstError: Error? = nil
var firstError: Error?
let needsRollback: Bool
do {
let completion = try operations()
@@ -1681,7 +1703,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// If nil, the transaction kind is DEFERRED when the current
/// database access is read-only, and IMMEDIATE otherwise.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
public func beginTransaction(_ kind: DatabaseTransactionKind? = nil) throws {
// SQLite throws an error for non-deferred transactions when read-only.
// We prefer immediate transactions for writes, so that write
// transactions can not overlap. This reduces the opportunity for
@@ -1744,7 +1766,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
if isInsideTransaction {
try execute(sql: "ROLLBACK TRANSACTION")
}
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
assert(!isInsideTransaction)
}
/// Commits a database transaction.
@@ -1923,10 +1945,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// Explicit non-conformance to Sendable: `Database` must be used from a
// serialized database access dispatch queue (see `SerializedDatabase`).
@available(*, unavailable)
extension Database: Sendable { }
extension DatabaseBase: Sendable { }
#if SQLITE_HAS_CODEC
extension Database {
extension DatabaseBase {
// MARK: - Encryption
@@ -1999,7 +2021,35 @@ extension Database {
}
#endif
extension Database {
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 {
// MARK: - Database-Related Types
@@ -2157,26 +2207,6 @@ extension Database {
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>
@@ -2363,29 +2393,6 @@ extension Database {
}
}
/// 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
@@ -2409,6 +2416,79 @@ extension Database {
}
}
#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)
+31 -24
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -53,12 +56,21 @@ 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 function: @Sendable (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
let xCompare: XCompare
/// Creates a collation.
///
@@ -75,21 +87,16 @@ public final class DatabaseCollation: Identifiable, Sendable {
/// - parameters:
/// - name: The collation name.
/// - function: A function that compares two strings.
public init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
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) {
self.name = name
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)
}
self.xCompare = xCompare
}
}
+11 -8
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
+59 -28
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
/// A custom SQL function or aggregate.
///
@@ -82,20 +85,43 @@ 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 init(
public convenience 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 { (argc, argv) in
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
}
return try function(arguments)
}
self.kind = .function(xFunc)
}
/// Creates an SQL aggregate function.
@@ -211,7 +237,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// Calls sqlite3_create_function_v2
/// See <https://sqlite.org/c3ref/create_function.html>
func install(in db: Database) {
func install(in db: DatabaseBase<some SQLiteAPI>) {
// Retain the function definition
let definition = kind.definition
let definitionP = Unmanaged.passRetained(definition).toOpaque()
@@ -238,7 +264,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// Calls sqlite3_create_function_v2
/// See <https://sqlite.org/c3ref/create_function.html>
func uninstall(in db: Database) {
func uninstall(in db: DatabaseBase<some SQLiteAPI>) {
let code = sqlite3_create_function_v2(
db.sqliteConnection,
id.name,
@@ -256,11 +282,10 @@ 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 compute: (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?
init(compute: @escaping (CInt, UnsafeMutablePointer<OpaquePointer?>?)
throws -> (any DatabaseValueConvertible)?)
let xFunc: XFunc
init(xFunc: @escaping XFunc)
{
self.compute = compute
self.xFunc = xFunc
}
}
@@ -283,11 +308,19 @@ 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(@Sendable (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
case function(XFunc)
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
case aggregate(@Sendable () -> any DatabaseAggregate)
@@ -296,8 +329,8 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
var definition: AnyObject {
switch self {
case .function(let compute):
return FunctionDefinition(compute: compute)
case .function(let xFunc):
return FunctionDefinition(xFunc: xFunc)
case .aggregate(let makeAggregate):
return AggregateDefinition(makeAggregate: makeAggregate)
}
@@ -312,9 +345,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
.fromOpaque(sqlite3_user_data(sqliteContext))
.takeUnretainedValue()
do {
try DatabaseFunction.report(
result: definition.compute(argc, argv),
in: sqliteContext)
try definition.xFunc(argc, argv.unsafelyUnwrapped, sqliteContext)
} catch {
DatabaseFunction.report(error: error, in: sqliteContext)
}
@@ -464,7 +495,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
/// }
/// ```
public protocol DatabaseAggregate {
public protocol DatabaseAggregate: GRDBSendableMetatype {
/// Creates an aggregate.
///
/// A new instance is created for each aggregation.
+50 -35
View File
@@ -4,8 +4,8 @@ import Foundation
import UIKit
#endif
public final class DatabasePool {
private let writer: SerializedDatabase
public final class DatabasePoolBase<API: SQLiteAPI> {
private let writer: SerializedDatabase<API>
/// The pool of reader connections.
/// It is constant, until close() sets it to nil.
@@ -143,9 +143,9 @@ public final class DatabasePool {
}
// @unchecked because of readerPool and suspensionObservers
extension DatabasePool: @unchecked Sendable { }
extension DatabasePoolBase: @unchecked Sendable { }
extension DatabasePool {
extension DatabasePoolBase {
// MARK: - Memory management
@@ -263,7 +263,7 @@ extension DatabasePool {
#endif
}
extension DatabasePool: DatabaseReader {
extension DatabasePoolBase: DatabaseReaderBase {
public func close() throws {
try readerPool?.barrier {
@@ -336,7 +336,7 @@ extension DatabasePool: DatabaseReader {
// MARK: - Reading from Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ value: (Database) throws -> T) throws -> T {
public func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
@@ -352,7 +352,7 @@ extension DatabasePool: DatabaseReader {
}
public func read<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
@@ -361,8 +361,13 @@ extension DatabasePool: DatabaseReader {
return try await readerPool.get { reader in
try await reader.execute { db in
defer {
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
// 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()
}
assert(!db.isInsideTransaction)
}
// The block isolation comes from the DEFERRED transaction.
@@ -374,7 +379,7 @@ extension DatabasePool: DatabaseReader {
}
public func asyncRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
@@ -387,8 +392,13 @@ extension DatabasePool: DatabaseReader {
// Second async jump because that's how `Pool.async` has to be used.
reader.async { db in
defer {
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
// 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()
}
assert(!db.isInsideTransaction)
releaseReader(.reuse)
}
@@ -408,7 +418,7 @@ extension DatabasePool: DatabaseReader {
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
public func unsafeRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
@@ -422,7 +432,7 @@ extension DatabasePool: DatabaseReader {
}
public func unsafeRead<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
@@ -437,7 +447,7 @@ extension DatabasePool: DatabaseReader {
}
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
@@ -465,7 +475,7 @@ extension DatabasePool: DatabaseReader {
}
}
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
if let reader = currentReader {
return try reader.reentrantSync(value)
} else if writer.onValidQueue {
@@ -484,7 +494,7 @@ extension DatabasePool: DatabaseReader {
}
public func spawnConcurrentRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
asyncConcurrentRead(value)
}
@@ -527,7 +537,7 @@ extension DatabasePool: DatabaseReader {
///
/// - parameter value: A function that accesses the database.
public func asyncConcurrentRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
// Check that we're on the writer queue...
writer.execute { db in
@@ -551,8 +561,13 @@ extension DatabasePool: DatabaseReader {
let (reader, releaseReader) = try readerPool.get()
reader.async { db in
defer {
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
// 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()
}
assert(!db.isInsideTransaction)
releaseReader(.reuse)
}
@@ -669,15 +684,15 @@ extension DatabasePool: DatabaseReader {
// MARK: - WAL Snapshot Transactions
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
/// Returns a long-lived WAL snapshot transaction on a reader connection.
func walSnapshotTransaction() throws -> WALSnapshotTransaction {
func walSnapshotTransaction() throws -> WALSnapshotTransactionBase<API> {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
let (reader, releaseReader) = try readerPool.get()
return try WALSnapshotTransaction(onReader: reader, release: { isInsideTransaction in
return try WALSnapshotTransactionBase(onReader: reader, release: { isInsideTransaction in
// Discard the connection if the transaction could not be
// properly ended. If we'd reuse it, the next read would
// fail because we'd fail starting a read transaction.
@@ -690,7 +705,7 @@ extension DatabasePool: DatabaseReader {
/// - important: The `completion` argument is executed in a serial
/// dispatch queue, so make sure you use the transaction asynchronously.
func asyncWALSnapshotTransaction(
_ completion: @escaping @Sendable (Result<WALSnapshotTransaction, Error>) -> Void
_ completion: @escaping @Sendable (Result<WALSnapshotTransactionBase<API>, Error>) -> Void
) {
guard let readerPool else {
completion(.failure(DatabaseError.connectionIsClosed()))
@@ -762,22 +777,22 @@ extension DatabasePool: DatabaseReader {
}
}
extension DatabasePool: DatabaseWriter {
extension DatabasePoolBase: DatabaseWriterBase {
// MARK: - Writing in Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
public func writeWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
try writer.sync(updates)
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: @Sendable (Database) throws -> T
_ updates: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
public func barrierWriteWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
@@ -787,7 +802,7 @@ extension DatabasePool: DatabaseWriter {
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @Sendable (Database) throws -> T
_ updates: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
@@ -817,7 +832,7 @@ extension DatabasePool: DatabaseWriter {
}
public func asyncBarrierWriteWithoutTransaction(
_ updates: @escaping @Sendable (Result<Database, Error>) -> Void
_ updates: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
guard let readerPool else {
updates(.failure(DatabaseError.connectionIsClosed()))
@@ -858,7 +873,7 @@ extension DatabasePool: DatabaseWriter {
/// - throws: The error thrown by `updates`, or by the wrapping transaction.
public func writeInTransaction(
_ kind: Database.TransactionKind? = nil,
_ updates: (Database) throws -> Database.TransactionCompletion)
_ updates: (DatabaseBase<API>) throws -> Database.TransactionCompletion)
throws
{
try writer.sync { db in
@@ -868,18 +883,18 @@ extension DatabasePool: DatabaseWriter {
}
}
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
public func unsafeReentrantWrite<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(
_ updates: @escaping @Sendable (Database) -> Void
_ updates: @escaping @Sendable (DatabaseBase<API>) -> Void
) {
writer.async(updates)
}
}
extension DatabasePool {
extension DatabasePoolBase {
// MARK: - Snapshots
@@ -935,7 +950,7 @@ extension DatabasePool {
purpose: "snapshot.\(databaseSnapshotCountMutex.increment())")
}
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
/// Creates a database snapshot that allows concurrent accesses to an
/// unchanging database content, as it exists at the moment the snapshot
/// is created.
+38 -28
View File
@@ -4,8 +4,8 @@ import Foundation
import UIKit
#endif
public final class DatabaseQueue {
private let writer: SerializedDatabase
public final class DatabaseQueueBase<API: SQLiteAPI> {
private let writer: SerializedDatabase<API>
/// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers.
private var suspensionObservers: [NSObjectProtocol] = []
@@ -124,9 +124,9 @@ public final class DatabaseQueue {
}
// @unchecked because of suspensionObservers
extension DatabaseQueue: @unchecked Sendable { }
extension DatabaseQueueBase: @unchecked Sendable { }
extension DatabaseQueue {
extension DatabaseQueueBase {
// MARK: - Memory management
@@ -183,7 +183,7 @@ extension DatabaseQueue {
#endif
}
extension DatabaseQueue: DatabaseReader {
extension DatabaseQueueBase: DatabaseReaderBase {
public func close() throws {
try writer.sync { try $0.close() }
}
@@ -225,7 +225,7 @@ extension DatabaseQueue: DatabaseReader {
// MARK: - Reading from Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ value: (Database) throws -> T) throws -> T {
public func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
try writer.sync { db in
try db.isolated(readOnly: true) {
try value(db)
@@ -234,7 +234,7 @@ extension DatabaseQueue: DatabaseReader {
}
public func read<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await writer.execute { db in
try db.isolated(readOnly: true) {
@@ -244,12 +244,17 @@ extension DatabaseQueue: DatabaseReader {
}
public func asyncRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
writer.async { db in
defer {
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
// 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()
}
assert(!db.isInsideTransaction)
try? db.endReadOnly()
}
@@ -268,28 +273,28 @@ extension DatabaseQueue: DatabaseReader {
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (Database) throws -> T) rethrows -> T {
public func unsafeRead<T>(_ value: (DatabaseBase<API>) throws -> T) rethrows -> T {
try writer.sync(value)
}
public func unsafeRead<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await writer.execute(value)
}
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
writer.async { value(.success($0)) }
}
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) rethrows -> T {
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<API>) throws -> T) rethrows -> T {
try writer.reentrantSync(value)
}
public func spawnConcurrentRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
// Check that we're on the writer queue...
writer.execute { db in
@@ -297,8 +302,13 @@ extension DatabaseQueue: DatabaseReader {
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
defer {
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
// 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()
}
assert(!db.isInsideTransaction)
try? db.endReadOnly()
}
@@ -339,7 +349,7 @@ extension DatabaseQueue: DatabaseReader {
}
}
extension DatabaseQueue: DatabaseWriter {
extension DatabaseQueueBase: DatabaseWriterBase {
// MARK: - Writing in Database
/// Wraps database operations inside a database transaction.
@@ -371,7 +381,7 @@ extension DatabaseQueue: DatabaseWriter {
/// - throws: The error thrown by `updates`, or by the wrapping transaction.
public func inTransaction(
_ kind: Database.TransactionKind? = nil,
_ updates: (Database) throws -> Database.TransactionCompletion)
_ updates: (DatabaseBase<API>) throws -> Database.TransactionCompletion)
throws
{
try writer.sync { db in
@@ -382,29 +392,29 @@ extension DatabaseQueue: DatabaseWriter {
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
public func writeWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
try writer.sync(updates)
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: @Sendable (Database) throws -> T
_ updates: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
public func barrierWriteWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) throws -> T {
try writer.sync(updates)
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @Sendable (Database) throws -> T
_ updates: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
public func asyncBarrierWriteWithoutTransaction(
_ updates: @escaping @Sendable (Result<Database, Error>) -> Void
_ updates: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
writer.async { updates(.success($0)) }
}
@@ -443,16 +453,16 @@ extension DatabaseQueue: DatabaseWriter {
///
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`.
public func inDatabase<T>(_ updates: (Database) throws -> T) rethrows -> T {
public func inDatabase<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
try writer.sync(updates)
}
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
public func unsafeReentrantWrite<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(
_ updates: @escaping @Sendable (Database) -> Void
_ updates: @escaping @Sendable (DatabaseBase<API>) -> Void
) {
writer.async(updates)
}
@@ -460,7 +470,7 @@ extension DatabaseQueue: DatabaseWriter {
// MARK: - Temp Copy
extension DatabaseQueue {
extension DatabaseQueueBase {
/// Returns a connection to an in-memory copy of the database at `path`.
///
/// Changes performed on the returned connection do not impact the
+27 -26
View File
@@ -52,7 +52,8 @@ import Dispatch
/// ### Supporting Types
///
/// - ``AnyDatabaseReader``
public protocol DatabaseReader: AnyObject, Sendable {
public protocol DatabaseReaderBase<API>: AnyObject, Sendable {
associatedtype API: SQLiteAPI
/// The database configuration.
var configuration: Configuration { get }
@@ -186,7 +187,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
/// would happen while establishing the database access.
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func read<T>(_ value: (Database) throws -> T) throws -> T
func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T
/// Executes read-only database operations, and returns their result after
/// they have finished executing.
@@ -215,7 +216,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// database access, or the error thrown by `value`, or
/// `CancellationError` if the task is cancelled.
func read<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T
/// Schedules read-only database operations for execution, and
@@ -245,7 +246,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func asyncRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
)
/// Executes database operations, and returns their result after they have
@@ -284,7 +285,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
/// would happen while establishing the database access.
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T
func unsafeRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -319,7 +320,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// database access, or the error thrown by `value`, or
/// `CancellationError` if the task is cancelled.
func unsafeRead<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T
/// Schedules database operations for execution, and returns immediately.
@@ -354,7 +355,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
)
/// Executes database operations, and returns their result after they have
@@ -398,7 +399,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// - parameter value: A closure which accesses the database.
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
/// would happen while establishing the database access.
func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T
func unsafeReentrantRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T
// MARK: - Value Observation
@@ -417,7 +418,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
) -> AnyDatabaseCancellable
}
extension DatabaseReader {
extension DatabaseReaderBase {
// MARK: - Backup
@@ -499,7 +500,7 @@ extension DatabaseReader {
}
#if canImport(Combine)
extension DatabaseReader {
extension DatabaseReaderBase {
// MARK: - Publishing Database Values
/// Returns a publisher that publishes one value and completes.
@@ -531,7 +532,7 @@ extension DatabaseReader {
/// - parameter value: A closure which accesses the database.
public func readPublisher<Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
value: @escaping @Sendable (Database) throws -> Output
value: @escaping @Sendable (DatabaseBase<API>) throws -> Output
) -> DatabasePublishers.Read<Output> {
OnDemandFuture { fulfill in
self.asyncRead { dbResult in
@@ -568,7 +569,7 @@ extension Publisher where Failure == Error {
}
#endif
extension DatabaseReader {
extension DatabaseReaderBase {
// MARK: - Value Observation Support
/// Adding an observation in a read-only database emits only the
@@ -619,17 +620,17 @@ extension DatabaseReader {
///
/// An instance of `AnyDatabaseReader` forwards its operations to an underlying
/// base database reader.
public final class AnyDatabaseReader {
private let base: any DatabaseReader
public final class AnyDatabaseReaderBase<API: SQLiteAPI> {
private let base: any DatabaseReader<API>
/// Creates a new database reader that wraps and forwards operations
/// to `base`.
public init(_ base: any DatabaseReader) {
public init(_ base: any DatabaseReader<API>) {
self.base = base
}
}
extension AnyDatabaseReader: DatabaseReader {
extension AnyDatabaseReaderBase: DatabaseReaderBase {
public var configuration: Configuration {
base.configuration
}
@@ -647,40 +648,40 @@ extension AnyDatabaseReader: DatabaseReader {
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ value: (Database) throws -> T) throws -> T {
public func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
try base.read(value)
}
public func read<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await base.read(value)
}
public func asyncRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
base.asyncRead(value)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
public func unsafeRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
try base.unsafeRead(value)
}
public func unsafeRead<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await base.unsafeRead(value)
}
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
base.asyncUnsafeRead(value)
}
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
try base.unsafeReentrantRead(value)
}
@@ -735,20 +736,20 @@ extension DatabaseSnapshotReader {
/// - parameter value: A closure which accesses the database.
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
/// would happen while establishing the database access.
public func reentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
public func reentrantRead<T>(_ value: (DatabaseBase<API>) 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: (Database) throws -> T) throws -> T {
public func unsafeRead<T>(_ value: (DatabaseBase<API>) 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<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, 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: Database) throws -> DatabaseRegion {
func observableRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion {
// SQLite does not expose schema changes to the
// TransactionObserver protocol. By removing internal SQLite tables from
// the observed region, we optimize database observation.
@@ -178,7 +178,7 @@ public struct DatabaseRegion: Sendable {
/// Returns a region only made of actual tables with their canonical names.
///
/// This method removes views.
func canonicalTables(_ db: Database) throws -> DatabaseRegion {
func canonicalTables(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion {
guard let tableRegions else { return .fullDatabase }
var region = DatabaseRegion()
for (table, tableRegion) in tableRegions {
@@ -237,7 +237,7 @@ extension DatabaseRegion {
/// Returns an array of all event kinds that can impact this region.
///
/// - precondition: the region is canonical.
func impactfulEventKinds(_ db: Database) throws -> [DatabaseEventKind] {
func impactfulEventKinds(_ db: DatabaseBase<some SQLiteAPI>) 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.schemaIdentifiers().flatMap { schemaIdentifier in
let schema = try db.schema(schemaIdentifier)
return try db.fetchSchemaIdentifiers().flatMap { schemaID in
let schema = try db.schema(schemaID)
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: Database) throws -> DatabaseRegion
func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
}
extension DatabaseRegionConvertible where Self == DatabaseRegion {
@@ -430,16 +430,16 @@ extension DatabaseRegionConvertible where Self == DatabaseRegion {
}
extension DatabaseRegion: DatabaseRegionConvertible {
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
public func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion {
self
}
}
/// A type-erased DatabaseRegionConvertible
public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
let _region: @Sendable (Database) throws -> DatabaseRegion
let _region: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
public init(_ region: @escaping @Sendable (Database) throws -> DatabaseRegion) {
public init(_ region: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion) {
_region = region
}
@@ -447,7 +447,7 @@ public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
_region = { try region.databaseRegion($0) }
}
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
public func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion {
try _region(db)
}
}
@@ -461,7 +461,7 @@ extension DatabaseRegion {
}
}
static func union(_ regions: [any DatabaseRegionConvertible]) -> @Sendable (Database) throws -> DatabaseRegion {
static func union<API: SQLiteAPI>(_ regions: [any DatabaseRegionConvertible]) -> @Sendable (DatabaseBase<API>) throws -> DatabaseRegion {
return { db in
try regions.reduce(into: DatabaseRegion()) { union, region in
try union.formUnion(region.databaseRegion(db))
+13 -9
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 (Database) throws -> DatabaseRegion
var observedRegion: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
}
extension DatabaseRegionObservation {
@@ -87,7 +87,7 @@ extension DatabaseRegionObservation {
public func start(
in writer: any DatabaseWriter,
onError: @escaping @Sendable (Error) -> Void,
onChange: @escaping @Sendable (Database) -> Void)
onChange: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) -> Void)
-> AnyDatabaseCancellable
{
let stateMutex = Mutex(ObservationState.pending)
@@ -146,12 +146,12 @@ extension DatabaseRegionObservation {
}
#endif
private class DatabaseRegionObserver: TransactionObserver {
private class DatabaseRegionObserver: TransactionObserverBase {
let region: DatabaseRegion
let onChange: @Sendable (Database) -> Void
let onChange: @Sendable (DatabaseBase<some SQLiteAPI>) -> Void
var isChanged = false
init(region: DatabaseRegion, onChange: @escaping @Sendable (Database) -> Void) {
init(region: DatabaseRegion, onChange: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) -> Void) {
self.region = region
self.onChange = onChange
}
@@ -172,14 +172,14 @@ private class DatabaseRegionObserver: TransactionObserver {
}
}
func databaseDidCommit(_ db: Database) {
func databaseDidCommit(_ db: DatabaseBase<some SQLiteAPI>) {
guard isChanged else { return }
isChanged = false
onChange(db)
}
func databaseDidRollback(_ db: Database) {
func databaseDidRollback(_ db: DatabaseBase<some SQLiteAPI>) {
isChanged = false
}
}
@@ -201,7 +201,11 @@ extension DatabasePublishers {
self.observation = observation
}
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
public func receive<S>(subscriber: S)
where S: Subscriber & GRDBSendableMetatype,
Failure == S.Failure,
Output == S.Input
{
let subscription = DatabaseRegionSubscription(
writer: writer,
observation: observation,
@@ -212,7 +216,7 @@ extension DatabasePublishers {
private class DatabaseRegionSubscription<Downstream>:
Subscription, @unchecked Sendable
where Downstream: Subscriber,
where Downstream: Subscriber & GRDBSendableMetatype,
Downstream.Failure == Error,
Downstream.Input == Database
{
+218
View File
@@ -0,0 +1,218 @@
/// 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
}
}
+14 -9
View File
@@ -113,8 +113,13 @@ public final class DatabaseSnapshot {
deinit {
// Leave snapshot isolation
reader.reentrantSync { db in
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
// 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()
}
assert(!db.isInsideTransaction)
}
}
@@ -149,24 +154,24 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
// MARK: - Reading from Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
public func read<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T {
try reader.sync(block)
}
public func read<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> T
) async throws -> T {
try await reader.execute(value)
}
public func asyncRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<some SQLiteAPI>, Error>) -> Void
) {
reader.async { value(.success($0)) }
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (Database) throws -> T) rethrows -> T {
public func unsafeRead<T>(_ value: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T {
try reader.sync(value)
}
@@ -175,18 +180,18 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
// `DatabaseSnapshotReader`, because of
// <https://github.com/apple/swift/issues/74469>.
public func unsafeRead<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> T
) async throws -> T {
try await read(value)
}
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<some SQLiteAPI>, Error>) -> Void
) {
reader.async { value(.success($0)) }
}
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T {
try reader.reentrantSync(value)
}
+20 -17
View File
@@ -1,12 +1,15 @@
#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
#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
/// A database connection that allows concurrent accesses to an unchanging
/// database content, as it existed at the moment the snapshot was created.
@@ -129,7 +132,7 @@ public final class DatabaseSnapshotPool {
/// - parameter configuration: A configuration. If nil, the configuration of
/// `db` is used.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public init(_ db: Database, configuration: Configuration? = nil) throws {
public init(_ db: DatabaseBase<some SQLiteAPI>, configuration: Configuration? = nil) throws {
let path = db.path
var configuration = Self.configure(configuration ?? db.configuration)
@@ -270,7 +273,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ value: (Database) throws -> T) throws -> T {
public func read<T>(_ value: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T {
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
@@ -294,7 +297,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
public func read<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> T
) async throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
@@ -316,7 +319,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
public func asyncRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<some SQLiteAPI>, Error>) -> Void
) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
@@ -342,12 +345,12 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
// `DatabaseSnapshotReader`, because of
// <https://github.com/apple/swift/issues/74469>.
public func unsafeRead<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> T
) async throws -> T {
try await read(value)
}
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T {
if let reader = currentReader {
return try reader.reentrantSync { db in
let result = try value(db)
@@ -396,11 +399,11 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
return readers.first { $0.onValidQueue }
}
private func poolCompletion(_ db: Database) -> PoolCompletion {
private func poolCompletion(_ db: DatabaseBase<some SQLiteAPI>) -> PoolCompletion {
snapshotIsLost(db) ? .discard : .reuse
}
private func snapshotIsLost(_ db: Database) -> Bool {
private func snapshotIsLost(_ db: DatabaseBase<some SQLiteAPI>) -> Bool {
do {
let currentSnapshot = try WALSnapshot(db)
if currentSnapshot.compare(walSnapshot) == 0 {
+13 -10
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -159,7 +162,7 @@ public struct DatabaseValue: Hashable {
}
/// Creates a `DatabaseValue` initialized from a raw SQLite statement pointer.
public init(sqliteStatement: SQLiteStatement, index: CInt) {
public init(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_NULL:
storage = .null
@@ -184,7 +187,7 @@ public struct DatabaseValue: Hashable {
}
extension DatabaseValue: StatementBinding {
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, 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: SQLiteStatement, at index: CInt) -> CInt {
public func bind(to sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, at index: CInt) -> CInt {
databaseValue.bind(to: sqliteStatement, at: index)
}
@@ -276,7 +276,7 @@ extension DatabaseValueConvertible {
/// - returns: A ``DatabaseValueCursor`` over fetched values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
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: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> [Self]
@@ -341,7 +341,7 @@ extension DatabaseValueConvertible {
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Self?
@@ -376,7 +376,7 @@ extension DatabaseValueConvertible where Self: Hashable {
/// - returns: A set.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
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: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -453,7 +453,7 @@ extension DatabaseValueConvertible {
/// - returns: An array.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -488,7 +488,7 @@ extension DatabaseValueConvertible {
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -522,7 +522,7 @@ extension DatabaseValueConvertible where Self: Hashable {
/// - returns: A set.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -581,7 +581,7 @@ extension DatabaseValueConvertible {
/// - request: A fetch request.
/// - returns: A ``DatabaseValueCursor`` over fetched values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: some FetchRequest) throws -> DatabaseValueCursor<Self> {
public static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, _ 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: Database, _ request: some FetchRequest) throws -> [Self] {
public static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> [Self] {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchAll(request.statement, adapter: request.adapter)
}
@@ -666,7 +666,7 @@ extension DatabaseValueConvertible {
/// - request: A fetch request.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
public static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> Self? {
let request = try request.makePreparedRequest(db, forSingleResult: true)
return try fetchOne(request.statement, adapter: request.adapter)
}
@@ -709,7 +709,7 @@ extension DatabaseValueConvertible where Self: Hashable {
/// - request: A fetch request.
/// - returns: A set.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
public static func fetchSet(_ db: DatabaseBase<some SQLiteAPI>, _ 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: Database) throws -> DatabaseValueCursor<RowDecoder> {
public func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) 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: Database) throws -> [RowDecoder] {
public func fetchAll(_ db: DatabaseBase<some SQLiteAPI>) throws -> [RowDecoder] {
try RowDecoder.fetchAll(db, self)
}
@@ -841,7 +841,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
public func fetchOne(_ db: DatabaseBase<some SQLiteAPI>) throws -> RowDecoder? {
try RowDecoder.fetchOne(db, self)
}
}
@@ -874,7 +874,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable {
/// - parameter db: A database connection.
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
public func fetchSet(_ db: DatabaseBase<some SQLiteAPI>) throws -> Set<RowDecoder> {
try RowDecoder.fetchSet(db, self)
}
}
+32 -32
View File
@@ -61,7 +61,7 @@ import Dispatch
/// ### Supporting Types
///
/// - ``AnyDatabaseWriter``
public protocol DatabaseWriter: DatabaseReader {
public protocol DatabaseWriterBase: DatabaseReaderBase {
// MARK: - Writing in Database
@@ -98,7 +98,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`.
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
func writeWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -130,7 +130,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// database access, or the error thrown by `updates`, or
/// `CancellationError` if the task is cancelled.
func writeWithoutTransaction<T: Sendable>(
_ updates: @Sendable (Database) throws -> T
_ updates: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T
/// Executes database operations, and returns their result after they have
@@ -171,7 +171,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`.
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T
func barrierWriteWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) throws -> T
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -213,7 +213,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// database access, or the error thrown by `updates`, or
/// `CancellationError` if the task is cancelled.
func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @Sendable (Database) throws -> T
_ updates: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T
/// Schedules database operations for execution, and returns immediately.
@@ -256,7 +256,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the barrier access to the database.
func asyncBarrierWriteWithoutTransaction(
_ updates: @escaping @Sendable (Result<Database, Error>) -> Void
_ updates: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
)
/// Schedules database operations for execution, and returns immediately.
@@ -290,7 +290,7 @@ public protocol DatabaseWriter: DatabaseReader {
///
/// - parameter updates: A closure which accesses the database.
func asyncWriteWithoutTransaction(
_ updates: @escaping @Sendable (Database) -> Void
_ updates: @escaping @Sendable (DatabaseBase<API>) -> Void
)
/// Executes database operations, and returns their result after they have
@@ -325,7 +325,7 @@ public protocol DatabaseWriter: DatabaseReader {
///
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`.
func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T
func unsafeReentrantWrite<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T
// MARK: - Reading from Database
@@ -374,7 +374,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func spawnConcurrentRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, 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: (Database) throws -> T) throws -> T {
public func write<T>(_ updates: (DatabaseBase<API>) 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 (Database) throws -> T,
_ updates: @escaping @Sendable (DatabaseBase<API>) 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: Database.TransactionObservationExtent = .observerLifetime)
extent: DatabaseTransactionObservationExtent = .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 || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// 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 (Database) throws -> T
_ updates: @Sendable (DatabaseBase<API>) 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 || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// 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 (Database) throws -> Output
updates: @escaping @Sendable (DatabaseBase<API>) 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 (Database) throws -> T,
updates: @escaping @Sendable (DatabaseBase<API>) 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: (Database) throws -> T) throws -> T {
public func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
try base.read(value)
}
public func read<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await base.read(value)
}
public func asyncRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
base.asyncRead(value)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
public func unsafeRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
try base.unsafeRead(value)
}
public func unsafeRead<T: Sendable>(
_ value: @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await base.unsafeRead(value)
}
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
base.asyncUnsafeRead(value)
}
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<API>) 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: (Database) throws -> T) rethrows -> T {
public func writeWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
try base.writeWithoutTransaction(updates)
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: @Sendable (Database) throws -> T
_ updates: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await base.writeWithoutTransaction(updates)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
public func barrierWriteWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) throws -> T {
try base.barrierWriteWithoutTransaction(updates)
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @Sendable (Database) throws -> T
_ updates: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await base.barrierWriteWithoutTransaction(updates)
}
public func asyncBarrierWriteWithoutTransaction(
_ updates: @escaping @Sendable (Result<Database, Error>) -> Void
_ updates: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
base.asyncBarrierWriteWithoutTransaction(updates)
}
public func asyncWriteWithoutTransaction(
_ updates: @escaping @Sendable (Database) -> Void
_ updates: @escaping @Sendable (DatabaseBase<API>) -> Void
) {
base.asyncWriteWithoutTransaction(updates)
}
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
public func unsafeReentrantWrite<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
try base.unsafeReentrantWrite(updates)
}
public func spawnConcurrentRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
base.spawnConcurrentRead(value)
}
+4
View File
@@ -43,3 +43,7 @@ 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(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
func makePreparedRequest<API>(_ db: DatabaseBase<API>, forSingleResult singleResult: Bool) throws -> PreparedRequestBase<API>
/// Returns the number of rows fetched by the request.
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
func fetchCount(_ db: Database) throws -> Int
func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int
}
extension FetchRequest {
/// Returns the database region that the request feeds from.
///
/// - parameter db: A database connection.
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
public func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) 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 = (
_ db: Database,
typealias SupplementaryFetch<API: SQLiteAPI> = (
_ db: DatabaseBase<API>,
_ rows: [Row],
_ willExecuteSupplementaryRequest: WillExecuteSupplementaryRequest?)
throws -> Void
/// A `PreparedRequest` is a request that is ready to be executed.
public struct PreparedRequest {
public struct PreparedRequestBase<API: SQLiteAPI> {
/// A prepared statement with bound parameters.
public var statement: Statement
public var statement: StatementBase<API>
/// An eventual adapter for rows fetched by the select statement.
public var adapter: (any RowAdapter)?
/// A closure that performs supplementary fetches.
/// Support for eager loading of hasMany associations.
var supplementaryFetch: SupplementaryFetch?
var supplementaryFetch: SupplementaryFetch<API>?
init(
statement: Statement,
statement: StatementBase<API>,
adapter: (any RowAdapter)?,
supplementaryFetch: SupplementaryFetch? = nil)
supplementaryFetch: SupplementaryFetch<API>? = nil)
{
self.statement = statement
self.adapter = adapter
@@ -172,7 +172,7 @@ extension FetchRequest {
/// - parameter adapter: A closure that accepts a database connection and
/// returns a row adapter.
public func adapted(
_ adapter: @escaping @Sendable (Database) throws -> any RowAdapter
_ adapter: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) 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 (Database) throws -> any RowAdapter
let adapter: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> any RowAdapter
/// Creates an adapted request from a base request and a closure that builds
/// a row adapter from a database connection.
init(_ base: Base, _ adapter: @escaping @Sendable (Database) throws -> any RowAdapter) {
init(_ base: Base, _ adapter: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> any RowAdapter) {
self.base = base
self.adapter = adapter
}
@@ -202,14 +202,14 @@ extension AdaptedFetchRequest: SQLSubqueryable {
extension AdaptedFetchRequest: FetchRequest {
public typealias RowDecoder = Base.RowDecoder
public func fetchCount(_ db: Database) throws -> Int {
public func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
try base.fetchCount(db)
}
public func makePreparedRequest(
_ db: Database,
public func makePreparedRequest<API>(
_ db: DatabaseBase<API>,
forSingleResult singleResult: Bool = false)
throws -> PreparedRequest
throws -> PreparedRequestBase<API>
{
var preparedRequest = try base.makePreparedRequest(db, forSingleResult: singleResult)
@@ -262,14 +262,14 @@ extension AnyFetchRequest: SQLSubqueryable {
}
extension AnyFetchRequest: FetchRequest {
public func fetchCount(_ db: Database) throws -> Int {
public func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
try request.fetchCount(db)
}
public func makePreparedRequest(
_ db: Database,
public func makePreparedRequest<API>(
_ db: DatabaseBase<API>,
forSingleResult singleResult: Bool = false)
throws -> PreparedRequest
throws -> PreparedRequestBase<API>
{
try request.makePreparedRequest(db, forSingleResult: singleResult)
}
@@ -283,11 +283,11 @@ private class FetchRequestEraser: FetchRequest, @unchecked Sendable {
fatalError("subclass must override")
}
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
func makePreparedRequest<API>(_ db: DatabaseBase<API>, forSingleResult singleResult: Bool) throws -> PreparedRequestBase<API> {
fatalError("subclass must override")
}
func fetchCount(_ db: Database) throws -> Int {
func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
fatalError("subclass must override")
}
}
@@ -303,11 +303,11 @@ private final class ConcreteFetchRequestEraser<Request: FetchRequest>: FetchRequ
request.sqlSubquery
}
override func fetchCount(_ db: Database) throws -> Int {
override func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
try request.fetchCount(db)
}
override func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
override func makePreparedRequest<API>(_ db: DatabaseBase<API>, forSingleResult singleResult: Bool) throws -> PreparedRequestBase<API> {
try request.makePreparedRequest(db, forSingleResult: singleResult)
}
}
+31 -28
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -231,7 +234,7 @@ public final class Row {
/// The row is implemented on top of StatementRowImpl, which grants *direct*
/// access to the SQLite statement. Iteration of the statement does modify
/// the row.
init(statement: Statement) {
init(statement: StatementBase<some SQLiteAPI>) {
self.statement = statement
self.sqliteStatement = statement.sqliteStatement
self.impl = StatementRowImpl(sqliteStatement: statement.sqliteStatement, statement: statement)
@@ -240,7 +243,7 @@ public final class Row {
/// Creates a row that maps an SQLite statement. Further calls to
/// sqlite3_step() modify the row.
init(sqliteStatement: SQLiteStatement) {
init(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>) {
self.statement = nil
self.sqliteStatement = sqliteStatement
self.impl = SQLiteStatementRowImpl(sqliteStatement: sqliteStatement)
@@ -254,8 +257,8 @@ public final class Row {
/// the values from the SQLite statement so that further iteration of the
/// statement does not modify the row.
convenience init(
copiedFromSQLiteStatement sqliteStatement: SQLiteStatement,
statement: Statement)
copiedFromSQLiteStatement sqliteStatement: SQLiteStatementBase<some SQLiteAPI>,
statement: StatementBase<some SQLiteAPI>)
{
self.init(impl: StatementCopyRowImpl(
sqliteStatement: sqliteStatement,
@@ -1733,7 +1736,7 @@ extension Row {
/// - returns: A ``RowCursor`` over fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> RowCursor
@@ -1761,7 +1764,7 @@ extension Row {
/// - returns: An array of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> [Row]
@@ -1790,7 +1793,7 @@ extension Row {
/// - returns: A set of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Set<Row>
@@ -1819,7 +1822,7 @@ extension Row {
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Row?
@@ -1874,7 +1877,7 @@ extension Row {
/// - returns: A ``RowCursor`` over fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -1903,7 +1906,7 @@ extension Row {
/// - returns: An array of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -1932,7 +1935,7 @@ extension Row {
/// - returns: A set of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -1961,7 +1964,7 @@ extension Row {
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -2024,7 +2027,7 @@ extension Row {
/// - request: A fetch request.
/// - returns: A ``RowCursor`` over fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: some FetchRequest) throws -> RowCursor {
public static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, _ 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)
@@ -2061,7 +2064,7 @@ extension Row {
/// - request: A fetch request.
/// - returns: An array of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Row] {
public static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, _ 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)
@@ -2099,7 +2102,7 @@ extension Row {
/// - request: A fetch request.
/// - returns: A set of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Row> {
public static func fetchSet(_ db: DatabaseBase<some SQLiteAPI>, _ 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)
@@ -2141,7 +2144,7 @@ extension Row {
/// - request: A fetch request.
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Row? {
public static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, _ 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
@@ -2190,7 +2193,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: Database) throws -> RowCursor {
public func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> RowCursor {
try Row.fetchCursor(db, self)
}
@@ -2211,7 +2214,7 @@ extension FetchRequest<Row> {
/// - parameter db: A database connection.
/// - returns: An array of fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [Row] {
public func fetchAll(_ db: DatabaseBase<some SQLiteAPI>) throws -> [Row] {
try Row.fetchAll(db, self)
}
@@ -2232,7 +2235,7 @@ extension FetchRequest<Row> {
/// - parameter db: A database connection.
/// - returns: A set of fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<Row> {
public func fetchSet(_ db: DatabaseBase<some SQLiteAPI>) throws -> Set<Row> {
try Row.fetchSet(db, self)
}
@@ -2253,7 +2256,7 @@ extension FetchRequest<Row> {
/// - parameter db: A database connection.
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> Row? {
public func fetchOne(_ db: DatabaseBase<some SQLiteAPI>) throws -> Row? {
try Row.fetchOne(db, self)
}
}
+11 -8
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
/// A key that is used to decode a value in a row
@usableFromInline
+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: Database) throws -> (sql: String, arguments: StatementArguments) {
public func build(_ db: DatabaseBase<some SQLiteAPI>) 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: Database) throws -> Int {
public func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
try SQLRequest<Int>("SELECT COUNT(*) FROM (\(self))").fetchOne(db)!
}
public func makePreparedRequest(
_ db: Database,
public func makePreparedRequest<API>(
_ db: DatabaseBase<API>,
forSingleResult singleResult: Bool = false)
throws -> PreparedRequest
throws -> PreparedRequestBase<API>
{
let context = SQLGenerationContext(db)
let sql = try sqlLiteral.sql(context)
+20
View File
@@ -0,0 +1,20 @@
public protocol SQLiteAPI {
static var SQLITE_NULL: CInt { get }
static var SQLITE_OK: CInt { get }
static func sqlite3_bind_double(_: OpaquePointer?, _: CInt, _: CDouble) -> CInt
static func sqlite3_bind_int64(_: OpaquePointer?, _: CInt, _: Int64) -> CInt
static func sqlite3_bind_null(_: OpaquePointer?, _: CInt) -> CInt
static func sqlite3_bind_text(_: OpaquePointer?, _: CInt, _: UnsafePointer<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: Database,
_ db: DatabaseBase<some SQLiteAPI>,
_ message: @autoclosure() -> String = "Database was not used on the correct thread.",
file: StaticString = #file,
line: UInt = #line)
@@ -69,11 +69,11 @@ final class SchedulingWatchdog: @unchecked Sendable {
/// Returns whether the database argument can be used in the current
/// dispatch queue.
static func allows(_ db: Database) -> Bool {
static func allows(_ db: DatabaseBase<some SQLiteAPI>) -> Bool {
current?.allows(db) ?? false
}
func allows(_ db: Database) -> Bool {
func allows(_ db: DatabaseBase<some SQLiteAPI>) -> 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 SerializedDatabase {
final class SerializedDatabaseBase<API: SQLiteAPI> {
/// The database connection
private let db: Database
private let db: DatabaseBase<API>
/// The actor that performs asynchronous accesses
private let actor: DispatchQueueActor
@@ -92,7 +92,7 @@ final class SerializedDatabase {
/// - parameter allowingLongLivedTransaction: When true, the
/// ``Configuration/allowsUnsafeTransactions`` configuration flag is
/// ignored until this method is called again with false.
func sync<T>(allowingLongLivedTransaction: Bool, _ body: (Database) throws -> T) rethrows -> T {
func sync<T>(allowingLongLivedTransaction: Bool, _ body: (DatabaseBase<API>) throws -> T) rethrows -> T {
try sync { db in
self.allowsUnsafeTransactions = allowingLongLivedTransaction
return try body(db)
@@ -103,7 +103,7 @@ final class SerializedDatabase {
/// have finished executing.
///
/// This method is not reentrant.
func sync<T>(_ block: (Database) throws -> T) rethrows -> T {
func sync<T>(_ block: (DatabaseBase<API>) throws -> T) rethrows -> T {
// Three different cases:
//
// 1. A database is invoked from some queue like the main queue:
@@ -153,7 +153,7 @@ final class SerializedDatabase {
/// - parameter allowingLongLivedTransaction: When true, the
/// ``Configuration/allowsUnsafeTransactions`` configuration flag is
/// ignored until this method is called again with false.
func reentrantSync<T>(allowingLongLivedTransaction: Bool, _ body: (Database) throws -> T) rethrows -> T {
func reentrantSync<T>(allowingLongLivedTransaction: Bool, _ body: (DatabaseBase<API>) throws -> T) rethrows -> T {
try reentrantSync { db in
self.allowsUnsafeTransactions = allowingLongLivedTransaction
return try body(db)
@@ -164,7 +164,7 @@ final class SerializedDatabase {
/// have finished executing.
///
/// This method is reentrant.
func reentrantSync<T>(_ block: (Database) throws -> T) rethrows -> T {
func reentrantSync<T>(_ block: (DatabaseBase<API>) throws -> T) rethrows -> T {
// Three different cases:
//
// 1. A database is invoked from some queue like the main queue:
@@ -228,7 +228,7 @@ final class SerializedDatabase {
}
/// Schedules database operations for execution, and returns immediately.
func async(_ block: @escaping @Sendable (Database) -> Void) {
func async(_ block: @escaping @Sendable (DatabaseBase<API>) -> Void) {
queue.async {
block(self.db)
self.preconditionNoUnsafeTransactionLeft(self.db)
@@ -243,14 +243,14 @@ final class SerializedDatabase {
/// Executes the block in the current queue.
///
/// - precondition: the current dispatch queue is valid.
func execute<T>(_ block: (Database) throws -> T) rethrows -> T {
func execute<T>(_ block: (DatabaseBase<API>) throws -> T) rethrows -> T {
preconditionValidQueue()
return try block(db)
}
/// Asynchrously executes the block.
func execute<T: Sendable>(
_ block: @Sendable (Database) throws -> T
_ block: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
let cancelMutex = Mutex<(@Sendable () -> Void)?>(nil)
return try await withTaskCancellationHandler {
@@ -295,7 +295,7 @@ final class SerializedDatabase {
/// Fatal error if a transaction has been left opened.
private func preconditionNoUnsafeTransactionLeft(
_ db: Database,
_ db: DatabaseBase<API>,
_ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access",
file: StaticString = #file,
line: UInt = #line)
+20 -14
View File
@@ -1,16 +1,22 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
/// A raw SQLite statement, suitable for the SQLite C API.
public typealias SQLiteStatement = OpaquePointer
//public typealias SQLiteStatement = OpaquePointer
public struct SQLiteStatementBase<API: SQLiteAPI> {
public let rawValue: OpaquePointer
}
extension String {
/// SQL statements are separated by semicolons and white spaces.
@@ -34,7 +40,7 @@ extension String {
}
}
public final class Statement {
public final class StatementBase<API: SQLiteAPI> {
enum TransactionEffect: Equatable {
case beginTransaction
case commitTransaction
@@ -45,7 +51,7 @@ public final class Statement {
}
/// The raw SQLite statement, suitable for the SQLite C API.
public let sqliteStatement: SQLiteStatement
public let sqliteStatement: SQLiteStatementBase<API>
/// The SQL query.
public var sql: String {
@@ -141,7 +147,7 @@ public final class Statement {
let authorizer = database.authorizer
authorizer.reset()
var sqliteStatement: SQLiteStatement? = nil
var sqliteStatement: SQLiteStatement?
let code = sqlite3_prepare_v3(
database.sqliteConnection, statementStart, -1, prepFlags,
&sqliteStatement, statementEnd)
@@ -836,11 +842,11 @@ public protocol StatementBinding {
/// - parameter sqliteStatement: An SQLite statement.
/// - parameter index: 1-based index to statement arguments.
/// - returns: the code returned by the `sqlite3_bind_xxx` function.
func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt
func bind(to sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, at index: CInt) -> CInt
}
/// Helper function for `withBinding(to:at:do:)` methods.
func checkBindingSuccess(code: CInt, sqliteStatement: SQLiteStatement) throws {
func checkBindingSuccess(code: CInt, sqliteStatement: SQLiteStatementBase<some SQLiteAPI>) throws {
if code == SQLITE_OK { return }
let message = String(cString: sqlite3_errmsg(sqlite3_db_handle(sqliteStatement)))
let sql = String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
+11 -8
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
#if canImport(string_h)
import string_h
+37 -31
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
/// A type that can decode itself from the low-level C interface to
/// SQLite results.
@@ -89,10 +92,10 @@ public protocol StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
/// - returns: A decoded value, or, if decoding is impossible, nil.
static func fromStatement(
_ sqliteStatement: SQLiteStatement,
atUncheckedIndex index: CInt)
-> Self?
static func fromStatement<API>(
_ sqliteStatement: SQLiteStatementBase<API>,
atUncheckedIndex index: CInt
) -> Self?
/// Creates an instance from a raw SQLite statement pointer, if possible.
///
@@ -104,7 +107,7 @@ public protocol StatementColumnConvertible {
///
/// ```swift
/// extension Int64: StatementColumnConvertible {
/// public init(sqliteStatement: SQLiteStatement, index: CInt) {
/// public init(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
/// self = sqlite3_column_int64(sqliteStatement, index)
/// }
/// }
@@ -117,7 +120,7 @@ public protocol StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
init?(sqliteStatement: SQLiteStatement, index: CInt)
init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt)
}
extension StatementColumnConvertible {
@@ -125,7 +128,10 @@ extension StatementColumnConvertible {
/// Default implementation fails on decoding NULL.
@inline(__always)
@inlinable
public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt) -> Self? {
public static func fromStatement<API>(
_ sqliteStatement: SQLiteStatementBase<API>,
atUncheckedIndex index: CInt
) -> Self? {
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
return nil
}
@@ -295,7 +301,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: A ``FastDatabaseValueCursor`` over fetched values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> FastDatabaseValueCursor<Self>
@@ -326,7 +332,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> [Self]
@@ -360,7 +366,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Self?
@@ -398,7 +404,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Set<Self>
@@ -443,7 +449,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: A ``FastDatabaseValueCursor`` over fetched values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -475,7 +481,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -510,7 +516,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -544,7 +550,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -603,7 +609,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - request: A fetch request.
/// - returns: A ``FastDatabaseValueCursor`` over fetched values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: some FetchRequest)
public static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest)
throws -> FastDatabaseValueCursor<Self>
{
let request = try request.makePreparedRequest(db, forSingleResult: false)
@@ -646,7 +652,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - request: A fetch request.
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
public static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> [Self] {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchAll(request.statement, adapter: request.adapter)
}
@@ -690,7 +696,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - request: A fetch request.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
public static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> Self? {
let request = try request.makePreparedRequest(db, forSingleResult: true)
return try fetchOne(request.statement, adapter: request.adapter)
}
@@ -733,7 +739,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
/// - request: A fetch request.
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
public static func fetchSet(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> Set<Self> {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchSet(request.statement, adapter: request.adapter)
}
@@ -786,7 +792,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// - parameter db: A database connection.
/// - returns: A ``FastDatabaseValueCursor`` over fetched values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> FastDatabaseValueCursor<RowDecoder> {
public func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> FastDatabaseValueCursor<RowDecoder> {
try RowDecoder.fetchCursor(db, self)
}
@@ -824,7 +830,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
public func fetchAll(_ db: DatabaseBase<some SQLiteAPI>) throws -> [RowDecoder] {
try RowDecoder.fetchAll(db, self)
}
@@ -865,7 +871,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
public func fetchOne(_ db: DatabaseBase<some SQLiteAPI>) throws -> RowDecoder? {
try RowDecoder.fetchOne(db, self)
}
}
@@ -905,7 +911,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// - parameter db: A database connection.
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
public func fetchSet(_ db: DatabaseBase<some SQLiteAPI>) throws -> Set<RowDecoder> {
try RowDecoder.fetchSet(db, self)
}
}
+13 -10
View File
@@ -1,17 +1,20 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
/// Data is convertible to and from DatabaseValue.
extension Data: DatabaseValueConvertible, StatementColumnConvertible {
public init(sqliteStatement: SQLiteStatement, index: CInt) {
public init(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, 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
@@ -46,7 +49,7 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
}
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
withUnsafeBytes {
sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
}
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -78,7 +81,7 @@ extension DatabaseDateComponents: StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
guard let cString = sqlite3_column_text(sqliteStatement, index) else {
return nil
}
+12 -9
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -133,7 +136,7 @@ extension Date: StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_INTEGER, SQLITE_FLOAT:
self.init(timeIntervalSince1970: sqlite3_column_double(sqliteStatement, index))
+12 -9
View File
@@ -1,12 +1,15 @@
#if !os(Linux)
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -47,7 +50,7 @@ extension Decimal: DatabaseValueConvertible {
extension Decimal: StatementColumnConvertible {
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_INTEGER:
self.init(sqlite3_column_int64(sqliteStatement, index))
+12 -9
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -78,7 +81,7 @@ extension UUID: DatabaseValueConvertible {
extension UUID: StatementColumnConvertible {
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, 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: SQLiteStatement, at index: CInt) -> CInt {
public func bind(to sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, at index: CInt) -> CInt {
rawValue.bind(to: sqliteStatement, at: index)
}
}
@@ -41,7 +41,7 @@ extension StatementBinding where Self: RawRepresentable, Self.RawValue: Statemen
extension StatementColumnConvertible where Self: RawRepresentable, Self.RawValue: StatementColumnConvertible {
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
guard let rawValue = RawValue(sqliteStatement: sqliteStatement, index: index) else {
return nil
}
@@ -1,17 +1,20 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
extension Optional: StatementBinding where Wrapped: StatementBinding {
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
switch self {
case .none:
return sqlite3_bind_null(sqliteStatement, index)
return API.sqlite3_bind_null(sqliteStatement.rawValue, index)
case let .some(value):
return value.bind(to: sqliteStatement, at: index)
}
@@ -84,11 +87,11 @@ extension Optional: DatabaseValueConvertible where Wrapped: DatabaseValueConvert
extension Optional: StatementColumnConvertible where Wrapped: StatementColumnConvertible {
@inline(__always)
@inlinable
public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt) -> Self? {
public static func fromStatement<API>(_ sqliteStatement: SQLiteStatementBase<API>, atUncheckedIndex index: CInt) -> Self? {
if let value = Wrapped.fromStatement(sqliteStatement, atUncheckedIndex: index) {
// Valid value
return value
} else if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
} else if API.sqlite3_column_type(sqliteStatement.rawValue, index) == API.SQLITE_NULL {
// NULL
return .some(.none)
} else {
@@ -97,7 +100,7 @@ extension Optional: StatementColumnConvertible where Wrapped: StatementColumnCon
}
}
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
guard let value = Wrapped(sqliteStatement: sqliteStatement, index: index) else {
return nil
}
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
// MARK: - Value Types
@@ -17,8 +20,8 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: CInt) {
self = sqlite3_column_int64(sqliteStatement, index) != 0
public init<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
self = API.sqlite3_column_int64(sqliteStatement.rawValue, index) != 0
}
/// Returns an INTEGER database value.
@@ -99,8 +102,8 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
}
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, self ? 1 : 0)
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, self ? 1 : 0)
}
}
@@ -114,8 +117,8 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
guard let v = Int(exactly: int64) else { return nil }
self = v
}
@@ -138,8 +141,8 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { Int(exactly: $0) }
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
}
}
@@ -153,8 +156,8 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
guard let v = Int8(exactly: int64) else { return nil }
self = v
}
@@ -177,8 +180,8 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { Int8(exactly: $0) }
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
}
}
@@ -192,8 +195,8 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
guard let v = Int16(exactly: int64) else { return nil }
self = v
}
@@ -216,8 +219,8 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { Int16(exactly: $0) }
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
}
}
@@ -231,8 +234,8 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
guard let v = Int32(exactly: int64) else { return nil }
self = v
}
@@ -255,8 +258,8 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { Int32(exactly: $0) }
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
}
}
@@ -268,8 +271,8 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: CInt) {
self = sqlite3_column_int64(sqliteStatement, index)
public init<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
self = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
}
/// Returns an INTEGER database value.
@@ -298,8 +301,8 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
}
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, self)
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, self)
}
}
@@ -313,8 +316,8 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
guard let v = UInt(exactly: int64) else { return nil }
self = v
}
@@ -337,8 +340,8 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { UInt(exactly: $0) }
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
}
}
@@ -352,8 +355,8 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
guard let v = UInt8(exactly: int64) else { return nil }
self = v
}
@@ -376,8 +379,8 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { UInt8(exactly: $0) }
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
}
}
@@ -391,8 +394,8 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
guard let v = UInt16(exactly: int64) else { return nil }
self = v
}
@@ -415,8 +418,8 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { UInt16(exactly: $0) }
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
}
}
@@ -430,8 +433,8 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
guard let v = UInt32(exactly: int64) else { return nil }
self = v
}
@@ -454,8 +457,8 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { UInt32(exactly: $0) }
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
}
}
@@ -469,8 +472,8 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
guard let v = UInt64(exactly: int64) else { return nil }
self = v
}
@@ -493,8 +496,8 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { UInt64(exactly: $0) }
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
}
}
@@ -506,8 +509,8 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: CInt) {
self = sqlite3_column_double(sqliteStatement, index)
public init<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
self = API.sqlite3_column_double(sqliteStatement.rawValue, index)
}
/// Returns a REAL database value.
@@ -533,8 +536,8 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
}
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_double(sqliteStatement, index, self)
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_double(sqliteStatement.rawValue, index, self)
}
}
@@ -546,8 +549,8 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: CInt) {
self = Float(sqlite3_column_double(sqliteStatement, index))
public init<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
self = Float(API.sqlite3_column_double(sqliteStatement.rawValue, index))
}
/// Returns a REAL database value.
@@ -573,8 +576,8 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
}
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_double(sqliteStatement, index, Double(self))
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_double(sqliteStatement.rawValue, index, Double(self))
}
}
@@ -586,8 +589,8 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: CInt) {
self = String(cString: sqlite3_column_text(sqliteStatement, index)!)
public init<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
self = String(cString: API.sqlite3_column_text(sqliteStatement.rawValue, index)!)
}
/// Returns a TEXT database value.
@@ -616,8 +619,8 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
}
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_text(sqliteStatement, index, self, -1, SQLITE_TRANSIENT)
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_text(sqliteStatement.rawValue, index, self, -1, SQLITE_TRANSIENT)
}
/// Calls the given closure after binding a statement argument.
@@ -627,9 +630,9 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameter sqliteStatement: An SQLite statement.
/// - parameter index: 1-based index to statement arguments.
/// - parameter body: The closure to execute when argument is bound.
func withBinding<T>(to sqliteStatement: SQLiteStatement, at index: CInt, do body: () throws -> T) throws -> T {
func withBinding<API, T>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt, do body: () throws -> T) throws -> T {
try withCString {
let code = sqlite3_bind_text(sqliteStatement, index, $0, -1, nil /* SQLITE_STATIC */)
let code = API.sqlite3_bind_text(sqliteStatement.rawValue, index, $0, -1, nil /* SQLITE_STATIC */)
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
return try body()
}
+28 -24
View File
@@ -10,7 +10,9 @@ import Foundation
///
/// - ``DefaultTransactionClock``
/// - ``CustomTransactionClock``
public protocol TransactionClock: Sendable {
public protocol TransactionClock<API>: Sendable {
associatedtype API: SQLiteAPI
/// Returns the date of the current transaction.
///
/// This function is called whenever a transaction starts - precisely
@@ -20,31 +22,33 @@ public protocol TransactionClock: Sendable {
/// called, and the database connection is not in a transaction.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/get_autocommit.html>
func now(_ db: Database) throws -> Date
func now(_ db: DatabaseBase<API>) throws -> Date
}
extension TransactionClock where Self == DefaultTransactionClock {
/// Returns the default clock.
public static var `default`: Self { DefaultTransactionClock() }
}
#warning("TODO: expose a version with default api")
//extension TransactionClock where Self == DefaultTransactionClock {
// /// Returns the default clock.
// public static var `default`: Self { DefaultTransactionClock() }
//}
extension TransactionClock where Self == CustomTransactionClock {
/// Returns a custom clock.
///
/// The provided closure is called whenever a transaction starts - precisely
/// speaking, whenever the database connection leaves the auto-commit mode.
///
/// It is also called when the ``Database/transactionDate`` property is
/// called, and the database connection is not in a transaction.
public static func custom(_ now: @escaping @Sendable (Database) throws -> Date) -> Self {
CustomTransactionClock(now)
}
}
#warning("TODO: expose a version with default api")
//extension TransactionClock where Self == CustomTransactionClock {
// /// Returns a custom clock.
// ///
// /// The provided closure is called whenever a transaction starts - precisely
// /// speaking, whenever the database connection leaves the auto-commit mode.
// ///
// /// It is also called when the ``Database/transactionDate`` property is
// /// called, and the database connection is not in a transaction.
// public static func custom(_ now: @escaping @Sendable (Database) throws -> Date) -> Self {
// CustomTransactionClock(now)
// }
//}
/// The default transaction clock.
public struct DefaultTransactionClock: TransactionClock {
public struct DefaultTransactionClock<API: SQLiteAPI>: TransactionClock {
/// Returns the start date of the current transaction.
public func now(_ db: Database) throws -> Date {
public func now(_ db: DatabaseBase<API>) throws -> Date {
// An opportunity to fetch transaction time from the database when
// SQLite supports the feature.
Date()
@@ -52,14 +56,14 @@ public struct DefaultTransactionClock: TransactionClock {
}
/// A custom transaction clock.
public struct CustomTransactionClock: TransactionClock {
let _now: @Sendable (Database) throws -> Date
public struct CustomTransactionClock<API: SQLiteAPI>: TransactionClock {
let _now: @Sendable (DatabaseBase<API>) throws -> Date
public init(_ now: @escaping @Sendable (Database) throws -> Date) {
public init(_ now: @escaping @Sendable (DatabaseBase<API>) throws -> Date) {
self._now = now
}
public func now(_ db: Database) throws -> Date {
public func now(_ db: DatabaseBase<API>) throws -> Date {
try _now(db)
}
}
+91 -83
View File
@@ -1,13 +1,16 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
extension Database {
extension DatabaseBase {
// MARK: - Database Observation
@@ -30,8 +33,8 @@ extension Database {
/// the observer lifetime (observation lasts until observer
/// is deallocated).
public func add(
transactionObserver: some TransactionObserver,
extent: TransactionObservationExtent = .observerLifetime)
transactionObserver: some TransactionObserverBase<API>,
extent: DatabaseTransactionObservationExtent = .observerLifetime)
{
SchedulingWatchdog.preconditionValidQueue(self)
guard let observationBroker else { return }
@@ -54,7 +57,7 @@ extension Database {
/// db.remove(transactionObserver: myObserver)
/// }
/// ```
public func remove(transactionObserver: some TransactionObserver) {
public func remove(transactionObserver: some TransactionObserverBase<API>) {
SchedulingWatchdog.preconditionValidQueue(self)
guard let observationBroker else { return }
@@ -79,7 +82,7 @@ extension Database {
/// ```swift
/// /// Inserts a region in the database, and start monitoring upon
/// /// successful insertion.
/// func startMonitoring(_ db: Database, region: CLRegion) throws {
/// func startMonitoring(_ db: DatabaseBase<some SQLiteAPI>, region: CLRegion) throws {
/// // Make sure database is inside a transaction
/// try db.inSavepoint {
///
@@ -110,34 +113,9 @@ extension Database {
/// - parameter onCommit: A closure executed on transaction commit.
/// - parameter onRollback: A closure executed on transaction rollback.
public func afterNextTransaction(
onCommit: @escaping @Sendable (Database) -> Void,
onRollback: @escaping @Sendable (Database) -> Void = { _ in })
onCommit: @escaping @Sendable (DatabaseBase<API>) -> Void,
onRollback: @escaping @Sendable (DatabaseBase<API>) -> 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")
@@ -145,16 +123,42 @@ extension Database {
transactionObserver: TransactionHandler(onCommit: onCommit, onRollback: onRollback),
extent: .nextTransaction)
}
/// The extent of the observation performed by a ``TransactionObserver``.
public enum TransactionObservationExtent: Sendable {
/// Observation lasts until observer is deallocated.
case observerLifetime
/// Observation lasts until the next transaction.
case nextTransaction
/// Observation lasts until the database is closed.
case databaseLifetime
}
fileprivate class TransactionHandler<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)
}
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
@@ -167,8 +171,8 @@ extension Database {
/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
/// func databaseDidChange(with event: DatabaseEvent)
/// func databaseWillCommit() throws
/// func databaseDidCommit(_ db: Database)
/// func databaseDidRollback(_ db: Database)
/// func databaseDidCommit(_ db: DatabaseBase<some SQLiteAPI>)
/// func databaseDidRollback(_ db: DatabaseBase<some SQLiteAPI>)
/// }
///
/// First observer is added, and a transaction is started. At this point,
@@ -241,8 +245,8 @@ extension Database {
///
/// After the statement *has been executed*, the broker calls
/// observer.databaseDidCommit().
class DatabaseObservationBroker {
private unowned let database: Database
class DatabaseObservationBroker<API: SQLiteAPI> {
private unowned let database: DatabaseBase<API>
/// The savepoint stack allows us to hold database event notifications until
/// all savepoints are released. The goal is to only tell transaction
@@ -255,10 +259,10 @@ class DatabaseObservationBroker {
private var transactionCompletion = TransactionCompletion.none
/// The registered transaction observers.
private var transactionObservations: [TransactionObservation] = []
private var transactionObservations: [TransactionObservation<API>] = []
/// The observers for an individual statement execution.
private var statementObservations: [StatementObservation] = [] {
private var statementObservations: [StatementObservation<API>] = [] {
didSet {
let isEmpty = statementObservations.isEmpty
if isEmpty != oldValue.isEmpty {
@@ -272,22 +276,22 @@ class DatabaseObservationBroker {
}
}
init(_ database: Database) {
init(_ database: DatabaseBase<API>) {
self.database = database
}
// MARK: - Transaction observers
func add(transactionObserver: some TransactionObserver, extent: Database.TransactionObservationExtent) {
func add(transactionObserver: some TransactionObserverBase<API>, extent: DatabaseTransactionObservationExtent) {
transactionObservations.append(TransactionObservation(observer: transactionObserver, extent: extent))
}
func remove(transactionObserver: some TransactionObserver) {
func remove(transactionObserver: some TransactionObserverBase<API>) {
transactionObservations.removeFirst { $0.isWrapping(transactionObserver) }
}
/// Called from ``TransactionObserver/stopObservingDatabaseChangesUntilNextTransaction()``.
func disableUntilNextTransaction(transactionObserver: some TransactionObserver) {
func disableUntilNextTransaction(transactionObserver: some TransactionObserverBase<API>) {
if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver) }) {
observation.isEnabled = false
statementObservations.removeFirst { $0.transactionObservation === observation }
@@ -319,7 +323,7 @@ class DatabaseObservationBroker {
}
/// Prepares observation of changes that are about to be performed by the statement.
func statementWillExecute(_ statement: Statement) {
func statementWillExecute(_ statement: StatementBase<API>) {
if !database.isReadOnly && !transactionObservations.isEmpty {
// As statement executes, it may trigger database changes that will
// be notified to transaction observers. As a consequence, observers
@@ -395,7 +399,7 @@ class DatabaseObservationBroker {
/// May throw the user-provided cancelled commit error, if a transaction
/// observer has cancelled a transaction.
func statementDidFail(_ statement: Statement) throws {
func statementDidFail(_ statement: StatementBase<API>) throws {
// Undo statementWillExecute
statementObservations = []
SchedulingWatchdog.current!.databaseObservationBroker = nil
@@ -422,7 +426,7 @@ class DatabaseObservationBroker {
/// May throw the user-provided cancelled commit error, if the statement
/// commits an empty transaction, and a transaction observer cancels this
/// empty transaction.
func statementDidExecute(_ statement: Statement) throws {
func statementDidExecute(_ statement: StatementBase<API>) throws {
// Undo statementWillExecute
if transactionObservations.isEmpty == false {
statementObservations = []
@@ -708,7 +712,7 @@ class DatabaseObservationBroker {
func installCommitAndRollbackHooks() {
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_commit_hook(database.sqliteConnection, { brokerPointer in
API.sqlite3_commit_hook(database.sqliteConnection, { brokerPointer in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
do {
try broker.databaseWillCommit()
@@ -722,7 +726,7 @@ class DatabaseObservationBroker {
}
}, brokerPointer)
sqlite3_rollback_hook(database.sqliteConnection, { brokerPointer in
API.sqlite3_rollback_hook(database.sqliteConnection, { brokerPointer in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
switch broker.transactionCompletion {
case .cancelledCommit:
@@ -738,7 +742,7 @@ class DatabaseObservationBroker {
private func installUpdateHook() {
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_update_hook(
API.sqlite3_update_hook(
database.sqliteConnection,
{ (brokerPointer, updateKind, databaseNameCString, tableNameCString, rowID) in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
@@ -771,7 +775,7 @@ class DatabaseObservationBroker {
}
private func uninstallUpdateHook() {
sqlite3_update_hook(database.sqliteConnection, nil, nil)
API.sqlite3_update_hook(database.sqliteConnection, nil, nil)
#if SQLITE_ENABLE_PREUPDATE_HOOK
sqlite3_preupdate_hook(database.sqliteConnection, nil, nil)
#endif
@@ -797,7 +801,8 @@ class DatabaseObservationBroker {
// MARK: - TransactionObserver
public protocol TransactionObserver: AnyObject {
public protocol TransactionObserverBase<API>: AnyObject {
associatedtype API: SQLiteAPI
/// Returns whether specific kinds of database changes should be notified
/// to the observer.
@@ -861,10 +866,10 @@ public protocol TransactionObserver: AnyObject {
func databaseWillCommit() throws
/// Called when a transaction has been committed on disk.
func databaseDidCommit(_ db: Database)
func databaseDidCommit(_ db: DatabaseBase<API>)
/// Called when a transaction has been rollbacked.
func databaseDidRollback(_ db: Database)
func databaseDidRollback(_ db: DatabaseBase<API>)
#if SQLITE_ENABLE_PREUPDATE_HOOK
/// Called when the database is changed by an insert, update, or
@@ -898,7 +903,7 @@ public protocol TransactionObserver: AnyObject {
#endif
}
extension TransactionObserver {
extension TransactionObserverBase {
/// The default implementation does nothing.
public func databaseWillCommit() throws { }
@@ -960,22 +965,25 @@ extension TransactionObserver {
// MARK: - TransactionObservation
/// This class manages the observation extent of a transaction observer
final class TransactionObservation {
let extent: Database.TransactionObservationExtent
final class TransactionObservation<API: SQLiteAPI> {
let extent: DatabaseTransactionObservationExtent
/// A disabled observation is not interested in individual database changes.
/// It is still interested in transactions commits & rollbacks.
var isEnabled = true
private weak var weakObserver: (any TransactionObserver)?
private var strongObserver: (any TransactionObserver)?
private var observer: (any TransactionObserver)? { strongObserver ?? weakObserver }
private weak var weakObserver: (any TransactionObserverBase<API>)?
private var strongObserver: (any TransactionObserverBase<API>)?
private var observer: (any TransactionObserverBase<API>)? {
if let strongObserver { return strongObserver }
return weakObserver
}
fileprivate var isObserving: Bool {
observer != nil
}
init(observer: some TransactionObserver, extent: Database.TransactionObservationExtent) {
init(observer: some TransactionObserverBase<API>, extent: DatabaseTransactionObservationExtent) {
self.extent = extent
switch extent {
case .observerLifetime:
@@ -988,7 +996,7 @@ final class TransactionObservation {
}
}
func isWrapping(_ observer: some TransactionObserver) -> Bool {
func isWrapping(_ observer: some TransactionObserverBase<API>) -> Bool {
self.observer === observer
}
@@ -1017,7 +1025,7 @@ final class TransactionObservation {
try observer?.databaseWillCommit()
}
func databaseDidCommit(_ db: Database) {
func databaseDidCommit(_ db: DatabaseBase<API>) {
switch extent {
case .observerLifetime, .databaseLifetime:
observer?.databaseDidCommit(db)
@@ -1033,7 +1041,7 @@ final class TransactionObservation {
}
}
func databaseDidRollback(_ db: Database) {
func databaseDidRollback(_ db: DatabaseBase<API>) {
switch extent {
case .observerLifetime, .databaseLifetime:
observer?.databaseDidRollback(db)
@@ -1052,8 +1060,8 @@ final class TransactionObservation {
/// The observation of one particular statement, by a particular
/// transaction observer.
struct StatementObservation {
var transactionObservation: TransactionObservation
struct StatementObservation<API: SQLiteAPI> {
var transactionObservation: TransactionObservation<API>
/// A predicate that filters database events that should be notified.
///
@@ -1064,7 +1072,7 @@ struct StatementObservation {
/// ```
var tracksEvent: DatabaseEventPredicate
init(transactionObservation: TransactionObservation, trackingEvents predicate: DatabaseEventPredicate) {
init(transactionObservation: TransactionObservation<API>, trackingEvents predicate: DatabaseEventPredicate) {
self.transactionObservation = transactionObservation
self.tracksEvent = predicate
}
@@ -1494,7 +1502,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt)
-> DatabaseValue?
{
var value: SQLiteValue? = nil
var value: SQLiteValue?
guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil }
if let value {
return DatabaseValue(sqliteValue: value)
+14 -23
View File
@@ -1,12 +1,15 @@
#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
#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
/// An instance of WALSnapshot records the state of a WAL mode database for some
/// specific point in history.
@@ -16,30 +19,18 @@ import SQLite3
/// 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: Database) throws {
init(_ db: DatabaseBase<some SQLiteAPI>) throws {
var sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>?
let code = withUnsafeMutablePointer(to: &sqliteSnapshot) {
return sqlite3_snapshot_get(db.sqliteConnection, "main", $0)
}
guard code == SQLITE_OK else {
guard code == API.SQLITE_OK else {
// <https://www.sqlite.org/c3ref/snapshot_get.html>
//
// > The following must be true for sqlite3_snapshot_get() to succeed. [...]
+13 -7
View File
@@ -1,13 +1,13 @@
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
/// A long-live read-only WAL transaction.
///
/// `WALSnapshotTransaction` **takes ownership** of its reader
/// `SerializedDatabase` (TODO: make it a move-only type eventually).
final class WALSnapshotTransaction: @unchecked Sendable {
final class WALSnapshotTransactionBase<API: SQLiteAPI>: @unchecked Sendable {
// @unchecked because `databaseAccess` is protected by a mutex.
private struct DatabaseAccess {
let reader: SerializedDatabase
let reader: SerializedDatabaseBase<API>
let release: @Sendable (_ isInsideTransaction: Bool) -> Void
// MUST be called only once
@@ -15,7 +15,13 @@ final class WALSnapshotTransaction: @unchecked Sendable {
// WALSnapshotTransaction may be deinitialized in the dispatch
// queue of its reader: allow reentrancy.
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
try? db.commit()
// 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()
}
return db.isInsideTransaction
}
release(isInsideTransaction)
@@ -54,7 +60,7 @@ final class WALSnapshotTransaction: @unchecked Sendable {
/// - parameter release: A closure to call when the read-only connection
/// is no longer used.
init(
onReader reader: SerializedDatabase,
onReader reader: SerializedDatabaseBase<API>,
release: @escaping @Sendable (_ isInsideTransaction: Bool) -> Void)
throws
{
@@ -84,7 +90,7 @@ final class WALSnapshotTransaction: @unchecked Sendable {
/// Executes database operations in the snapshot transaction, and
/// returns their result after they have finished executing.
func read<T>(_ value: (Database) throws -> T) throws -> T {
func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
try databaseAccessMutex.withLock { databaseAccess in
guard let databaseAccess else {
throw DatabaseError.snapshotIsLost()
@@ -97,7 +103,7 @@ final class WALSnapshotTransaction: @unchecked Sendable {
/// Schedules database operations for execution, and
/// returns immediately.
func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
func asyncRead(_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void) {
databaseAccessMutex.withLock { databaseAccess in
guard let databaseAccess else {
value(.failure(DatabaseError.snapshotIsLost()))
@@ -29,6 +29,8 @@ Get information about schema objects such as tables, columns, indexes, foreign k
### Supporting Types
- ``DatabaseSchemaID``
- ``DatabaseObjectID``
- ``ColumnInfo``
- ``ForeignKeyInfo``
- ``IndexInfo``
@@ -96,6 +96,7 @@ do {
- ``persistentReadOnlyConnections``
- ``prepareDatabase(_:)``
- ``publicStatementArguments``
- ``schemaSource``
- ``transactionClock``
- ``TransactionClock``
@@ -106,3 +107,7 @@ do {
- ``writeQoS``
- ``targetQueue``
- ``writeTargetQueue``
### Supporting Types
- ``DatabaseSchemaSource``
@@ -128,7 +128,7 @@ For example:
```swift
extension EvenInteger: StatementColumnConvertible {
init?(sqliteStatement: SQLiteStatement, index: CInt) {
init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, 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,6 +94,7 @@ 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: Database) throws {
mutating func willInsert(_ db: DatabaseBase<some SQLiteAPI>) throws {
if creationDate == nil {
creationDate = try db.transactionDate
}
@@ -182,7 +182,7 @@ extension Player: Encodable, MutablePersistableRecord {
/// Sets both `creationDate` and `modificationDate` to the
/// transaction date, if they are not set yet.
mutating func willInsert(_ db: Database) throws {
mutating func willInsert(_ db: DatabaseBase<some SQLiteAPI>) throws {
if creationDate == nil {
creationDate = try db.transactionDate
}
@@ -311,7 +311,7 @@ You can copy it in your application, or use it as an inspiration. Not all apps h
extension Player {
/// If the player has a non-nil primary key and a matching row in
/// the database, the player is updated. Otherwise, it is inserted.
mutating func saveWithTimestamp(_ db: Database) throws {
mutating func saveWithTimestamp(_ db: DatabaseBase<some SQLiteAPI>) throws {
// Test the presence of id first, so that we don't perform an
// update that would surely throw RecordError.recordNotFound.
if id == nil {
@@ -346,7 +346,7 @@ extension TimestampedRecord {
/// `TimestampedRecord` types that customize the `willInsert`
/// persistence callback should call `initializeTimestamps` from
/// their implementation.
mutating func willInsert(_ db: Database) throws {
mutating func willInsert(_ db: DatabaseBase<some SQLiteAPI>) throws {
try initializeTimestamps(db)
}
@@ -356,7 +356,7 @@ extension TimestampedRecord {
/// It is called automatically before insertion, if your type does not
/// customize the `willInsert` persistence callback. If you customize
/// this callback, call `initializeTimestamps` from your implementation.
mutating func initializeTimestamps(_ db: Database) throws {
mutating func initializeTimestamps(_ db: DatabaseBase<some SQLiteAPI>) throws {
if creationDate == nil {
creationDate = try db.transactionDate
}
@@ -370,7 +370,7 @@ extension TimestampedRecord {
///
/// - parameter modificationDate: The modification date. If nil, the
/// transaction date is used.
mutating func updateWithTimestamp(_ db: Database, modificationDate: Date? = nil) throws {
mutating func updateWithTimestamp(_ db: DatabaseBase<some SQLiteAPI>, modificationDate: Date? = nil) throws {
self.modificationDate = try modificationDate ?? db.transactionDate
try update(db)
}
@@ -403,7 +403,7 @@ extension TimestampedRecord {
/// - returns: Whether the record was changed and updated.
@discardableResult
mutating func updateChangesWithTimestamp(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
modificationDate: Date? = nil,
modify: (inout Self) -> Void)
throws -> Bool
@@ -431,7 +431,7 @@ extension TimestampedRecord {
///
/// - parameter modificationDate: The modification date. If nil, the
/// transaction date is used.
mutating func touch(_ db: Database, modificationDate: Date? = nil) throws {
mutating func touch(_ db: DatabaseBase<some SQLiteAPI>, 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: Database, columns: Set<String>) throws {
func willUpdate(_ db: DatabaseBase<some SQLiteAPI>, 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: Database) throws -> AppConfiguration {
static func find(_ db: DatabaseBase<some SQLiteAPI>) throws -> AppConfiguration {
try fetchOne(db) ?? .default
}
}
@@ -233,7 +233,7 @@ extension AppConfiguration {
// Database Access
extension AppConfiguration: FetchableRecord, PersistableRecord {
// Customize the default PersistableRecord behavior
func willUpdate(_ db: Database, columns: Set<String>) throws {
func willUpdate(_ db: DatabaseBase<some SQLiteAPI>, 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: Database) throws -> AppConfiguration {
static func find(_ db: DatabaseBase<some SQLiteAPI>) throws -> AppConfiguration {
try fetchOne(db) ?? .default
}
}
+7 -1
View File
@@ -55,7 +55,7 @@ let count = try await writer.read { db in
}
// Shorthand notation:
// ⚠️ Converting non-sendable function value to '@Sendable (Database)
// ⚠️ Converting non-sendable function value to '@Sendable (DatabaseBase<some SQLiteAPI>)
// throws -> Int' may introduce data races.
let count = try await writer.read(Player.fetchCount)
```
@@ -229,5 +229,11 @@ 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: Database) throws {
func myCriticalMethod(_ db: DatabaseBase<some SQLiteAPI>) throws {
precondition(db.isInsideTransaction, "This method requires a transaction")
try ...
}
@@ -169,7 +169,7 @@ func myCriticalMethod(_ db: Database) throws {
Yet, there is a better option than checking for transactions. Critical database sections should use savepoints, described below:
```swift
func myCriticalMethod(_ db: Database) throws {
func myCriticalMethod(_ db: DatabaseBase<some SQLiteAPI>) throws {
try db.inSavepoint {
// Here the database is guaranteed to be inside a transaction.
try ...
+383
View File
@@ -0,0 +1,383 @@
# 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 Database {
extension DatabaseBase {
/// Prints the results of all statements in the provided SQL.
///
/// For example:
@@ -183,7 +183,7 @@ extension Database {
// MARK: -
extension Database {
extension DatabaseBase {
func _dumpStatements(
_ statements: some Cursor<Statement>,
format: some DumpFormat,
@@ -317,14 +317,14 @@ extension Database {
}
private func ignoresObject(named name: String) throws -> Bool {
if Database.isSQLiteInternalTable(name) { return true }
if Database.isGRDBInternalTable(name) { return true }
if Self.isSQLiteInternalTable(name) { return true }
if Self.isGRDBInternalTable(name) { return true }
if try isShadowTable(name) { return true }
return false
}
private func isShadowTable(_ tableName: String) throws -> Bool {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
// 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 DatabaseReader {
extension DatabaseReaderBase {
/// Prints the results of all statements in the provided SQL.
///
/// For example:
+8 -6
View File
@@ -33,26 +33,28 @@
/// - ``writeRow(_:statement:to:)``
/// - ``finalize(_:statement:to:)``
public protocol DumpFormat {
#warning("TODO: incompatible with GRDB 7")
/// Writes a row from the given statement.
///
/// - Parameters:
/// - db: A connection to the database
/// - statement: The iterated statement
/// - stream: A stream for text output.
mutating func writeRow(
_ db: Database,
statement: Statement,
mutating func writeRow<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream) throws
#warning("TODO: incompatible with GRDB 7")
/// All rows from the statement have been printed.
///
/// - Parameters:
/// - db: A connection to the database
/// - statement: The statement that was iterated.
/// - stream: A stream for text output.
mutating func finalize(
_ db: Database,
statement: Statement,
mutating func finalize<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
}
+18 -15
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -58,9 +61,9 @@ public struct DebugDumpFormat: Sendable {
}
extension DebugDumpFormat: DumpFormat {
public mutating func writeRow(
_ db: Database,
statement: Statement,
public mutating func writeRow<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
{
if firstRow {
@@ -88,15 +91,15 @@ extension DebugDumpFormat: DumpFormat {
stream.write("\n")
}
public mutating func finalize(
_ db: Database,
statement: Statement,
public mutating func finalize<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
{
firstRow = true
}
private func formattedValue(_ db: Database, in sqliteStatement: SQLiteStatement, at index: CInt) -> String {
private func formattedValue(_ db: DatabaseBase<some SQLiteAPI>, in sqliteStatement: SQLiteStatement, at index: CInt) -> String {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_NULL:
return nullValue
+18 -15
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -77,9 +80,9 @@ public struct JSONDumpFormat: Sendable {
}
extension JSONDumpFormat: DumpFormat {
public mutating func writeRow(
_ db: Database,
statement: Statement,
public mutating func writeRow<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
throws {
if firstRow {
@@ -124,9 +127,9 @@ extension JSONDumpFormat: DumpFormat {
stream.write("}")
}
public mutating func finalize(
_ db: Database,
statement: Statement,
public mutating func finalize<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
{
if firstRow {
@@ -142,7 +145,7 @@ extension JSONDumpFormat: DumpFormat {
firstRow = true
}
private func formattedValue(_ db: Database, in sqliteStatement: SQLiteStatement, at index: CInt) throws -> String {
private func formattedValue(_ db: DatabaseBase<some SQLiteAPI>, in sqliteStatement: SQLiteStatement, at index: CInt) throws -> String {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_NULL:
return "null"
+18 -15
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -40,9 +43,9 @@ public struct LineDumpFormat: Sendable {
}
extension LineDumpFormat: DumpFormat {
public mutating func writeRow(
_ db: Database,
statement: Statement,
public mutating func writeRow<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
{
var lines: [(column: String, value: String)] = []
@@ -73,9 +76,9 @@ extension LineDumpFormat: DumpFormat {
}
}
public mutating func finalize(
_ db: Database,
statement: Statement,
public mutating func finalize<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
{
if firstRow == false {
@@ -85,7 +88,7 @@ extension LineDumpFormat: DumpFormat {
}
func formattedValue(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
in sqliteStatement: SQLiteStatement,
at index: CInt)
-> String
+18 -15
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -55,9 +58,9 @@ public struct ListDumpFormat: Sendable {
}
extension ListDumpFormat: DumpFormat {
public mutating func writeRow(
_ db: Database,
statement: Statement,
public mutating func writeRow<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
{
if firstRow {
@@ -85,16 +88,16 @@ extension ListDumpFormat: DumpFormat {
stream.write("\n")
}
public mutating func finalize(
_ db: Database,
statement: Statement,
public mutating func finalize<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
{
firstRow = true
}
func formattedValue(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
in sqliteStatement: SQLiteStatement,
at index: CInt)
-> String
+17 -14
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
/// A format that prints one line per database row, formatting values
/// as SQL literals.
@@ -44,9 +47,9 @@ public struct QuoteDumpFormat: Sendable {
}
extension QuoteDumpFormat: DumpFormat {
public mutating func writeRow(
_ db: Database,
statement: Statement,
public mutating func writeRow<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
{
if firstRow {
@@ -78,9 +81,9 @@ extension QuoteDumpFormat: DumpFormat {
stream.write("\n")
}
public mutating func finalize(
_ db: Database,
statement: Statement,
public mutating func finalize<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
{
firstRow = true
+9 -7
View File
@@ -40,11 +40,11 @@ public struct FTS3 {
/// the `remove_diacritics=1` tokenizer argument.
case removeLegacy
#if GRDBCUSTOMSQLITE
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Remove diacritics from Latin script characters. This option matches
/// the `remove_diacritics=2` tokenizer argument.
case remove
#elseif !GRDBCIPHER
#else
/// 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,6 +66,7 @@ public struct FTS3 {
/// See ``Database/create(virtualTable:options:using:_:)``
public init() { }
#warning("TODO: expose a version with default api")
/// Returns an array of tokens found in the string argument.
///
/// For example:
@@ -94,12 +95,13 @@ public struct FTS3 {
/// - <https://www.sqlite.org/fts3.html#querying_tokenizers>
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func tokenize(
public static func tokenize<API: SQLiteAPI>(
_ string: String,
withTokenizer tokenizer: FTS3TokenizerDescriptor = .simple)
withTokenizer tokenizer: FTS3TokenizerDescriptor = .simple,
api: API.Type)
throws -> [String]
{
try DatabaseQueue().inDatabase { db in
try DatabaseQueueBase<API>().inDatabase { db in
var tokenizerChunks: [String] = []
tokenizerChunks.append(tokenizer.name)
for option in tokenizer.arguments {
@@ -121,7 +123,7 @@ extension FTS3: VirtualTableModule {
FTS3TableDefinition()
}
public func moduleArguments(for definition: FTS3TableDefinition, in db: Database) -> [String] {
public func moduleArguments(for definition: FTS3TableDefinition, in db: DatabaseBase<some SQLiteAPI>) -> [String] {
var arguments = definition.columns
if let tokenizer = definition.tokenizer {
if tokenizer.arguments.isEmpty {
@@ -136,7 +138,7 @@ extension FTS3: VirtualTableModule {
return arguments
}
public func database(_ db: Database, didCreate tableName: String, using definition: FTS3TableDefinition) { }
public func database(_ db: DatabaseBase<some SQLiteAPI>, didCreate tableName: String, using definition: FTS3TableDefinition) { }
}
/// A `FTS3TableDefinition` lets you define the components of an FTS3
+34 -14
View File
@@ -22,6 +22,7 @@ public struct FTS3Pattern: Sendable {
/// It is guaranteed to be a valid FTS3/4 pattern.
public let rawPattern: String
#warning("TODO: expose a version with default api")
/// Creates a pattern from a raw pattern string.
///
/// The pattern syntax is documented at <https://www.sqlite.org/fts3.html#full_text_index_queries>
@@ -37,14 +38,17 @@ public struct FTS3Pattern: Sendable {
/// ```
///
/// - throws: A ``DatabaseError`` if the pattern has an invalid syntax.
public init(rawPattern: String) throws {
public init<API: SQLiteAPI>(
rawPattern: String,
api: API.Type
) throws {
// Correctness above all: use SQLite to validate the pattern.
//
// Invalid patterns have SQLite return an error on the first
// call to sqlite3_step() on a statement that matches against
// that pattern.
do {
try DatabaseQueue().inDatabase { db in
try DatabaseQueueBase<API>().inDatabase { db in
try db.execute(literal: """
CREATE VIRTUAL TABLE documents USING fts3();
SELECT * FROM documents WHERE content MATCH \(rawPattern);
@@ -59,6 +63,7 @@ public struct FTS3Pattern: Sendable {
self.rawPattern = rawPattern
}
#warning("TODO: expose a version with default api")
/// Creates a pattern that matches any token found in the input string.
///
/// The result is nil if no pattern could be built.
@@ -71,13 +76,17 @@ public struct FTS3Pattern: Sendable {
/// ```
///
/// - parameter string: The string to turn into an FTS3 pattern.
public init?(matchingAnyTokenIn string: String) {
guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple),
public init?<API: SQLiteAPI>(
matchingAnyTokenIn string: String,
api: API.Type
) {
guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple, api: api),
!tokens.isEmpty
else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " OR "))
try? self.init(rawPattern: tokens.joined(separator: " OR "), api: api)
}
#warning("TODO: expose a version with default api")
/// Creates a pattern that matches all tokens found in the input string.
///
/// The result is nil if no pattern could be built.
@@ -90,13 +99,17 @@ public struct FTS3Pattern: Sendable {
/// ```
///
/// - parameter string: The string to turn into an FTS3 pattern.
public init?(matchingAllTokensIn string: String) {
guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple),
public init?<API: SQLiteAPI>(
matchingAllTokensIn string: String,
api: API.Type
) {
guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple, api: api),
!tokens.isEmpty
else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " "))
try? self.init(rawPattern: tokens.joined(separator: " "), api: api)
}
#warning("TODO: expose a version with default api")
/// Creates a pattern that matches all token prefixes found in the input
/// string.
///
@@ -110,13 +123,17 @@ public struct FTS3Pattern: Sendable {
/// ```
///
/// - parameter string: The string to turn into an FTS3 pattern.
public init?(matchingAllPrefixesIn string: String) {
guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple),
public init?<API: SQLiteAPI>(
matchingAllPrefixesIn string: String,
api: API.Type
) {
guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple, api: api),
!tokens.isEmpty
else { return nil }
try? self.init(rawPattern: tokens.map { "\($0)*" }.joined(separator: " "))
try? self.init(rawPattern: tokens.map { "\($0)*" }.joined(separator: " "), api: api)
}
#warning("TODO: expose a version with default api")
/// Creates a pattern that matches a contiguous string.
///
/// The result is nil if no pattern could be built.
@@ -129,11 +146,14 @@ public struct FTS3Pattern: Sendable {
/// ```
///
/// - parameter string: The string to turn into an FTS3 pattern.
public init?(matchingPhrase string: String) {
guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple),
public init?<API: SQLiteAPI>(
matchingPhrase string: String,
api: API.Type
) {
guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple, api: api),
!tokens.isEmpty
else { return nil }
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"", api: api)
}
}
+2 -2
View File
@@ -95,10 +95,10 @@ public struct FTS3TokenizerDescriptor: Sendable {
break
case .keep:
arguments.append("remove_diacritics=0")
#if GRDBCUSTOMSQLITE
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
case .remove:
arguments.append("remove_diacritics=2")
#elseif !GRDBCIPHER
#else
case .remove:
arguments.append("remove_diacritics=2")
#endif
+6 -3
View File
@@ -42,7 +42,10 @@ extension FTS4: VirtualTableModule {
FTS4TableDefinition(configuration: configuration)
}
public func moduleArguments(for definition: FTS4TableDefinition, in db: Database) -> [String] {
public func moduleArguments(
for definition: FTS4TableDefinition,
in db: DatabaseBase<some SQLiteAPI>
) -> [String] {
var arguments: [String] = []
for column in definition.columns {
@@ -95,7 +98,7 @@ extension FTS4: VirtualTableModule {
return arguments
}
public func database(_ db: Database, didCreate tableName: String, using definition: FTS4TableDefinition) throws {
public func database(_ db: DatabaseBase<some SQLiteAPI>, didCreate tableName: String, using definition: FTS4TableDefinition) throws {
switch definition.contentMode {
case .raw:
break
@@ -397,7 +400,7 @@ public final class FTS4ColumnDefinition {
@available(*, unavailable)
extension FTS4ColumnDefinition: Sendable { }
extension Database {
extension DatabaseBase {
/// Deletes the synchronization triggers for a synchronized FTS4 table.
///
/// See ``FTS4TableDefinition/synchronize(withTable:)``.
+22 -16
View File
@@ -1,12 +1,15 @@
#if SQLITE_ENABLE_FTS5
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -60,12 +63,12 @@ public struct FTS5 {
/// Remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=1" tokenizer argument.
case removeLegacy
#if GRDBCUSTOMSQLITE
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=2" tokenizer argument,
/// available from SQLite 3.27.0
case remove
#elseif !GRDBCIPHER
#else
/// Remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=2" tokenizer argument,
/// available from SQLite 3.27.0
@@ -116,9 +119,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: Database) -> UnsafePointer<fts5_api> {
var statement: SQLiteStatement? = nil
var api: UnsafePointer<fts5_api>? = nil
public static func api(_ db: DatabaseBase<some SQLiteAPI>) -> UnsafePointer<fts5_api> {
var statement: SQLiteStatement?
var api: UnsafePointer<fts5_api>?
let type: StaticString = "fts5_api_ptr"
let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil)
@@ -149,7 +152,10 @@ extension FTS5: VirtualTableModule {
}
/// Don't use this method.
public func moduleArguments(for definition: FTS5TableDefinition, in db: Database) throws -> [String] {
public func moduleArguments(
for definition: FTS5TableDefinition,
in db: DatabaseBase<some SQLiteAPI>
) throws -> [String] {
var arguments: [String] = []
if definition.columns.isEmpty {
@@ -220,7 +226,7 @@ extension FTS5: VirtualTableModule {
/// Reserved; part of the VirtualTableModule protocol.
///
/// See Database.create(virtualTable:options:using:_:)
public func database(_ db: Database, didCreate tableName: String, using definition: FTS5TableDefinition) throws {
public func database(_ db: DatabaseBase<some SQLiteAPI>, didCreate tableName: String, using definition: FTS5TableDefinition) throws {
switch definition.contentMode {
case .raw:
break
@@ -528,7 +534,7 @@ extension Column {
public static let rank = Column("rank")
}
extension Database {
extension DatabaseBase {
/// Deletes the synchronization triggers for a synchronized FTS5 table.
public func dropFTS5SynchronizationTriggers(forTable tableName: String) throws {
try execute(sql: """
+14 -11
View File
@@ -1,12 +1,15 @@
#if SQLITE_ENABLE_FTS5
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
/// A type that implements a custom tokenizer for the ``FTS5`` full-text engine.
///
@@ -31,7 +34,7 @@ public protocol FTS5CustomTokenizer: FTS5Tokenizer {
///
/// - parameter db: A Database connection
/// - parameter arguments: An array of string arguments
init(db: Database, arguments: [String]) throws
init(db: DatabaseBase<some SQLiteAPI>, arguments: [String]) throws
}
extension FTS5CustomTokenizer {
@@ -49,12 +52,12 @@ extension FTS5CustomTokenizer {
}
}
extension Database {
extension DatabaseBase {
// MARK: - FTS5
private class FTS5TokenizerConstructor {
let db: Database
let db: DatabaseBase<some SQLiteAPI>
let constructor: (Database, [String], UnsafeMutablePointer<OpaquePointer?>?) -> CInt
init(
+1 -1
View File
@@ -173,7 +173,7 @@ public struct FTS5Pattern: Sendable {
}
}
extension Database {
extension DatabaseBase {
// MARK: - FTS5
+13 -10
View File
@@ -1,12 +1,15 @@
#if SQLITE_ENABLE_FTS5
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -191,7 +194,7 @@ extension FTS5Tokenizer {
}
}
extension Database {
extension DatabaseBase {
// MARK: - FTS5
@@ -208,7 +211,7 @@ extension Database {
self.xTokenizer = xTokenizer
var tokenizerPointer: OpaquePointer? = nil
var tokenizerPointer: OpaquePointer?
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
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
case .remove:
components.append(contentsOf: ["remove_diacritics", "2"])
#elseif !GRDBCIPHER
#else
case .remove:
components.append(contentsOf: ["remove_diacritics", "2"])
#endif
+11 -8
View File
@@ -1,12 +1,15 @@
#if SQLITE_ENABLE_FTS5
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
+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 (Database) throws -> T) -> DatabaseFuture<T> { preconditionFailure() }
public func concurrentRead<T>(_ value: @escaping (DatabaseBase<some SQLiteAPI>) throws -> T) -> DatabaseFuture<T> { preconditionFailure() }
}
// swiftlint:enable all
+1 -1
View File
@@ -154,7 +154,7 @@ extension SQLSpecificExpressible {
}
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
extension SQLJSONExpressible {
/// The `->>` SQL operator.
///
+4 -4
View File
@@ -1,7 +1,7 @@
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
// MARK: - JSON
extension Database {
extension DatabaseBase {
/// Validates and minifies a JSON string, with the `JSON` SQL function.
///
/// For example:
@@ -453,7 +453,7 @@ extension Database {
// MARK: - JSONB
extension Database {
extension DatabaseBase {
public struct JSONValidationOptions: OptionSet, Sendable {
public let rawValue: Int
@@ -791,7 +791,7 @@ extension Database {
#else
// MARK: - JSON
extension Database {
extension DatabaseBase {
/// Validates and minifies a JSON string, with the `JSON` SQL function.
///
/// For example:
+166 -24
View File
@@ -18,6 +18,7 @@ import Foundation
/// ### Registering Migrations
///
/// - ``registerMigration(_:foreignKeyChecks:migrate:)``
/// - ``registerMigration(_:foreignKeyChecks:merging:migrate:)``
/// - ``ForeignKeyChecks``
///
/// ### Configuring a DatabaseMigrator
@@ -161,9 +162,8 @@ public struct DatabaseMigrator: Sendable {
/// Registers a migration.
///
/// 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.
/// The registered migration is appended to the list of migrations. It
/// will execute after previously registered migrations.
///
/// For example:
///
@@ -213,7 +213,108 @@ public struct DatabaseMigrator: Sendable {
public mutating func registerMigration(
_ identifier: String,
foreignKeyChecks: ForeignKeyChecks = .deferred,
migrate: @escaping @Sendable (Database) throws -> Void)
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)
{
let migrationChecks: Migration.ForeignKeyChecks
switch foreignKeyChecks {
@@ -226,7 +327,18 @@ public struct DatabaseMigrator: Sendable {
case .immediate:
migrationChecks = .immediate
}
registerMigration(Migration(identifier: identifier, foreignKeyChecks: migrationChecks, migrate: migrate))
// 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))
}
// MARK: - Applying Migrations
@@ -270,7 +382,7 @@ public struct DatabaseMigrator: Sendable {
/// from succeeding.
public func asyncMigrate(
_ writer: any DatabaseWriter,
completion: @escaping @Sendable (Result<Database, Error>) -> Void)
completion: @escaping @Sendable (Result<DatabaseBase<some SQLiteAPI>, Error>) -> Void)
{
writer.asyncBarrierWriteWithoutTransaction { dbResult in
do {
@@ -312,7 +424,7 @@ public struct DatabaseMigrator: Sendable {
/// try migrator.migrate(dbQueue)
/// ```
///
public func hasSchemaChanges(_ db: Database) throws -> Bool {
public func hasSchemaChanges(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool {
let appliedIdentifiers = try appliedIdentifiers(db)
let knownIdentifiers = Set(_migrations.map { $0.identifier })
if !appliedIdentifiers.isSubset(of: knownIdentifiers) {
@@ -388,7 +500,7 @@ public struct DatabaseMigrator: Sendable {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func appliedMigrations(_ db: Database) throws -> [String] {
public func appliedMigrations(_ db: DatabaseBase<some SQLiteAPI>) throws -> [String] {
let appliedIdentifiers = try self.appliedIdentifiers(db)
return _migrations.map { $0.identifier }.filter { appliedIdentifiers.contains($0) }
}
@@ -397,7 +509,7 @@ public struct DatabaseMigrator: Sendable {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func appliedIdentifiers(_ db: Database) throws -> Set<String> {
public func appliedIdentifiers(_ db: DatabaseBase<some SQLiteAPI>) throws -> Set<String> {
do {
return try String.fetchSet(db, sql: "SELECT identifier FROM grdb_migrations")
} catch {
@@ -417,7 +529,7 @@ public struct DatabaseMigrator: Sendable {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func completedMigrations(_ db: Database) throws -> [String] {
public func completedMigrations(_ db: DatabaseBase<some SQLiteAPI>) throws -> [String] {
let appliedIdentifiers = try appliedMigrations(db)
let knownIdentifiers = _migrations.map(\.identifier)
return zip(appliedIdentifiers, knownIdentifiers)
@@ -430,7 +542,7 @@ public struct DatabaseMigrator: Sendable {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func hasCompletedMigrations(_ db: Database) throws -> Bool {
public func hasCompletedMigrations(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool {
try completedMigrations(db).last == _migrations.last?.identifier
}
@@ -442,7 +554,7 @@ public struct DatabaseMigrator: Sendable {
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func hasBeenSuperseded(_ db: Database) throws -> Bool {
public func hasBeenSuperseded(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool {
let appliedIdentifiers = try self.appliedIdentifiers(db)
let knownIdentifiers = _migrations.map(\.identifier)
return appliedIdentifiers.contains { !knownIdentifiers.contains($0) }
@@ -450,6 +562,16 @@ 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),
@@ -457,8 +579,8 @@ public struct DatabaseMigrator: Sendable {
_migrations.append(migration)
}
/// Returns unapplied migration identifier,
private func unappliedMigrations(upTo targetIdentifier: String, appliedIdentifiers: [String]) -> [Migration] {
/// Returns unapplied migration executions
private func unappliedExecutions(upTo targetIdentifier: String, appliedIdentifiers: Set<String>) -> [Execution] {
var expectedMigrations: [Migration] = []
for migration in _migrations {
expectedMigrations.append(migration)
@@ -472,36 +594,56 @@ public struct DatabaseMigrator: Sendable {
expectedMigrations.last?.identifier == targetIdentifier,
"undefined migration: \(String(reflecting: targetIdentifier))")
return expectedMigrations.filter { !appliedIdentifiers.contains($0.identifier) }
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))
}
}
}
private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws {
private func runMigrations(_ db: DatabaseBase<some SQLiteAPI>, 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 lastAppliedIdentifier = appliedIdentifiers.last,
let lastAppliedIndex = _migrations.firstIndex(where: { $0.identifier == lastAppliedIdentifier }),
let lastAppliedMigration = appliedMigrations.last,
let lastAppliedIndex = _migrations.firstIndex(where: { $0.identifier == lastAppliedMigration }),
targetIndex < lastAppliedIndex
{
fatalError("database is already migrated beyond migration \(String(reflecting: targetIdentifier))")
}
let unappliedMigrations = self.unappliedMigrations(
let appliedIdentifiers = try self.appliedIdentifiers(db) // All ids, even unknown ones
let unappliedExecutions = self.unappliedExecutions(
upTo: targetIdentifier,
appliedIdentifiers: appliedIdentifiers)
if unappliedMigrations.isEmpty {
if unappliedExecutions.isEmpty {
return
}
for migration in unappliedMigrations {
try migration.run(db)
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)
}
}
}
private func migrate(_ db: Database, upTo targetIdentifier: String) throws {
private func migrate(_ db: DatabaseBase<some SQLiteAPI>, upTo targetIdentifier: String) throws {
if eraseDatabaseOnSchemaChange {
var needsErase = false
try db.inTransaction(.deferred) {
+54 -25
View File
@@ -6,40 +6,68 @@ struct Migration: Sendable {
case disabled
}
let identifier: String
var foreignKeyChecks: ForeignKeyChecks
let migrate: @Sendable (Database) throws -> Void
typealias Migrate = @Sendable (_ db: DatabaseBase<some SQLiteAPI>, _ mergedIdentifiers: Set<String>) throws -> Void
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)
let identifier: String
let mergedIdentifiers: Set<String>
var foreignKeyChecks: ForeignKeyChecks
// Private so that the guarantees of `run(_:)` are enforced.
private let migrate: Migrate
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)
}
} else {
try runWithImmediateForeignKeysChecks(db)
}
}
private func runWithImmediateForeignKeysChecks(_ db: Database) throws {
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 {
try db.inTransaction(.immediate) {
try migrate(db)
try insertAppliedIdentifier(db)
try migrate(db, mergedIdentifiers)
try updateAppliedIdentifier(db)
return .commit
}
}
private func runWithDisabledForeignKeysChecks(_ db: Database) throws {
private func runWithDisabledForeignKeysChecks(_ db: DatabaseBase<some SQLiteAPI>, mergedIdentifiers: Set<String>) throws {
try db.execute(sql: "PRAGMA foreign_keys = OFF")
try throwingFirstError(
execute: {
try db.inTransaction(.immediate) {
try migrate(db)
try insertAppliedIdentifier(db)
try migrate(db, mergedIdentifiers)
try updateAppliedIdentifier(db)
return .commit
}
},
@@ -48,7 +76,7 @@ struct Migration: Sendable {
})
}
private func runWithDeferredForeignKeysChecks(_ db: Database) throws {
private func runWithDeferredForeignKeysChecks(_ db: DatabaseBase<some SQLiteAPI>, mergedIdentifiers: Set<String>) throws {
// Support for database alterations described at
// https://www.sqlite.org/lang_altertable.html#otheralter
//
@@ -60,8 +88,8 @@ struct Migration: Sendable {
execute: {
// > 2. Start a transaction.
try db.inTransaction(.immediate) {
try migrate(db)
try insertAppliedIdentifier(db)
try migrate(db, mergedIdentifiers)
try updateAppliedIdentifier(db)
// > 10. If foreign key constraints were originally enabled
// > then run PRAGMA foreign_key_check to verify that the
@@ -80,7 +108,8 @@ struct Migration: Sendable {
})
}
private func insertAppliedIdentifier(_ db: Database) throws {
try db.execute(sql: "INSERT INTO grdb_migrations (identifier) VALUES (?)", arguments: [identifier])
private func updateAppliedIdentifier(_ db: DatabaseBase<some SQLiteAPI>) throws {
try deleteMergedIdentifiers(db)
try db.execute(literal: "INSERT INTO grdb_migrations (identifier) VALUES (\(identifier))")
}
}
@@ -173,8 +173,10 @@ extension Association {
// SelectionRequest conformance
extension Association {
public func selectWhenConnected(
_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]
#warning("TODO: expose a version with default api")
public func selectWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ selection: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLSelectable]
) -> Self {
withDestinationRelation { relation in
relation = relation.selectWhenConnected { db in
@@ -183,8 +185,10 @@ extension Association {
}
}
public func annotatedWhenConnected(
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]
#warning("TODO: expose a version with default api")
public func annotatedWhenConnected<API: SQLiteAPI>(
api: API.Type,
with selection: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLSelectable]
) -> Self {
withDestinationRelation { relation in
relation = relation.annotatedWhenConnected { db in
@@ -196,8 +200,10 @@ extension Association {
// FilteredRequest conformance
extension Association {
public func filterWhenConnected(
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible
#warning("TODO: expose a version with default api")
public func filterWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ predicate: @escaping @Sendable (DatabaseBase<API>) throws -> any SQLExpressible
) -> Self {
withDestinationRelation { relation in
relation = relation.filterWhenConnected { db in
@@ -209,8 +215,10 @@ extension Association {
// OrderedRequest conformance
extension Association {
public func orderWhenConnected(
_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm]
#warning("TODO: expose a version with default api")
public func orderWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ orderings: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLOrderingTerm]
) -> Self {
withDestinationRelation { relation in
relation = relation.orderWhenConnected { db in
@@ -247,8 +255,10 @@ extension Association {
// AggregatingRequest conformance
extension Association {
public func groupWhenConnected(
_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible]
#warning("TODO: expose a version with default api")
public func groupWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ expressions: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLExpressible]
) -> Self {
withDestinationRelation { relation in
relation = relation.groupWhenConnected { db in
@@ -257,8 +267,10 @@ extension Association {
}
}
public func havingWhenConnected(
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible
#warning("TODO: expose a version with default api")
public func havingWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ predicate: @escaping @Sendable (DatabaseBase<API>) 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? = nil
var key: String?
/// 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: Database.StorageClass)
as storageClass: DatabaseStorageClass)
-> AssociationAggregate<RowDecoder>
{
aggregate
@@ -333,7 +333,7 @@ struct SQLCTE {
var isRecursive: Bool
/// The number of columns in the common table expression.
func columnCount(_ db: Database) throws -> Int {
func columnCount(_ db: DatabaseBase<some SQLiteAPI>) 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: Database) throws -> Int {
public func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
try relation.fetchCount(db)
}
public func makePreparedRequest(
_ db: Database,
public func makePreparedRequest<API>(
_ db: DatabaseBase<API>,
forSingleResult singleResult: Bool = false)
throws -> PreparedRequest
throws -> PreparedRequestBase<API>
{
let generator = SQLQueryGenerator(relation: relation, forSingleResult: singleResult)
var preparedRequest = try generator.makePreparedRequest(db)
@@ -136,8 +136,10 @@ extension QueryInterfaceRequest: FetchRequest {
// MARK: - Request Derivation
extension QueryInterfaceRequest: SelectionRequest {
public func selectWhenConnected(
_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
#warning("TODO: expose a version with default api")
public func selectWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ selection: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLSelectable])
-> Self
{
with {
@@ -362,17 +364,21 @@ extension QueryInterfaceRequest: SelectionRequest {
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
where RowDecoder: Identifiable
{
selectWhenConnected { db in
let primaryKey = try db.primaryKey(self.databaseTableName)
let databaseTableName = self.databaseTableName
return selectWhenConnected { db in
let primaryKey = try db.primaryKey(databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"selectID requires a single-column primary key in the table \(self.databaseTableName)")
"selectID requires a single-column primary key in the table \(databaseTableName)")
return [Column(primaryKey.columns[0])]
}.asRequest(of: RowDecoder.ID.self)
}
public func annotatedWhenConnected(
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
#warning("TODO: expose a version with default api")
public func annotatedWhenConnected<API: SQLiteAPI>(
api: API.Type,
with selection: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLSelectable])
-> Self
{
with {
@@ -384,8 +390,10 @@ extension QueryInterfaceRequest: SelectionRequest {
}
extension QueryInterfaceRequest: FilteredRequest {
public func filterWhenConnected(
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible)
#warning("TODO: expose a version with default api")
public func filterWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ predicate: @escaping @Sendable (DatabaseBase<API>) throws -> any SQLExpressible)
-> Self
{
with {
@@ -397,8 +405,10 @@ extension QueryInterfaceRequest: FilteredRequest {
}
extension QueryInterfaceRequest: OrderedRequest {
public func orderWhenConnected(
_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm])
#warning("TODO: expose a version with default api")
public func orderWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ orderings: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLOrderingTerm])
-> Self
{
with {
@@ -465,8 +475,10 @@ extension QueryInterfaceRequest: OrderedRequest {
}
extension QueryInterfaceRequest: AggregatingRequest {
public func groupWhenConnected(
_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible])
#warning("TODO: expose a version with default api")
public func groupWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ expressions: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLExpressible])
-> Self
{
with {
@@ -476,8 +488,10 @@ extension QueryInterfaceRequest: AggregatingRequest {
}
}
public func havingWhenConnected(
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible)
#warning("TODO: expose a version with default api")
public func havingWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ predicate: @escaping @Sendable (DatabaseBase<API>) throws -> any SQLExpressible)
-> Self
{
with {
@@ -617,7 +631,7 @@ extension QueryInterfaceRequest {
/// ```
///
/// - parameter db: A database connection.
public func isEmpty(_ db: Database) throws -> Bool {
public func isEmpty(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool {
try !SQLRequest("SELECT \(exists())").fetchOne(db)!
}
}
@@ -631,17 +645,20 @@ extension QueryInterfaceRequest {
/// - returns: The number of deleted rows
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@discardableResult
public func deleteAll(_ db: Database) throws -> Int {
public func deleteAll(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
let statement = try SQLQueryGenerator(relation: relation).makeDeleteStatement(db)
try statement.execute()
return db.changesCount
var changesCount = 0
try db.countChanges(&changesCount, forTable: relation.source.tableName) {
try statement.execute()
}
return changesCount
}
}
// MARK: - Batch Delete and Fetch
extension QueryInterfaceRequest {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Returns a `DELETE RETURNING` prepared statement.
///
/// For example:
@@ -663,11 +680,10 @@ extension QueryInterfaceRequest {
/// - returns: A prepared statement.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: `selection` is not empty.
public func deleteAndFetchStatement(
_ db: Database,
selection: [any SQLSelectable])
throws -> Statement
{
public func deleteAndFetchStatement<API>(
_ db: DatabaseBase<API>,
selection: [any SQLSelectable]
) throws -> StatementBase<API> {
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection)
}
@@ -701,7 +717,7 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The result of `select` is not empty.
public func deleteAndFetchStatement(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> Statement
where RowDecoder: TableRecord
@@ -731,7 +747,7 @@ extension QueryInterfaceRequest {
/// - parameter db: A database connection.
/// - returns: A ``RecordCursor`` over the deleted records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func deleteAndFetchCursor(_ db: Database)
public func deleteAndFetchCursor(_ db: DatabaseBase<some SQLiteAPI>)
throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
{
@@ -758,7 +774,7 @@ extension QueryInterfaceRequest {
/// - parameter db: A database connection.
/// - returns: An array of deleted records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func deleteAndFetchAll(_ db: Database)
public func deleteAndFetchAll(_ db: DatabaseBase<some SQLiteAPI>)
throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
{
@@ -784,7 +800,7 @@ extension QueryInterfaceRequest {
/// - parameter db: A database connection.
/// - returns: A set of deleted records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func deleteAndFetchSet(_ db: Database)
public func deleteAndFetchSet(_ db: DatabaseBase<some SQLiteAPI>)
throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
{
@@ -810,7 +826,7 @@ extension QueryInterfaceRequest {
/// - parameter db: A database connection.
/// - returns: A set of deleted ids.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func deleteAndFetchIds(_ db: Database)
public func deleteAndFetchIds(_ db: DatabaseBase<some SQLiteAPI>)
throws -> Set<RowDecoder.ID>
where RowDecoder: TableRecord & Identifiable,
RowDecoder.ID: Hashable & DatabaseValueConvertible & StatementColumnConvertible
@@ -847,11 +863,10 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: `selection` is not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func deleteAndFetchStatement(
_ db: Database,
selection: [any SQLSelectable])
throws -> Statement
{
public func deleteAndFetchStatement<API>(
_ db: DatabaseBase<API>,
selection: [any SQLSelectable]
) throws -> StatementBase<API> {
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection)
}
@@ -886,7 +901,7 @@ extension QueryInterfaceRequest {
/// - precondition: The result of `select` is not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func deleteAndFetchStatement(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> Statement
where RowDecoder: TableRecord
@@ -917,7 +932,7 @@ extension QueryInterfaceRequest {
/// - returns: A ``RecordCursor`` over the deleted records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func deleteAndFetchCursor(_ db: Database)
public func deleteAndFetchCursor(_ db: DatabaseBase<some SQLiteAPI>)
throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
{
@@ -945,7 +960,7 @@ extension QueryInterfaceRequest {
/// - returns: An array of deleted records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func deleteAndFetchAll(_ db: Database)
public func deleteAndFetchAll(_ db: DatabaseBase<some SQLiteAPI>)
throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
{
@@ -972,7 +987,7 @@ extension QueryInterfaceRequest {
/// - returns: A set of deleted records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func deleteAndFetchSet(_ db: Database)
public func deleteAndFetchSet(_ db: DatabaseBase<some SQLiteAPI>)
throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
{
@@ -999,7 +1014,7 @@ extension QueryInterfaceRequest {
/// - returns: A set of deleted ids.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func deleteAndFetchIds(_ db: Database)
public func deleteAndFetchIds(_ db: DatabaseBase<some SQLiteAPI>)
throws -> Set<RowDecoder.ID>
where RowDecoder: TableRecord & Identifiable,
RowDecoder.ID: Hashable & DatabaseValueConvertible & StatementColumnConvertible
@@ -1020,7 +1035,7 @@ extension QueryInterfaceRequest {
extension QueryInterfaceRequest {
/// The conflict resolution to use for batch updates
private var defaultConflictResolutionForUpdate: Database.ConflictResolution {
private var defaultConflictResolutionForUpdate: DatabaseConflictResolution {
// In order to look for the default conflict resolution, we perform a
// runtime check for MutablePersistableRecord, and look for a
// user-defined default. Such dynamic dispatch is unusual in GRDB, but
@@ -1057,8 +1072,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@discardableResult
public func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
assignment: (DatabaseComponents) throws -> ColumnAssignment
) throws -> Int
where RowDecoder: TableRecord
@@ -1092,8 +1107,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@discardableResult
public func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> Int
where RowDecoder: TableRecord
@@ -1120,8 +1135,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@discardableResult
public func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ assignments: [ColumnAssignment]) throws -> Int
{
let conflictResolution = conflictResolution ?? defaultConflictResolutionForUpdate
@@ -1133,8 +1148,11 @@ extension QueryInterfaceRequest {
// database not hit
return 0
}
try updateStatement.execute()
return db.changesCount
var changesCount = 0
try db.countChanges(&changesCount, forTable: relation.source.tableName) {
try updateStatement.execute()
}
return changesCount
}
/// Updates matching rows, and returns the number of updated rows.
@@ -1156,8 +1174,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@discardableResult
public func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ assignments: ColumnAssignment...)
throws -> Int
{
@@ -1168,7 +1186,7 @@ extension QueryInterfaceRequest {
// MARK: - Batch Update and Fetch
extension QueryInterfaceRequest {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Returns an `UPDATE RETURNING` prepared statement.
///
/// For example:
@@ -1206,8 +1224,8 @@ extension QueryInterfaceRequest {
/// - precondition: The results of `select` and `assignments` results
/// are not empty.
public func updateAndFetchStatement(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment],
select: (DatabaseComponents) -> [any SQLSelectable]
) throws -> Statement
@@ -1247,8 +1265,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: `selection` and `assignments` are not empty.
public func updateAndFetchStatement(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ assignments: [ColumnAssignment],
selection: [any SQLSelectable])
throws -> Statement
@@ -1301,8 +1319,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The result of `assignments` is not empty.
public func updateAndFetchCursor(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
@@ -1336,8 +1354,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: `assignments` is not empty.
public func updateAndFetchCursor(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
@@ -1380,8 +1398,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The result of `assignments` is not empty.
public func updateAndFetchAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
@@ -1412,8 +1430,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: `assignments` is not empty.
public func updateAndFetchAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
@@ -1451,8 +1469,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The result of `assignments` is not empty.
public func updateAndFetchSet(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
@@ -1483,8 +1501,8 @@ extension QueryInterfaceRequest {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: `assignments` is not empty.
public func updateAndFetchSet(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
@@ -1530,8 +1548,8 @@ extension QueryInterfaceRequest {
/// are not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetchStatement(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment],
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> Statement
@@ -1572,8 +1590,8 @@ extension QueryInterfaceRequest {
/// - precondition: `selection` and `assignments` are not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetchStatement(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ assignments: [ColumnAssignment],
selection: [any SQLSelectable])
throws -> Statement
@@ -1627,8 +1645,8 @@ extension QueryInterfaceRequest {
/// - precondition: The result of `assignments` is not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetchCursor(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
@@ -1663,8 +1681,8 @@ extension QueryInterfaceRequest {
/// - precondition: `assignments` is not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetchCursor(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
@@ -1708,8 +1726,8 @@ extension QueryInterfaceRequest {
/// - precondition: The result of `assignments` is not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetchAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
@@ -1741,8 +1759,8 @@ extension QueryInterfaceRequest {
/// - precondition: `assignments` is not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetchAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
@@ -1781,8 +1799,8 @@ extension QueryInterfaceRequest {
/// - precondition: The result of `assignments` is not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetchSet(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
@@ -1814,8 +1832,8 @@ extension QueryInterfaceRequest {
/// - precondition: `assignments` is not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetchSet(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ db: DatabaseBase<some SQLiteAPI>,
onConflict conflictResolution: DatabaseConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
@@ -2136,7 +2154,7 @@ extension ColumnExpression {
/// - parameter willExecuteSupplementaryRequest: A closure executed before a
/// supplementary fetch is performed.
private func prefetch(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
associations: [_SQLAssociation],
from originRelation: SQLRelation,
into originRows: [Row],
@@ -2303,7 +2321,7 @@ func makePrefetchRequest(
// CAUTION: Keep this code in sync with prefetch(_:associations:in:)
/// Returns the region of prefetched associations
func prefetchedRegion(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
associations: [_SQLAssociation],
from originTable: String)
throws -> DatabaseRegion
@@ -2325,7 +2343,7 @@ throws -> DatabaseRegion
// CAUTION: Keep this code in sync with prefetch(_:associations:in:)
func prefetchedRegion(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
association: _SQLAssociation,
pivotMapping: JoinMapping)
throws -> DatabaseRegion
@@ -40,6 +40,7 @@ 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
@@ -67,10 +68,12 @@ public protocol SelectionRequest {
///
/// - parameter selection: A closure that accepts a database connection and
/// returns an array of result columns.
func selectWhenConnected(
_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]
func selectWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ selection: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLSelectable]
) -> Self
#warning("TODO: expose a version with default api")
/// Appends result columns to the selected columns.
///
/// The `selection` parameter is a closure that accepts a database
@@ -89,8 +92,9 @@ public protocol SelectionRequest {
///
/// - parameter selection: A closure that accepts a database connection and
/// returns an array of result columns.
func annotatedWhenConnected(
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]
func annotatedWhenConnected<API: SQLiteAPI>(
api: API.Type,
with selection: @escaping @Sendable (DatabaseBase<API>) throws -> [any SQLSelectable]
) -> Self
}
@@ -358,6 +362,7 @@ extension SelectionRequest where Self: TypedRequest, Self.RowDecoder: TableRecor
///
/// - ``filter(_:)-48a4t``
public protocol FilteredRequest {
#warning("TODO: expose a version with default api")
/// Filters the fetched rows with a boolean SQL expression.
///
/// The `predicate` parameter is a closure that accepts a database
@@ -377,8 +382,9 @@ public protocol FilteredRequest {
///
/// - parameter predicate: A closure that accepts a database connection and
/// returns a boolean SQL expression.
func filterWhenConnected(
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible
func filterWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ predicate: @escaping @Sendable (DatabaseBase<$API>) throws -> any SQLExpressible
) -> Self
}
@@ -747,7 +753,10 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
/// let request = try Player...filterWhenConnected(keys: { db in [1, 2, 3] })
///
/// - parameter keys: A collection of primary keys
fileprivate func filterWhenConnected(keys: @escaping @Sendable (Database) throws -> [SQLExpression]) -> Self {
fileprivate func filterWhenConnected<API: SQLiteAPI>(
api: API.Type,
keys: @escaping @Sendable (DatabaseBase<API>) 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
@@ -826,10 +835,17 @@ 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 {
fatalError("""
table \(databaseTableName) has no unique key on column(s) \
\(key.keys.sorted().joined(separator: ", "))
""")
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: ", "))
""")
}
}
let lowercaseColumns = columns.map { $0.lowercased() }
@@ -985,6 +1001,7 @@ extension TableRequest where Self: AggregatingRequest {
/// - ``group(_:)-4216o``
/// - ``having(_:)-2ssg9``
public protocol AggregatingRequest {
#warning("TODO: expose a version with default api")
/// Returns an aggregate request grouped on the given SQL expressions.
///
/// The `expressions` parameter is a closure that accepts a database
@@ -1007,10 +1024,12 @@ public protocol AggregatingRequest {
///
/// - parameter expressions: A closure that accepts a database connection
/// and returns an array of SQL expressions.
func groupWhenConnected(
_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible]
func groupWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ expressions: @escaping @Sendable (DatabaseBase<API>) 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
@@ -1033,8 +1052,9 @@ public protocol AggregatingRequest {
///
/// - parameter predicate: A closure that accepts a database connection and
/// returns a boolean SQL expression.
func havingWhenConnected(
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible
func havingWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ predicate: @escaping @Sendable (DatabaseBase<API>) throws -> any SQLExpressible
) -> Self
}
@@ -1263,6 +1283,7 @@ extension AggregatingRequest where Self: TypedRequest, Self.RowDecoder: TableRec
/// - ``order(_:)-63rzl``
/// - ``order(_:)-6co0m``
public protocol OrderedRequest {
#warning("TODO: expose a version with default api")
/// Sorts the fetched rows according to the given SQL ordering terms.
///
/// The `orderings` parameter is a closure that accepts a database
@@ -1290,8 +1311,9 @@ public protocol OrderedRequest {
///
/// - parameter orderings: A closure that accepts a database connection and
/// returns an array of SQL ordering terms.
func orderWhenConnected(
_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm]
func orderWhenConnected<API: SQLiteAPI>(
api: API.Type,
_ orderings: @escaping @Sendable (DatabaseBase<API>) 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 (Database) throws -> T
let resolve: @Sendable (DatabaseBase<some SQLiteAPI>) 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 (Database) throws -> T) {
init(_ resolve: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) 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, Database.StorageClass)
indirect case cast(SQLExpression, DatabaseStorageClass)
/// 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 || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// 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: Database.StorageClass) -> Self {
static func cast(_ expression: SQLExpression, as storageClass: DatabaseStorageClass) -> Self {
self.init(impl: .cast(expression, storageClass))
}
@@ -1193,7 +1193,7 @@ extension SQLExpression {
/// The expression as a quoted SQL literal (not public in order to avoid abuses)
///
/// try "foo'bar".databaseValue.quotedSQL(db) // "'foo''bar'""
func quotedSQL(_ db: Database) throws -> String {
func quotedSQL(_ db: DatabaseBase<some SQLiteAPI>) throws -> String {
let context = SQLGenerationContext(db, argumentsSink: .literalValues)
return try sql(context)
}
@@ -1223,7 +1223,7 @@ extension SQLExpression {
/// - parameter acceptsBijection: If true, expressions that define a
/// bijection on a column return this column. For example: `-score`
/// returns `score`.
func column(_ db: Database, for alias: TableAliasBase, acceptsBijection: Bool = false) throws -> String? {
func column(_ db: DatabaseBase<some SQLiteAPI>, for alias: TableAliasBase, acceptsBijection: Bool = false) throws -> String? {
switch impl {
case let .qualifiedColumn(name, a):
if alias == a {
@@ -1510,7 +1510,7 @@ extension SQLExpression {
///
/// // SELECT * FROM "player" WHERE "name" = 'Arthur' LIMIT 1
/// try Player.filter(Column("name") == "Arthur").fetchOne(db)
func identifyingColums(_ db: Database, for alias: TableAliasBase) throws -> Set<String> {
func identifyingColums(_ db: DatabaseBase<some SQLiteAPI>, 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: Database, for alias: TableAliasBase) throws -> Set<Int64>? {
func identifyingRowIDs(_ db: DatabaseBase<some SQLiteAPI>, 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>? = nil
var result: Set<Int64>?
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: Database, for alias: TableAliasBase) throws -> String? {
func column(_ db: DatabaseBase<some SQLiteAPI>, 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? = nil // SQLite 3.44.0+
var filter: SQLExpression? = nil // @available(iOS 14, macOS 10.16, tvOS 14, *) SQLite 3.30+
var ordering: SQLOrdering? // SQLite 3.44.0+
var filter: SQLExpression? // @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 || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Returns an expression suitable in JSON building contexts.
var jsonBuilderExpression: SQLExpression {
switch preferredJSONInterpretation {
@@ -2373,7 +2373,7 @@ extension SQLSpecificExpressible {
.desc(sqlExpression)
}
#if GRDBCUSTOMSQLITE
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// 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)
}
#elseif !GRDBCIPHER
#else
/// 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: Database) throws -> ForeignKeyMapping {
func fetchForeignKeyMapping(_ db: DatabaseBase<some SQLiteAPI>) 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: Database, for name: String) throws -> TableType? {
for schemaID in try db.schemaIdentifiers() {
private func tableType(_ db: DatabaseBase<some SQLiteAPI>, for name: String) throws -> TableType? {
for schemaID in try db.fetchSchemaIdentifiers() {
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 || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// 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: Database.StorageClass) -> SQLExpression {
public func cast(_ expression: some SQLSpecificExpressible, as storageClass: DatabaseStorageClass) -> SQLExpression {
.cast(expression.sqlExpression, as: storageClass)
}
@@ -163,7 +163,7 @@ public func max(
.simpleFunction("MAX", [value1.sqlExpression, value2.sqlExpression] + values.map(\.sqlExpression))
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// 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 || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// The `MIN` SQL aggregate function.
///
/// For example:
@@ -269,7 +269,7 @@ public func min(_ value: some SQLSpecificExpressible) -> SQLExpression {
}
#endif
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// The `SUM` SQL aggregate function.
///
/// For example:
@@ -333,7 +333,7 @@ public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression {
}
#endif
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// The `TOTAL` SQL aggregate function.
///
/// For example:
+19 -17
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 (Database) -> [SQLSelection] = { _ in [.allColumns] })
selection: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) -> [SQLSelection] = { _ in [.allColumns] })
-> Self
{
SQLRelation(
@@ -197,7 +197,7 @@ extension SQLRelation {
}
extension SQLRelation: Refinable {
func selectWhenConnected(_ selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self {
func selectWhenConnected(_ selection: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> [SQLSelection]) -> Self {
with {
$0.selectionPromise = DatabasePromise(selection)
}
@@ -228,7 +228,7 @@ extension SQLRelation: Refinable {
}
}
func annotatedWhenConnected(with selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self {
func annotatedWhenConnected(with selection: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> [SQLSelection]) -> Self {
with {
let old = $0.selectionPromise
$0.selectionPromise = DatabasePromise { db in
@@ -242,7 +242,7 @@ extension SQLRelation: Refinable {
annotatedWhenConnected(with: { _ in selection })
}
func filterWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self {
func filterWhenConnected(_ predicate: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> SQLExpression) -> Self {
with {
if let old = $0.filterPromise {
$0.filterPromise = DatabasePromise { db in
@@ -259,7 +259,7 @@ extension SQLRelation: Refinable {
filterWhenConnected { _ in predicate }
}
func orderWhenConnected(_ orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) -> Self {
func orderWhenConnected(_ orderings: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> [SQLOrdering]) -> Self {
with {
$0.ordering = SQLRelation.Ordering(orderings: orderings)
}
@@ -285,12 +285,14 @@ extension SQLRelation: Refinable {
func withStableOrder() -> Self {
with { relation in
relation.ordering = relation.ordering.appending(Ordering(orderings: { [relation] db in
if try db.tableExists(source.tableName) {
do {
// 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 }
} else {
// Support for views: create a stable order from all columns:
} 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:
// ORDER BY 1, 2, 3, ...
let columnCount = try SQLQueryGenerator(relation: relation).columnCount(db)
return (1...columnCount).map { SQL(sql: $0.description).sqlOrdering }
@@ -313,13 +315,13 @@ extension SQLRelation: Refinable {
}
}
func groupWhenConnected(_ expressions: @escaping @Sendable (Database) throws -> [SQLExpression]) -> Self {
func groupWhenConnected(_ expressions: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> [SQLExpression]) -> Self {
with {
$0.groupPromise = DatabasePromise(expressions)
}
}
func havingWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self {
func havingWhenConnected(_ predicate: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> SQLExpression) -> Self {
with {
if let old = $0.havingExpressionPromise {
$0.havingExpressionPromise = DatabasePromise { db in
@@ -600,7 +602,7 @@ extension SQLRelation {
}
extension SQLRelation {
func fetchCount(_ db: Database) throws -> Int {
func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
guard groupPromise == nil && limit == nil && ctes.isEmpty else {
// SELECT ... GROUP BY ...
// SELECT ... LIMIT ...
@@ -649,7 +651,7 @@ extension SQLRelation {
}
// SELECT COUNT(*) FROM (self)
private func fetchTrivialCount(_ db: Database) throws -> Int {
private func fetchTrivialCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
let countRequest: SQLRequest<Int> = "SELECT COUNT(*) FROM (\(SQLSubquery.relation(unordered())))"
return try countRequest.fetchOne(db)!
}
@@ -714,7 +716,7 @@ extension SQLRelation {
}
}
func resolve(_ db: Database) throws -> [SQLOrdering] {
func resolve(_ db: DatabaseBase<some SQLiteAPI>) throws -> [SQLOrdering] {
switch self {
case .terms(let terms):
return try terms.resolve(db)
@@ -740,7 +742,7 @@ extension SQLRelation {
isReversed: false)
}
init(orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) {
init(orderings: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> [SQLOrdering]) {
self.init(
elements: [.terms(DatabasePromise(orderings))],
isReversed: false)
@@ -764,7 +766,7 @@ extension SQLRelation {
isReversed: isReversed)
}
func resolve(_ db: Database) throws -> [SQLOrdering] {
func resolve(_ db: DatabaseBase<some SQLiteAPI>) throws -> [SQLOrdering] {
if isReversed {
return try elements.flatMap { try $0.reversed.resolve(db) }
} else {
@@ -830,7 +832,7 @@ enum SQLAssociationCondition: Sendable {
}
func joinExpression(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
leftAlias: TableAliasBase,
rightAlias: TableAliasBase)
throws -> SQLExpression?
@@ -889,7 +891,7 @@ struct SQLForeignKeyCondition: Equatable {
/// Turns the foreign key condition into a `JoinMapping` that can feed an
/// SQL JOIN clause.
func joinMapping(_ db: Database, from originTable: String) throws -> JoinMapping {
func joinMapping(_ db: DatabaseBase<some SQLiteAPI>, 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) throws -> Int {
func columnCount(_ context: SQLGenerationContext<some SQLiteAPI>) 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: Database) throws -> Int {
func columnCount(_ db: DatabaseBase<some SQLiteAPI>) 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