Compare commits

...
Author SHA1 Message Date
Tim De Jong 3dd3bbf0c5 vscode config 2025-10-12 18:03:57 +02:00
Tim De Jong d7cf0f9e59 NSError bridging is not available, or doesn't work the same on non-Darwin platforms. Skip testNSErrorBridging on these platforms. 2025-10-12 18:03:57 +02:00
Tim De Jong 389c3e0d4a Use #if !canImport(Combine) per test case (as done by @marcprux) and throw an XCTSkip for these test cases. This gives a better impression how many tests are skipped on Linux/non-Darwin platforms. 2025-10-12 18:03:57 +02:00
Tim De Jong a212bf9e89 It should be canImport(Darwin) not os(Darwin) 2025-10-12 18:03:57 +02:00
Tim De Jong 65186104cc Integrated upstream changes.
Some tests depend on Combine which is not available on non-Darwin platforms. Fix this.
2025-10-12 18:03:57 +02:00
Tim De Jong 2f108508fa Fixed DatabaseSnapshotTests on non-darwin platforms 2025-10-12 18:03:57 +02:00
Tim De Jong 5513eab099 Fixed the tests in DatabaseQueueTests.swift 2025-10-12 18:03:57 +02:00
Tim De Jong 2ad2d20a89 Fixed the unit tests in DatabasePoolConcurrencyTests. 2025-10-12 18:03:57 +02:00
Tim De Jong dd90fe6e62 Ignore ValueObservationRecorderTests.swift on non-Darwin platforms. 2025-10-12 18:03:57 +02:00
Tim De Jong 691207567a Ignore FailureTestCase.swift entirely on non-Darwin platforms for now. 2025-10-12 18:03:57 +02:00
Tim De Jong c7f1dd7470 Fixed import in CGFloatTests.swift to work under non-Darwin platforms. 2025-10-12 18:03:57 +02:00
Tim De Jong 8e5b9ca9bd Fixed UUID fromDatabaseValue for non-Darwin platforms 2025-10-12 18:03:56 +02:00
Tim De Jong dc7d47c066 Fixed databaseValue build for non-Darwin platforms. 2025-10-12 18:03:56 +02:00
Tim De Jong 14f60ad48f Fixed fromDatabaseValue build under non-Darwin platforms 2025-10-12 18:03:56 +02:00
Tim De Jong e758fde941 Removed #if !os(Linux) in NSString.swift, NSData.swift and Date.swift. 2025-10-12 17:43:25 +02:00
Tim De Jong 7477e1cff8 Removed the #if !os(Linux) compiler directive in the Decimal extension, as it compiles fine under swift 6 2025-10-12 17:43:15 +02:00
Tim De Jong 2d6fe172c3 Import Foundation for CGFloat on non-Darwin platforms 2025-10-12 17:43:02 +02:00
Tim De Jong 0526853dde Fixed some linker errors caused by WAL absence on Linux. 2025-10-12 17:42:49 +02: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
Gwendal Roué 8ba1bc9a96 Merge branch 'development' 2025-07-23 13:27:07 +02:00
Gwendal Roué c4e39285a0 v7.6.1 2025-07-23 13:27:01 +02:00
Gwendal Roué 1622b72b62 Merge pull request #1797 from groue/dev/cancellation-fix
Fix race condition regarding Task cancellation
2025-07-23 13:24:52 +02:00
Gwendal Roué 215128390d Fix race condition: prevent cancellation from cancelling other database accesses after database accesses has completed
Before this change, cancelling a database access could cancel *another* database access 😱
2025-07-23 12:01:58 +02:00
Gwendal Roué c5283a0bd9 Warn against the incompatibility between custom SQLite builds and SPM
Addresses https://github.com/groue/GRDB.swift/issues/1709#issuecomment-3100503200
2025-07-22 07:47:41 +02:00
Gwendal Roué fb68849bfb Merge branch 'development' 2025-07-20 18:11:22 +02:00
Gwendal Roué c2bddde88a v7.6.0 2025-07-20 17:21:28 +02:00
Gwendal Roué b4a21d63b2 Merge pull request #1796 from groue/dev/public-RowDecodingError
Throwing row accessors
2025-07-20 17:13:49 +02:00
Gwendal Roué 6ca38eda3b Give TableAliasBase a location in DocC 2025-07-20 14:38:15 +02:00
Gwendal Roué d76922fe1a Document throwing accessors for records and record collections 2025-07-20 14:38:15 +02:00
Gwendal Roué a46f3b69e9 Document throwing row accessors 2025-07-20 14:38:15 +02:00
Gwendal Roué b572982e34 Document RowDecodingError 2025-07-20 13:11:42 +02:00
Gwendal Roué 5a8b025ee8 TODO: test throwing row accessors of record collections and sets 2025-07-20 13:00:12 +02:00
Gwendal Roué 9a1914a813 Test throwing record row accessors 2025-07-20 13:00:12 +02:00
Gwendal Roué 4a92263c5e Test throwing column row accessors 2025-07-20 13:00:12 +02:00
Gwendal Roué f72d0cecb2 Document throwing row accessors 2025-07-20 13:00:12 +02:00
Gwendal Roué 24e0f5ddeb Make throwing row accessors public 2025-07-20 13:00:12 +02:00
Gwendal Roué 2b1b56ea47 Make RowDecodingError public 2025-07-20 13:00:12 +02:00
Gwendal Roué ad704c58e5 Hide implementation of RowDecodingError
Turn the enum into a struct so that it can be made public without exposing internal details
2025-07-20 13:00:12 +02:00
Gwendal Roué 3f928bcf9c Merge pull request #1794 from groue/dev/actor-access
Access task locals from asynchronous database accesses
2025-07-19 17:15:25 +02:00
Gwendal Roué c91c183354 Async database accesses are no longer escaping and no longer need to capture self 2025-07-19 16:42:17 +02:00
Gwendal Roué c666393e63 AppDatabase can be a struct, so let it be a struct 2025-07-19 16:42:17 +02:00
Gwendal Roué d242421862 Async methods accept a non-escaping closure 2025-07-19 16:42:17 +02:00
Gwendal Roué 7a1e65b142 Remove late cancellation checks
I'm slowly changing my mind about this.
2025-07-19 15:27:08 +02:00
Gwendal Roué fb4578a7d6 Delete unused code 2025-07-19 15:26:46 +02:00
Gwendal Roué 6069e6d683 DatabasePool.barrierWriteWithoutTransaction can access task locals 2025-07-19 15:26:44 +02:00
Gwendal Roué a703da9b27 Async version of Pool.barrier { ... } 2025-07-19 14:25:50 +02:00
Gwendal Roué 684266b7b8 DispatchQueueActor supports barriers in concurrent DispatchQueue 2025-07-19 14:25:50 +02:00
Gwendal Roué b24fb76610 Failing test for task locals with DatabaseWriter (#1793) 2025-07-19 14:25:50 +02:00
Gwendal Roué cbbd0cb945 Add asserts about expected ends of transaction 2025-07-19 14:25:50 +02:00
Gwendal Roué dd4227303a DatabasePool unsafeRead can access task locals 2025-07-19 14:25:50 +02:00
Gwendal Roué 69b786dc9e Allow COMMIT from a cancelled read-only access. 2025-07-19 14:25:50 +02:00
Gwendal Roué 9dd8b2cef7 Add failing test for task locals access from unsafeRead (#1793) 2025-07-19 14:25:50 +02:00
Gwendal Roué c5ac6cdaa6 DatabaseSnapshotPool reads can access task locals 2025-07-19 14:25:50 +02:00
Gwendal Roué e154a652dc Don't check for reentrancy from async Pool.read
One can't call an async function from a database access anywau
2025-07-19 14:25:50 +02:00
Gwendal Roué 41d4f23a83 DatabasePool reads can access task locals 2025-07-19 14:25:50 +02:00
Gwendal Roué 27b7400979 Async version of Pool.get() 2025-07-19 14:25:50 +02:00
Gwendal Roué e6847886db Extract DispatchQueueActor
We'll probably need it in order to access pool elements with support for task locals
2025-07-19 14:25:50 +02:00
Gwendal Roué c064515247 DatabaseQueue and DatabaseSnapshot reads can access task locals 2025-07-19 14:25:50 +02:00
Gwendal Roué 96236a3d44 Turn Database.cancel into a sendable closure 2025-07-19 14:25:50 +02:00
Gwendal Roué 01cd49b4ec Failing test for task locals (#1793) 2025-07-19 14:25:50 +02:00
Gwendal Roué 9db14cb893 Merge pull request #1776 from Jason-Abbott/development
Add custom build instruction for hardened runtime
2025-06-11 09:22:36 +02:00
Jason Abbott b26f60eae0 Add custom build instruction for hardened runtime 2025-06-10 18:45:29 -06:00
Gwendal Roué 79a41dcbbb Merge pull request #1773 from Jason-Abbott/development 2025-06-01 10:24:09 +02:00
Jason Abbott c7d50486ad Merge branch 'groue:development' into development 2025-05-30 12:05:03 -06:00
Jason Abbott 93292d88f4 Make DatabasePreUpdateEvent.Kind Sendable, matching DatabaseEvent.Kind, and also duplicate comments from DatabaseEvent.Kind while here 2025-05-30 12:02:23 -06:00
Gwendal Roué be22e0a2d0 Merge pull request #1768 from groue/dev/throwing-closures
All closures that accept DatabaseComponents can throw
2025-05-12 20:58:47 +02:00
Gwendal Roué d1a2cb0948 All closures that accept DatabaseComponents can throw 2025-05-12 20:33:18 +02:00
192 changed files with 5817 additions and 1858 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
+7
View File
@@ -0,0 +1,7 @@
{
"editor.formatOnSave": false,
"editor.insertSpaces": true,
"editor.tabSize": 4,
"editor.detectIndentation": false,
"editor.trimAutoWhitespace": false
}
+40
View File
@@ -7,6 +7,9 @@ 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)
- `7.3.x` Releases - [7.3.0](#730)
@@ -137,6 +140,43 @@ 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
- **Fixed**: Fix race condition regarding Task cancellation by [@groue](https://github.com/groue) in [#1797](https://github.com/groue/GRDB.swift/pull/1797)
## 7.6.0
Released July 20, 2025
- **New**: All closures that accept DatabaseComponents can throw by [@groue](https://github.com/groue) in [#1768](https://github.com/groue/GRDB.swift/pull/1768)
- **New**: Add Sendable conformance to DatabasePreUpdateEvent.Kind, matching DatabaseEvent.Kind by [@Jason-Abbott](https://github.com/Jason-Abbott) in [#1773](https://github.com/groue/GRDB.swift/pull/1773)
- **New**: Add custom build instruction for hardened runtime by [@Jason-Abbott](https://github.com/Jason-Abbott) in [#1776](https://github.com/groue/GRDB.swift/pull/1776)
- **New**: Access task locals from asynchronous database accesses by [@groue](https://github.com/groue) in [#1794](https://github.com/groue/GRDB.swift/pull/1794)
- **New**: Throwing row accessors by [@groue](https://github.com/groue) in [#1796](https://github.com/groue/GRDB.swift/pull/1796)
## 7.5.0
Released May 11, 2025
+8 -9
View File
@@ -2186,26 +2186,25 @@ struct BookInfo: FetchableRecord {
init(row: Row) throws {
book = try Book(row: row)
author = row["author"]
country = row["country"]
coverImage = row["coverImage"]
author = try row.decode(forKey: "author")
country = try row.decodeIfPresent(forKey: "country")
coverImage = try row.decodeIfPresent(forKey: "coverImage")
}
}
let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
```
You are already familiar with row subscripts to decode [database values](../README.md#column-values):
When you extract a record from a row, GRDB looks up the tree of **association keys**:
```swift
let name: String = row["name"]
let author = try row.decode(Author.self, forKey: "author")
```
When you extract a record instead of a value from a row, GRDB looks up the tree of **association keys**. If the key is not found, or only associated with columns that all contain NULL values, an optional record is decoded as nil:
If the key is not found, or only associated with columns that are all NULL, an optional record is decoded as nil:
```swift
let author: Author = row["author"]
let country: Country? = row["country"]
let country = try row.decodeIfPresent(Country.self, forKey: "country")
```
You can also perform custom navigation in the tree by using *row scopes*. See [Row Adapters] for more information.
@@ -2221,7 +2220,7 @@ struct AuthorInfo: FetchableRecord {
init(row: Row) throws {
author = try Author(row: row)
books = row["books"]
books = try row.decode(forKey: "books")
}
}
+32 -26
View File
@@ -9,18 +9,20 @@ A custom SQLite build can activate extra SQLite features, and extra GRDB feature
GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfalling/SQLiteLib), which uses the same SQLite configuration as the one used by Apple in its operating systems, and lets you add extra compilation options that leverage the features you need.
> Warning: The technique described here is not compatible with the Swift Package Manager (SPM). It will create [build issues](https://github.com/groue/GRDB.swift/issues/1709) with SPM companion librairies such as [GRDBQuery](https://github.com/groue/GRDBQuery) or [GRDBSnapshotTesting](https://github.com/groue/GRDBSnapshotTesting).
**To install GRDB with a custom SQLite build:**
1. Clone the GRDB git repository, checkout the latest tagged version:
```sh
cd [GRDB directory]
git checkout [latest tag]
git submodule update --init SQLiteCustom/src
```
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5`, `SQLITE_ENABLE_PREUPDATE_HOOK`.
It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation) when you use a [Database Pool](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool).
3. Create a folder named `GRDBCustomSQLite` somewhere in your project directory.
@@ -28,31 +30,31 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
4. Create four files in the `GRDBCustomSQLite` folder:
- `SQLiteLib-USER.xcconfig`: this file sets the extra SQLite compilation flags.
```xcconfig
// As many -D options as there are custom SQLite compilation options
// Note: there is no space between -D and the option name.
CUSTOM_SQLLIBRARY_CFLAGS = -DSQLITE_ENABLE_SNAPSHOT -DSQLITE_ENABLE_FTS5
```
- `GRDBCustomSQLite-USER.xcconfig`: this file lets GRDB know about extra compilation flags, and enables extra GRDB APIs.
```xcconfig
// As many -D options as there are custom SQLite compilation options
// Note: there is one space between -D and the option name.
CUSTOM_OTHER_SWIFT_FLAGS = -D SQLITE_ENABLE_SNAPSHOT -D SQLITE_ENABLE_FTS5
```
- `GRDBCustomSQLite-USER.h`: this file lets your application know about extra compilation flags.
```c
// As many #define as there are custom SQLite compilation options
#define SQLITE_ENABLE_SNAPSHOT
#define SQLITE_ENABLE_FTS5
```
- `GRDBCustomSQLite-INSTALL.sh`: this file installs the three other files.
```sh
# License: MIT License
# https://github.com/swiftlyfalling/SQLiteLib/blob/master/LICENSE
@@ -61,52 +63,52 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
# PROJECT PATHS
# !! MODIFY THESE TO MATCH YOUR PROJECT HIERARCHY !!
#######################################################
# The path to the folder containing GRDBCustom.xcodeproj:
GRDB_SOURCE_PATH="${PROJECT_DIR}/GRDB"
# The path to your custom "SQLiteLib-USER.xcconfig":
SQLITELIB_XCCONFIG_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/SQLiteLib-USER.xcconfig"
# The path to your custom "GRDBCustomSQLite-USER.xcconfig":
CUSTOMSQLITE_XCCONFIG_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-USER.xcconfig"
# The path to your custom "GRDBCustomSQLite-USER.h":
CUSTOMSQLITE_H_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-USER.h"
#######################################################
#
#######################################################
if [ ! -d "$GRDB_SOURCE_PATH" ];
then
echo "error: Path to GRDB source (GRDB_SOURCE_PATH) missing/incorrect: $GRDB_SOURCE_PATH"
exit 1
fi
SyncFileChanges () {
SOURCE=$1
DESTINATIONPATH=$2
DESTINATIONFILENAME=$3
DESTINATION="${DESTINATIONPATH}/${DESTINATIONFILENAME}"
if [ ! -f "$SOURCE" ];
then
echo "error: Source file missing: $SOURCE"
exit 1
fi
rsync -a "$SOURCE" "$DESTINATION"
}
SyncFileChanges $SQLITELIB_XCCONFIG_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom/src" "SQLiteLib-USER.xcconfig"
SyncFileChanges $CUSTOMSQLITE_XCCONFIG_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom" "GRDBCustomSQLite-USER.xcconfig"
SyncFileChanges $CUSTOMSQLITE_H_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom" "GRDBCustomSQLite-USER.h"
echo "Finished syncing"
```
Modify the top of `GRDBCustomSQLite-INSTALL.sh` file so that it contains correct paths.
5. Embed the `GRDBCustom.xcodeproj` project in your own project.
@@ -116,17 +118,21 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
7. Add the `GRDBCustom.framework` from the targeted platform to the **Embedded Binaries** section of the **General** tab of your **application target**.
8. Add a Run Script phase for your target in the **Pre-actions** section of the **Build** tab of your **application scheme**:
```sh
source "${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-INSTALL.sh"
```
The path should be the path to your `GRDBCustomSQLite-INSTALL.sh` file.
Select your application target in the "Provide build settings from" menu.
9. Check the "Shared" checkbox of your application scheme (this lets you commit the pre-action in your Version Control System).
10. If you have enabled "Hardened Runtime" for your target (**Build Settings**/**Signing**) then you may need to check **Disable Library Validation** under the **Hardened Runtime** section of the **Signing & Capabilities** tab.
(The build error without this exception is "Library not loaded ... different Team IDs")
Now you can use GRDB with your custom SQLite build:
```swift
@@ -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"
@@ -12,7 +12,7 @@ import os.log
/// let dbQueue = try DatabaseQueue(configuration: config)
/// let appDatabase = try AppDatabase(dbQueue)
/// ```
final class AppDatabase: Sendable {
struct AppDatabase: Sendable {
/// Access to the database.
///
/// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections>
@@ -130,7 +130,7 @@ extension AppDatabase {
/// Refresh all players (by performing some random changes, for demo purpose).
func refreshPlayers() async throws {
try await dbWriter.write { [self] db in
try await dbWriter.write { db in
if try Player.all().isEmpty(db) {
// When database is empty, insert new random players
try createRandomPlayers(db)
@@ -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
+3 -3
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '7.5.0'
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
+23 -2
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 */; };
@@ -273,6 +275,7 @@
56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */; };
56A8C2301D1914540096E9D4 /* UUID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C22F1D1914540096E9D4 /* UUID.swift */; };
56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AACAA722ACED7100A40F2A /* Fetch.swift */; };
56AC93DF2E291C4700DB6C74 /* DispatchQueueActor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AC93DE2E291C4700DB6C74 /* DispatchQueueActor.swift */; };
56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */; };
56AE6424222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE6423222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift */; };
56AFEF2F29969F6E00CA1E51 /* TransactionClock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */; };
@@ -287,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 */; };
@@ -502,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>"; };
@@ -673,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>"; };
@@ -769,6 +775,7 @@
56A8C22F1D1914540096E9D4 /* UUID.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UUID.swift; sourceTree = "<group>"; };
56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSUUIDTests.swift; sourceTree = "<group>"; };
56AACAA722ACED7100A40F2A /* Fetch.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Fetch.swift; sourceTree = "<group>"; };
56AC93DE2E291C4700DB6C74 /* DispatchQueueActor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DispatchQueueActor.swift; sourceTree = "<group>"; };
56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HasOneThroughAssociation.swift; sourceTree = "<group>"; };
56AE6423222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLTests.swift; sourceTree = "<group>"; };
56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = "<group>"; };
@@ -790,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>"; };
@@ -995,6 +1003,7 @@
56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */,
563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */,
563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */,
568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */,
);
name = PersistableRecord;
sourceTree = "<group>";
@@ -1484,6 +1493,7 @@
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */,
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */,
568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */,
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */,
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */,
@@ -1590,18 +1600,19 @@
569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */,
564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */,
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */,
566A84192041146100E50BFD /* DatabaseSnapshot.swift */,
568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */,
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
56AC93DE2E291C4700DB6C74 /* DispatchQueueActor.swift */,
5636E9BB1D22574100B9B05F /* FetchRequest.swift */,
56A238761B9C75030082EB20 /* Row.swift */,
567404871CEF84C8003ED5CC /* RowAdapter.swift */,
566B9C1F25C6CC24004542CF /* RowDecodingError.swift */,
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
56E9FAD7221053DC00C703A8 /* SQL.swift */,
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */,
56FBFED82210731A00945324 /* SQLRequest.swift */,
@@ -1611,6 +1622,7 @@
56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */,
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
56B7EE822863781300C0525F /* WALSnapshot.swift */,
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
5605F1471C672E4000235C62 /* Support */,
);
path = Core;
@@ -1839,8 +1851,9 @@
DC3773EA19C8CBB3004FCF85 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = YES;
LastSwiftUpdateCheck = 0730;
LastUpgradeCheck = 1400;
LastUpgradeCheck = 2600;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
56E5D7F81B4D422D00430942 = {
@@ -2006,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 */,
@@ -2110,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 */,
@@ -2180,6 +2195,7 @@
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
5656A8B02295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */,
56AC93DF2E291C4700DB6C74 /* DispatchQueueActor.swift in Sources */,
5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */,
566DDE0D288D763C0000DCFB /* Fixits.swift in Sources */,
56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
@@ -2203,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 */,
@@ -2535,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 = (
@@ -2542,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;
@@ -2566,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 = (
@@ -2573,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"
+27 -8
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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)
@@ -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
@@ -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.
File diff suppressed because it is too large. Load diff
+8 -5
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
@@ -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,
+92 -26
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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:)``
@@ -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``
@@ -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.
@@ -1149,7 +1171,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// See <https://www.sqlite.org/c3ref/interrupt.html>
func interrupt() {
sqlite3_interrupt(sqliteConnection)
if let sqliteConnection {
sqlite3_interrupt(sqliteConnection)
}
}
// MARK: - Database Suspension
@@ -1223,22 +1247,31 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
/// Cancels the current database access. All statements but ROLLBACK
/// will throw `CancellationError`, until `uncancel()` is called.
///
/// This method can be called from any thread.
func cancel() {
let needsInterrupt = suspensionMutex.withLock { suspension in
if suspension.isCancelled {
return false
/// Returns a closure that cancels the current database access.
/// Most statements will throw `CancellationError`, until `uncancel()`
/// is called.
var cancel: @Sendable () -> Void {
// Workaround the fact that SQLiteConnection is not Sendable.
struct Connection: @unchecked Sendable {
var sqliteConnection: SQLiteConnection?
}
let connection = Connection(sqliteConnection: sqliteConnection)
return { [suspensionMutex, connection] in
let needsInterrupt = suspensionMutex.withLock { suspension in
if suspension.isCancelled {
return false
}
suspension.isCancelled = true
return suspension.interruptsWhenCancelled
}
suspension.isCancelled = true
return suspension.interruptsWhenCancelled
}
if needsInterrupt {
interrupt()
if needsInterrupt {
if let sqliteConnection = connection.sqliteConnection {
sqlite3_interrupt(sqliteConnection)
}
}
}
}
@@ -1275,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) }
@@ -1318,6 +1351,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
return
}
// Commits when read-only are just like rollbacks above.
if statement.transactionEffect == .commitTransaction && isReadOnly {
return
}
// Suspension should not prevent adjusting the read-only mode.
// See <https://github.com/groue/GRDB.swift/issues/1715>.
if statement.isQueryOnlyPragma {
@@ -1467,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()
@@ -1610,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()
@@ -1728,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.
@@ -1983,6 +2021,34 @@ extension Database {
}
#endif
extension Database {
/// 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 Database {
// MARK: - Database-Related Types
+27 -20
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
}
}
+7 -4
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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 -22
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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.
@@ -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.
+64 -70
View File
@@ -352,40 +352,29 @@ extension DatabasePool: DatabaseReader {
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
let dbAccess = CancellableDatabaseAccess()
return try await dbAccess.withCancellableContinuation { continuation in
readerPool.asyncGet { result in
do {
let (reader, releaseReader) = try result.get()
// Second async jump because that's how `Pool.async` has to be used.
reader.async { db in
defer {
try? db.commit() // Ignore commit error
releaseReader(.reuse)
}
do {
let result = try dbAccess.inDatabase(db) {
// The block isolation comes from the DEFERRED transaction.
try db.beginTransaction(.deferred)
try db.clearSchemaCacheIfNeeded()
return try value(db)
}
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
}
}
} catch {
continuation.resume(throwing: error)
}
}
return try await readerPool.get { reader in
try await reader.execute { db in
defer {
// Commit or rollback, but make sure we leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
assert(!db.isInsideTransaction)
}
// The block isolation comes from the DEFERRED transaction.
try db.beginTransaction(.deferred)
try db.clearSchemaCacheIfNeeded()
return try value(db)
}
}
}
@@ -403,7 +392,14 @@ extension DatabasePool: DatabaseReader {
// Second async jump because that's how `Pool.async` has to be used.
reader.async { db in
defer {
try? db.commit() // Ignore commit error
// 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)
}
do {
@@ -436,35 +432,16 @@ extension DatabasePool: DatabaseReader {
}
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
let dbAccess = CancellableDatabaseAccess()
return try await dbAccess.withCancellableContinuation { continuation in
readerPool.asyncGet { result in
do {
let (reader, releaseReader) = try result.get()
// Second async jump because that's how `Pool.async` has to be used.
reader.async { db in
defer {
releaseReader(.reuse)
}
do {
let result = try dbAccess.inDatabase(db) {
try db.clearSchemaCacheIfNeeded()
return try value(db)
}
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
}
}
} catch {
continuation.resume(throwing: error)
}
return try await readerPool.get { reader in
try await reader.execute { db in
try db.clearSchemaCacheIfNeeded()
return try value(db)
}
}
}
@@ -584,7 +561,14 @@ extension DatabasePool: DatabaseReader {
let (reader, releaseReader) = try readerPool.get()
reader.async { db in
defer {
try? db.commit() // Ignore commit error
// 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)
}
do {
@@ -700,7 +684,7 @@ 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 {
guard let readerPool else {
@@ -802,7 +786,7 @@ extension DatabasePool: DatabaseWriter {
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
@@ -818,22 +802,32 @@ extension DatabasePool: DatabaseWriter {
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
let dbAccess = CancellableDatabaseAccess()
return try await dbAccess.withCancellableContinuation { continuation in
asyncBarrierWriteWithoutTransaction { dbResult in
do {
try dbAccess.checkCancellation()
let db = try dbResult.get()
let result = try dbAccess.inDatabase(db) {
try updates(db)
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
// Pool.barrier does not support async calls (yet?).
// So we perform cancellation checks just as in
// the async version of SerializedDatabase.execute().
let cancelMutex = Mutex<(@Sendable () -> Void)?>(nil)
return try await withTaskCancellationHandler {
try Task.checkCancellation()
return try await readerPool.barrier {
try Task.checkCancellation()
return try writer.sync { db in
defer {
cancelMutex.store(nil)
db.uncancel()
}
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
cancelMutex.store(db.cancel)
try Task.checkCancellation()
return try updates(db)
}
}
} onCancel: {
cancelMutex.withLock { $0?() }
}
}
@@ -956,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.
+20 -8
View File
@@ -234,7 +234,7 @@ extension DatabaseQueue: DatabaseReader {
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute { db in
try db.isolated(readOnly: true) {
@@ -248,8 +248,14 @@ extension DatabaseQueue: DatabaseReader {
) {
writer.async { db in
defer {
// Ignore error because we can not notify it.
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()
}
@@ -272,7 +278,7 @@ extension DatabaseQueue: DatabaseReader {
}
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute(value)
}
@@ -296,8 +302,14 @@ extension DatabaseQueue: DatabaseReader {
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
defer {
// Ignore error because we can not notify it.
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()
}
@@ -385,7 +397,7 @@ extension DatabaseQueue: DatabaseWriter {
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
@@ -396,7 +408,7 @@ extension DatabaseQueue: DatabaseWriter {
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
+6 -6
View File
@@ -22,14 +22,14 @@ import Dispatch
/// ### Reading from the Database
///
/// - ``read(_:)-3806d``
/// - ``read(_:)-4d1da``
/// - ``read(_:)-5mfwu``
/// - ``readPublisher(receiveOn:value:)``
/// - ``asyncRead(_:)``
///
/// ### Unsafe Methods
///
/// - ``unsafeRead(_:)-5i7tf``
/// - ``unsafeRead(_:)-5gsav``
/// - ``unsafeRead(_:)-90w0p``
/// - ``unsafeReentrantRead(_:)``
/// - ``asyncUnsafeRead(_:)``
///
@@ -215,7 +215,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: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T
/// Schedules read-only database operations for execution, and
@@ -319,7 +319,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: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T
/// Schedules database operations for execution, and returns immediately.
@@ -652,7 +652,7 @@ extension AnyDatabaseReader: DatabaseReader {
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await base.read(value)
}
@@ -669,7 +669,7 @@ extension AnyDatabaseReader: DatabaseReader {
}
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await base.unsafeRead(value)
}
+2 -2
View File
@@ -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
+6 -2
View File
@@ -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: Database, 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: Database, 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: Database,
inView view: DatabaseObjectID
) throws -> [String]?
}
extension DatabaseSchemaSource {
public func columnsForPrimaryKey(
_ db: Database,
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: Database, 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
}
}
+10 -3
View File
@@ -113,7 +113,14 @@ public final class DatabaseSnapshot {
deinit {
// Leave snapshot isolation
reader.reentrantSync { db in
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)
}
}
@@ -152,7 +159,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await reader.execute(value)
}
@@ -173,7 +180,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
// `DatabaseSnapshotReader`, because of
// <https://github.com/apple/swift/issues/74469>.
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await read(value)
}
+22 -30
View File
@@ -1,11 +1,14 @@
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
@@ -294,36 +297,25 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
let dbAccess = CancellableDatabaseAccess()
return try await dbAccess.withCancellableContinuation { continuation in
readerPool.asyncGet { result in
do {
let (reader, releaseReader) = try result.get()
// Second async jump because that's how `Pool.async` has to be used.
reader.async { db in
defer {
releaseReader(self.poolCompletion(db))
}
do {
let result = try dbAccess.inDatabase(db) {
try value(db)
}
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
}
}
} catch {
continuation.resume(throwing: error)
}
}
let (reader, releaseReader) = try await readerPool.get()
var readerCompletion: PoolCompletion?
defer {
// readerCompletion might be null in cancelled database accesses
releaseReader(readerCompletion ?? .reuse)
}
let (result, completion) = try await reader.execute { db in
let result = Result { try value(db) }
let completion = poolCompletion(db)
return (result, completion)
}
readerCompletion = completion
return try result.get()
}
public func asyncRead(
@@ -353,7 +345,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
// `DatabaseSnapshotReader`, because of
// <https://github.com/apple/swift/issues/74469>.
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await read(value)
}
+7 -4
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
+12 -12
View File
@@ -22,18 +22,18 @@ import Dispatch
/// ### Writing into the Database
///
/// - ``write(_:)-76inz``
/// - ``write(_:)-3db50``
/// - ``write(_:)-4gnqx``
/// - ``writePublisher(receiveOn:updates:)``
/// - ``writePublisher(receiveOn:updates:thenRead:)``
/// - ``writeWithoutTransaction(_:)-4qh1w``
/// - ``writeWithoutTransaction(_:)-67mri``
/// - ``writeWithoutTransaction(_:)-18zhj``
/// - ``asyncWrite(_:completion:)``
/// - ``asyncWriteWithoutTransaction(_:)``
///
/// ### Exclusive Access to the Database
///
/// - ``barrierWriteWithoutTransaction(_:)-280j1``
/// - ``barrierWriteWithoutTransaction(_:)-48d63``
/// - ``barrierWriteWithoutTransaction(_:)-11q6c``
/// - ``asyncBarrierWriteWithoutTransaction(_:)``
///
/// ### Reading from the Latest Committed Database State
@@ -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: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T
/// Executes database operations, and returns their result after they have
@@ -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: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T
/// Schedules database operations for execution, and returns immediately.
@@ -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: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await writeWithoutTransaction { db in
var result: T?
@@ -665,7 +665,7 @@ extension DatabaseWriter {
try await writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Creates a new database file at the specified path with a minimum
/// amount of disk space.
///
@@ -885,7 +885,7 @@ extension AnyDatabaseWriter: DatabaseReader {
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await base.read(value)
}
@@ -902,7 +902,7 @@ extension AnyDatabaseWriter: DatabaseReader {
}
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (Database) throws -> T
) async throws -> T {
try await base.unsafeRead(value)
}
@@ -936,7 +936,7 @@ extension AnyDatabaseWriter: DatabaseWriter {
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await base.writeWithoutTransaction(updates)
}
@@ -947,7 +947,7 @@ extension AnyDatabaseWriter: DatabaseWriter {
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (Database) throws -> T
) async throws -> T {
try await base.barrierWriteWithoutTransaction(updates)
}
+53
View File
@@ -0,0 +1,53 @@
#if os(Linux)
@preconcurrency import Dispatch
#else
import Dispatch
#endif
/// An actor that runs in a DispatchQueue.
///
/// Inspired by <https://forums.swift.org/t/using-dispatchqueue-as-actors-serial-executor-under-linux/75260/3>
actor DispatchQueueActor {
private let executor: DispatchQueueExecutor
/// - precondition: the queue is serial, or flags contains `.barrier`.
init(queue: DispatchQueue, flags: DispatchWorkItemFlags = []) {
self.executor = DispatchQueueExecutor(queue: queue, flags: flags)
}
nonisolated var unownedExecutor: UnownedSerialExecutor {
executor.asUnownedSerialExecutor()
}
func execute<T>(_ work: () throws -> T) rethrows -> T {
try work()
}
}
private final class DispatchQueueExecutor: SerialExecutor {
private let queue: DispatchQueue
private let flags: DispatchWorkItemFlags
init(queue: DispatchQueue, flags: DispatchWorkItemFlags) {
self.queue = queue
self.flags = flags
}
func enqueue(_ job: UnownedJob) {
queue.async(flags: flags) {
job.runSynchronously(on: self.asUnownedSerialExecutor())
}
}
func asUnownedSerialExecutor() -> UnownedSerialExecutor {
UnownedSerialExecutor(ordinary: self)
}
func checkIsolated() {
dispatchPrecondition(condition: .onQueue(queue))
}
}
#if os(Linux)
extension DispatchQueueExecutor: @unchecked Sendable {}
#endif
+365 -117
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
@@ -52,6 +55,8 @@ import Foundation
/// - ``subscript(_:)-9c1fw``
/// - ``subscript(_:)-3jhwm``
/// - ``subscript(_:)-7krrg``
/// - ``decode(_:atIndex:)-33ykh``
/// - ``decode(_:atIndex:)-3btwn``
/// - ``withUnsafeData(atIndex:_:)``
/// - ``dataNoCopy(atIndex:)``
///
@@ -61,7 +66,8 @@ import Foundation
/// - ``subscript(_:)-4k8od``
/// - ``subscript(_:)-9rbo7``
/// - ``coalesce(_:)-359k7``
/// - ``coalesce(_:)-6nbah``
/// - ``decode(_:forColumn:)-4i1o4``
/// - ``decode(_:forColumn:)-4rhs4``
/// - ``withUnsafeData(named:_:)``
/// - ``dataNoCopy(named:)``
///
@@ -70,6 +76,9 @@ import Foundation
/// - ``subscript(_:)-9txgm``
/// - ``subscript(_:)-2esg7``
/// - ``subscript(_:)-wl9a``
/// - ``coalesce(_:)-6nbah``
/// - ``decode(_:forColumn:)-1ljuo``
/// - ``decode(_:forColumn:)-47qeg``
/// - ``withUnsafeData(at:_:)``
/// - ``dataNoCopy(_:)``
///
@@ -84,6 +93,10 @@ import Foundation
/// - ``subscript(_:)-8god3``
/// - ``subscript(_:)-jwnx``
/// - ``subscript(_:)-6ge6t``
/// - ``decode(_:forKey:)-9bbd3``
/// - ``decode(_:forKey:)-2w6lc``
/// - ``decode(_:forKey:)-2soc2``
/// - ``decodeIfPresent(_:forKey:)``
/// - ``PrefetchedRowsView``
/// - ``ScopesTreeView``
/// - ``ScopesView``
@@ -119,6 +132,10 @@ import Foundation
///
/// - ``RowAdapter``
///
/// ### Errors
///
/// - ``RowDecodingError``
///
/// ### Supporting Types
///
/// - ``RowCursor``
@@ -452,7 +469,7 @@ extension Row {
/// ```
@inlinable
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value {
try! decode(Value.self, forKey: columnName)
try! decode(Value.self, forColumn: columnName)
}
/// Returns the value at given column, converted to the requested type.
@@ -489,7 +506,7 @@ extension Row {
/// ```
@inlinable
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value {
try! decode(Value.self, forKey: columnName)
try! decode(Value.self, forColumn: columnName)
}
/// Returns `Int64`, `Double`, `String`, `Data` or nil, depending on the
@@ -533,7 +550,7 @@ extension Row {
/// ```
@inlinable
public subscript<Value: DatabaseValueConvertible>(_ column: some ColumnExpression) -> Value {
try! decode(Value.self, forKey: column.name)
try! decode(Value.self, forColumn: column)
}
/// Returns the value at given column, converted to the requested type.
@@ -573,7 +590,7 @@ extension Row {
-> Value
where Value: DatabaseValueConvertible & StatementColumnConvertible
{
try! decode(Value.self, forKey: column.name)
try! decode(Value.self, forColumn: column)
}
/// Calls the given closure with the `Data` at given index.
@@ -739,12 +756,13 @@ extension Row {
// MARK: - Extracting Records
/// The record associated to the given scope.
/// Returns the record associated to the given key.
///
/// Row scopes can be defined manually, with ``ScopeAdapter``.
/// The ``JoinableRequest/including(required:)`` and
/// ``JoinableRequest/including(optional:)`` request methods define scopes
/// named after the key of included associations between record types.
/// The key is a row scope that was either defined manually, with
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
/// and ``JoinableRequest/including(optional:)`` request methods. The
/// latter define row scopes named after the key of included
/// associations between record types.
///
/// A breadth-first search is performed in all available scopes in the row,
/// recursively.
@@ -769,26 +787,28 @@ extension Row {
/// let request = Book
/// .including(required: Book.author
/// .including(required: Author.country))
/// let bookRow = try Row.fetchOne(db, request)!
/// let row = try Row.fetchOne(db, request)!
///
/// let book = try Book(row: bookRow)
/// let author: Author = bookRow["author"]
/// let country: Country = bookRow["country"]
/// let book = try Book(row: row)
/// let author: Author = row["author"]
/// let country: Country = row["country"]
/// ```
///
/// See also: ``scopesTree``
/// For more details about row scopes, see ``ScopeAdapter``,
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
///
/// - parameter scope: A scope identifier.
public subscript<Record: FetchableRecord>(_ scope: String) -> Record {
try! decode(Record.self, forKey: scope)
}
/// The eventual record associated to the given scope.
/// Returns the eventual record associated to the given key.
///
/// Row scopes can be defined manually, with ``ScopeAdapter``.
/// The ``JoinableRequest/including(required:)`` and
/// ``JoinableRequest/including(optional:)`` request methods define scopes
/// named after the key of included associations between record types.
/// The key is a row scope that was either defined manually, with
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
/// and ``JoinableRequest/including(optional:)`` request methods. The
/// latter define row scopes named after the key of included
/// associations between record types.
///
/// A breadth-first search is performed in all available scopes in the row,
/// recursively.
@@ -809,25 +829,26 @@ extension Row {
///
/// struct Country: TableRecord, FetchableRecord { }
///
/// // Fetch a book, with its author, and the country of its author.
/// // Fetch a book, with its eventual author, and the country of its author.
/// let request = Book
/// .including(optional: Book.author
/// .including(optional: Author.country))
/// let bookRow = try Row.fetchOne(db, request)!
/// let row = try Row.fetchOne(db, request)!
///
/// let book = try Book(row: bookRow)
/// let author: Author? = bookRow["author"]
/// let country: Country? = bookRow["country"]
/// let book = try Book(row: row)
/// let author: Author? = row["author"]
/// let country: Country? = row["country"]
/// ```
///
/// See also: ``scopesTree``
/// For more details about row scopes, see ``ScopeAdapter``,
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
///
/// - parameter scope: A scope identifier.
public subscript<Record: FetchableRecord>(_ scope: String) -> Record? {
try! decodeIfPresent(Record.self, forKey: scope)
}
/// A collection of prefetched records associated to the given
/// Returns a collection of prefetched records associated to the given
/// association key.
///
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
@@ -843,10 +864,10 @@ extension Row {
/// struct Book: TableRecord, FetchableRecord { }
///
/// let request = Author.including(all: Author.books)
/// let authorRow = try Row.fetchOne(db, request)!
/// let row = try Row.fetchOne(db, request)!
///
/// let author = try Author(row: authorRow)
/// let books: [Book] = author["books"]
/// let author = try Author(row: row)
/// let books: [Book] = row["books"]
/// ```
///
/// See also: ``prefetchedRows``
@@ -861,7 +882,8 @@ extension Row {
try! decode(Records.self, forKey: key)
}
/// A set prefetched records associated to the given association key.
/// Returns the set of prefetched records associated to the given
/// association key.
///
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
/// request method.
@@ -876,10 +898,10 @@ extension Row {
/// struct Book: TableRecord, FetchableRecord, Hashable { }
///
/// let request = Author.including(all: Author.books)
/// let authorRow = try Row.fetchOne(db, request)!
/// let row = try Row.fetchOne(db, request)!
///
/// let author = try Author(row: authorRow)
/// let books: Set<Book> = author["books"]
/// let author = try Author(row: row)
/// let books: Set<Book> = row["books"]
/// ```
///
/// See also: ``prefetchedRows``
@@ -935,7 +957,8 @@ extension Row {
/// // Prints [code:"US" name:"United States of America"]
/// ```
///
/// See also ``scopesTree``.
/// For more details about row scopes, see ``ScopeAdapter``,
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
public var scopes: ScopesView {
impl.scopes(prefetchedRows: prefetchedRows)
}
@@ -1065,10 +1088,28 @@ extension Row {
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
/// rightmost column.
///
/// If the SQLite value is NULL, or if the conversion fails, a
/// `RowDecodingError` is thrown.
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42")!
/// let score = try row.decode(Int.self, atIndex: 0) // 42
/// let score: Int = try row.decode(atIndex: 0) // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")!
/// let name = try row.decode(String.self, atIndex: 0) // "Alice"
/// let name: String = try row.decode(atIndex: 0) // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL")!
/// let name: String? = try row.decode(atIndex: 0) // nil
/// ```
///
/// - throws: Any error that happens during the decoding.
@inlinable
func decode<Value: DatabaseValueConvertible>(
public func decode<Value: DatabaseValueConvertible>(
_ type: Value.Type = Value.self,
atIndex index: Int)
throws -> Value
@@ -1082,13 +1123,37 @@ extension Row {
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// If the row does not contain the column, or if the SQLite value is NULL,
/// or if the SQLite value can not be converted to `Value`, a
/// `RowDecodingError` is thrown.
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
/// let score = try row.decode(Int.self, forColumn: "score") // 42
/// let score: Int = try row.decode(forColumn: "score") // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name = try row.decode(String.self, forColumn: "name") // "Alice"
/// let name: String = try row.decode(forColumn: "name") // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// let name: String? = try row.decode(forColumn: "name") // nil
/// ```
///
/// When the column does not exist, nil is returned:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String? = try row.decode(forColumn: "missing") // nil
/// ```
///
/// - throws: Any error that happens during the decoding.
@inlinable
func decode<Value: DatabaseValueConvertible>(
public func decode<Value: DatabaseValueConvertible>(
_ type: Value.Type = Value.self,
forKey columnName: String)
forColumn columnName: String)
throws -> Value
{
guard let index = index(forColumn: columnName) else {
@@ -1100,6 +1165,47 @@ extension Row {
}
return try Value.decode(fromRow: self, atUncheckedIndex: index)
}
/// Returns the value at given column, converted to the requested type.
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
/// let score = try row.decode(Int.self, forColumn: Column("score")) // 42
/// let score: Int = try row.decode(forColumn: Column("score")) // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name = try row.decode(String.self, forColumn: Column("name")) // "Alice"
/// let name: String = try row.decode(forColumn: Column("name")) // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// let name: String? = try row.decode(forColumn: Column("name")) // nil
/// ```
///
/// When the column does not exist, nil is returned:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String? = try row.decode(forColumn: Column("missing")) // nil
/// ```
///
/// - throws: Any error that happens during the decoding.
@inlinable
public func decode<Value: DatabaseValueConvertible>(
_ type: Value.Type = Value.self,
forColumn column: some ColumnExpression)
throws -> Value
{
try decode(type, forColumn: column.name)
}
}
// MARK: - Throwing DatabaseValueConvertible & StatementColumnConvertible Decoding Methods
@@ -1114,11 +1220,29 @@ extension Row {
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
/// rightmost column.
///
/// If the SQLite value is NULL, or if the conversion fails, a
/// `RowDecodingError` is thrown.
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42")!
/// let score = try row.decode(Int.self, atIndex: 0) // 42
/// let score: Int = try row.decode(atIndex: 0) // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")!
/// let name = try row.decode(String.self, atIndex: 0) // "Alice"
/// let name: String = try row.decode(atIndex: 0) // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL")!
/// let name: String? = try row.decode(atIndex: 0) // nil
/// ```
///
/// - throws: Any error that happens during the decoding.
@inline(__always)
@inlinable
func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
public func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type = Value.self,
atIndex index: Int)
throws -> Value
@@ -1136,13 +1260,37 @@ extension Row {
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// If the row does not contain the column, or if the SQLite value is NULL,
/// or if the SQLite value can not be converted to `Value`, a
/// `RowDecodingError` is thrown.
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
/// let score = try row.decode(Int.self, forColumn: "score") // 42
/// let score: Int = try row.decode(forColumn: "score") // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name = try row.decode(String.self, forColumn: "name") // "Alice"
/// let name: String = try row.decode(forColumn: "name") // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// let name: String? = try row.decode(forColumn: "name") // nil
/// ```
///
/// When the column does not exist, nil is returned:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String? = try row.decode(forColumn: "missing") // nil
/// ```
///
/// - throws: Any error that happens during the decoding.
@inlinable
func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
public func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type = Value.self,
forKey columnName: String)
forColumn columnName: String)
throws -> Value
{
guard let index = index(forColumn: columnName) else {
@@ -1155,6 +1303,51 @@ extension Row {
return try Value.fastDecode(fromRow: self, atUncheckedIndex: index)
}
/// Returns the value at given column, converted to the requested type.
///
/// This method exists as an optimization opportunity for types that adopt
/// ``StatementColumnConvertible``. It can trigger [SQLite built-in
/// conversions](https://www.sqlite.org/datatype3.html).
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
/// let score = try row.decode(Int.self, forColumn: Column("score")) // 42
/// let score: Int = try row.decode(forColumn: Column("score")) // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name = try row.decode(String.self, forColumn: Column("name")) // "Alice"
/// let name: String = try row.decode(forColumn: Column("name")) // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// let name: String? = try row.decode(forColumn: Column("name")) // nil
/// ```
///
/// When the column does not exist, nil is returned:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String? = try row.decode(forColumn: Column("missing")) // nil
/// ```
///
/// - throws: Any error that happens during the decoding.
@inlinable
public func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type = Value.self,
forColumn column: some ColumnExpression)
throws -> Value
{
try decode(type, forColumn: column.name)
}
// Support for fast decoding in scoped rows
@usableFromInline
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
@@ -1187,37 +1380,51 @@ extension Row {
// MARK: - Throwing Record Decoding Methods
extension Row {
/// Returns the eventual record associated with the given scope.
/// Returns the eventual record associated to the given key.
///
/// The key is a row scope that was either defined manually, with
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
/// and ``JoinableRequest/including(optional:)`` request methods. The
/// latter define row scopes named after the key of included
/// associations between record types.
///
/// A breadth-first search is performed in all available scopes in the row,
/// recursively.
///
/// The result is nil if the scope is not available, or contains only
/// `NULL` values.
///
/// For example:
///
/// let request = Book.including(optional: Book.author)
/// let row = try Row.fetchOne(db, request)!
/// ```swift
/// struct Book: TableRecord, FetchableRecord {
/// static let author = belongsTo(Author.self)
/// }
///
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
/// struct Author: TableRecord, FetchableRecord {
/// static let country = belongsTo(Country.self)
/// }
///
/// let author: Author? = row["author"]
/// print(author.name)
/// // Prints "Herman Melville"
/// struct Country: TableRecord, FetchableRecord { }
///
/// Associated records stored in nested associations are available, too:
/// // Fetch a book, with its eventual author, and the country of its author.
/// let request = Book
/// .including(optional: Book.author
/// .including(optional: Author.country))
/// let row = try Row.fetchOne(db, request)!
///
/// let request = Book.including(optional: Book.author.including(optional: Author.country))
/// let row = try Row.fetchOne(db, request)!
/// let book = try Book(row: row)
/// let author: Author? = try row.decode(forKey: "author")
/// let country: Country? = try row.decode(forKey: "country")
/// ```
///
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
/// For more details about row scopes, see ``ScopeAdapter``,
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
///
/// let country: Country? = row["country"]
/// print(country.name)
/// // Prints "United States"
///
/// Nil is returned if the scope is not available, or contains only
/// null values.
///
/// See ``splittingRowAdapters(columnCounts:)`` for a sample code.
func decodeIfPresent<Record: FetchableRecord>(
/// - parameter type: The decoded type.
/// - parameter scope: A scope identifier.
/// - throws: Any error that happens during the decoding.
public func decodeIfPresent<Record: FetchableRecord>(
_ type: Record.Type = Record.self,
forKey scope: String)
throws -> Record?
@@ -1228,37 +1435,48 @@ extension Row {
return try Record(row: scopedRow)
}
/// Returns the record associated with the given scope.
/// Returns the record associated to the given key.
///
/// The key is a row scope that was either defined manually, with
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
/// and ``JoinableRequest/including(optional:)`` request methods. The
/// latter define row scopes named after the key of included
/// associations between record types.
///
/// A breadth-first search is performed in all available scopes in the row,
/// recursively.
///
/// For example:
///
/// let request = Book.including(required: Book.author)
/// let row = try Row.fetchOne(db, request)!
/// ```swift
/// struct Book: TableRecord, FetchableRecord {
/// static let author = belongsTo(Author.self)
/// }
///
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
/// struct Author: TableRecord, FetchableRecord {
/// static let country = belongsTo(Country.self)
/// }
///
/// let author: Author = row["author"]
/// print(author.name)
/// // Prints "Herman Melville"
/// struct Country: TableRecord, FetchableRecord { }
///
/// Associated records stored in nested associations are available, too:
/// // Fetch a book, with its author, and the country of its author.
/// let request = Book
/// .including(required: Book.author
/// .including(required: Author.country))
/// let row = try Row.fetchOne(db, request)!
///
/// let request = Book.including(required: Book.author.including(required: Author.country))
/// let row = try Row.fetchOne(db, request)!
/// let book = try Book(row: row)
/// let author: Author = try row.decode(forKey: "author")
/// let country: Country = try row.decode(forKey: "country")
/// ```
///
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
/// For more details about row scopes, see ``ScopeAdapter``,
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
///
/// let country: Country = row["country"]
/// print(country.name)
/// // Prints "United States"
///
/// A fatal error is raised if the scope is not available, or contains only
/// null values.
///
/// See ``splittingRowAdapters(columnCounts:)`` for a sample code.
func decode<Record: FetchableRecord>(
/// - parameter type: The decoded type.
/// - parameter scope: A scope identifier.
/// - throws: Any error that happens during the decoding.
public func decode<Record: FetchableRecord>(
_ type: Record.Type = Record.self,
forKey scope: String)
throws -> Record
@@ -1300,20 +1518,34 @@ extension Row {
// MARK: - Throwing Record RangeReplaceableCollection and Set Methods
extension Row {
/// Returns the records encoded in the given prefetched rows.
/// Returns a collection of prefetched records associated to the given
/// association key.
///
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
/// request method.
///
/// For example:
///
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
/// ```swift
/// struct Author: TableRecord, FetchableRecord {
/// static let books = hasMany(Book.self)
/// }
///
/// try print(Author(row: row).name)
/// // Prints "Herman Melville"
/// struct Book: TableRecord, FetchableRecord { }
///
/// let books: [Book] = row["books"]
/// print(books[0].title)
/// // Prints "Moby-Dick"
func decode<Collection>(
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
///
/// let author = try Author(row: row)
/// let books: [Book] = try row.decode(forKey: "books")
/// ```
///
/// See also: ``prefetchedRows``
///
/// - parameter type: The type of the decoded collection.
/// - parameter key: An association key.
/// - throws: Any error that happens during the decoding.
public func decode<Collection>(
_ type: Collection.Type = Collection.self,
forKey key: String)
throws -> Collection
@@ -1321,6 +1553,7 @@ extension Row {
Collection: RangeReplaceableCollection,
Collection.Element: FetchableRecord
{
// TODO: test independently
guard let rows = prefetchedRows[key] else {
let availableKeys = prefetchedRows.keys
if availableKeys.isEmpty {
@@ -1351,24 +1584,39 @@ extension Row {
return collection
}
/// Returns the set of records encoded in the given prefetched rows.
/// Returns the set of prefetched records associated to the given
/// association key.
///
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
/// request method.
///
/// For example:
///
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
/// ```swift
/// struct Author: TableRecord, FetchableRecord {
/// static let books = hasMany(Book.self)
/// }
///
/// try print(Author(row: row).name)
/// // Prints "Herman Melville"
/// struct Book: TableRecord, FetchableRecord, Hashable { }
///
/// let books: Set<Book> = row["books"]
/// print(books.first!.title)
/// // Prints "Moby-Dick"
func decode<Record: FetchableRecord & Hashable>(
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
///
/// let author = try Author(row: row)
/// let books: Set<Book> = try row.decode(forKey: "books")
/// ```
///
/// See also: ``prefetchedRows``
///
/// - parameter type: The type of the decoded set.
/// - parameter key: An association key.
/// - throws: Any error that happens during the decoding.
public func decode<Record: FetchableRecord & Hashable>(
_ type: Set<Record>.Type = Set<Record>.self,
forKey key: String)
throws -> Set<Record>
{
// TODO: test independently
guard let rows = prefetchedRows[key] else {
let availableKeys = prefetchedRows.keys
if availableKeys.isEmpty {
+39 -20
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
@@ -23,9 +26,21 @@ enum RowKey: Hashable, Sendable {
case prefetchKey(String)
}
/// A decoding error
@usableFromInline
enum RowDecodingError: Error {
/// A decoding error thrown when decoding a database row.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// // RowDecodingError: could not decode String from database value NULL.
/// let name = try row.decode(String.self, forColumn: "name")
/// ```
public struct RowDecodingError: Error {
enum Impl {
case keyNotFound(RowKey, Context)
case valueMismatch(Any.Type, Context)
}
@usableFromInline
struct Context: CustomDebugStringConvertible, Sendable {
/// A description of what went wrong, for debugging purposes.
@@ -55,17 +70,19 @@ enum RowDecodingError: Error {
}
}
case keyNotFound(RowKey, Context)
case valueMismatch(Any.Type, Context)
var impl: Impl
var context: Context {
switch self {
switch impl {
case .keyNotFound(_, let context),
.valueMismatch(_, let context):
return context
}
}
static func valueMismatch(_ type: Any.Type, _ context: Context) -> Self {
self.init(impl: .valueMismatch(type, context))
}
/// Convenience method that builds the
/// `could not decode <Type> from database value <value>` error message.
static func valueMismatch(
@@ -74,11 +91,10 @@ enum RowDecodingError: Error {
databaseValue: DatabaseValue)
-> Self
{
valueMismatch(
type,
RowDecodingError.Context(decodingContext: context, debugDescription: """
could not decode \(type) from database value \(databaseValue)
"""))
let context = RowDecodingError.Context(decodingContext: context, debugDescription: """
could not decode \(type) from database value \(databaseValue)
""")
return self.init(impl: .valueMismatch(type, context))
}
/// Convenience method that builds the
@@ -115,11 +131,15 @@ enum RowDecodingError: Error {
/// error message.
@usableFromInline
static func columnNotFound(_ columnName: String, context: RowDecodingContext) -> Self {
keyNotFound(
self.init(impl: .keyNotFound(
.columnName(columnName),
RowDecodingError.Context(decodingContext: context, debugDescription: """
column not found: \(String(reflecting: columnName))
"""))
""")))
}
static func keyNotFound(_ rowKey: RowKey, _ context: Context) -> Self {
self.init(impl: .keyNotFound(rowKey, context))
}
}
@@ -167,8 +187,7 @@ struct RowDecodingContext {
}
extension RowDecodingError: CustomStringConvertible {
@usableFromInline
var description: String {
public var description: String {
let context = self.context
let row = context.row
var chunks: [String] = []
+18 -116
View File
@@ -5,6 +5,9 @@ final class SerializedDatabase {
/// The database connection
private let db: Database
/// The actor that performs asynchronous accesses
private let actor: DispatchQueueActor
/// The database configuration
var configuration: Configuration { db.configuration }
@@ -55,6 +58,8 @@ final class SerializedDatabase {
} else {
self.queue = configuration.makeWriterDispatchQueue(label: identifier)
}
self.actor = DispatchQueueActor(queue: queue)
SchedulingWatchdog.allowDatabase(db, onQueue: queue)
try queue.sync {
do {
@@ -245,20 +250,22 @@ final class SerializedDatabase {
/// Asynchrously executes the block.
func execute<T: Sendable>(
_ block: @escaping @Sendable (Database) throws -> T
_ block: @Sendable (Database) throws -> T
) async throws -> T {
let dbAccess = CancellableDatabaseAccess()
return try await dbAccess.withCancellableContinuation { continuation in
self.async { db in
do {
let result = try dbAccess.inDatabase(db) {
try block(db)
}
continuation.resume(returning: result)
} catch {
continuation.resume(throwing: error)
let cancelMutex = Mutex<(@Sendable () -> Void)?>(nil)
return try await withTaskCancellationHandler {
try await actor.execute {
defer {
cancelMutex.store(nil)
db.uncancel()
preconditionNoUnsafeTransactionLeft(db)
}
cancelMutex.store(db.cancel)
try Task.checkCancellation()
return try block(db)
}
} onCancel: {
cancelMutex.withLock { $0?() }
}
}
@@ -305,108 +312,3 @@ final class SerializedDatabase {
// It happens the job of SerializedDatabase is precisely to provide thread-safe
// access to `Database`.
extension SerializedDatabase: @unchecked Sendable { }
// MARK: - Task Cancellation Support
enum DatabaseAccessCancellationState: @unchecked Sendable {
// @unchecked Sendable because database is only accessed from its
// dispatch queue.
case notConnected
case connected(Database)
case cancelled
case expired
}
typealias CancellableDatabaseAccess = Mutex<DatabaseAccessCancellationState>
/// Supports Task cancellation in async database accesses.
///
/// Usage:
///
/// ```swift
/// let dbAccess = CancellableDatabaseAccess()
/// return try dbAccess.withCancellableContinuation { continuation in
/// asyncDatabaseAccess { db in
/// do {
/// let result = try dbAccess.inDatabase(db) {
/// // Perform database operations
/// }
/// continuation.resume(returning: result)
/// } catch {
/// continuation.resume(throwing: error)
/// }
/// }
/// }
/// ```
extension CancellableDatabaseAccess: DatabaseCancellable {
convenience init() {
self.init(.notConnected)
}
func cancel() {
withLock { state in
switch state {
case let .connected(db):
db.cancel()
state = .cancelled
case .notConnected:
state = .cancelled
case .cancelled, .expired:
break
}
}
}
func withCancellableContinuation<Value>(
_ fn: (UnsafeContinuation<Value, any Error>) -> Void
) async throws -> Value {
try await withTaskCancellationHandler {
try checkCancellation()
return try await withUnsafeThrowingContinuation { continuation in
fn(continuation)
}
} onCancel: {
cancel()
}
}
func checkCancellation() throws {
try withLock { state in
if case .cancelled = state {
throw CancellationError()
}
}
}
/// Wraps a full database access with cancellation support. When this
/// method returns, the database is NOT cancelled.
func inDatabase<Value>(_ db: Database, execute work: () throws -> Value) throws -> Value {
try withLock { state in
switch state {
case .connected, .expired:
fatalError("Can't use a CancellableDatabaseAccess twice")
case .notConnected:
state = .connected(db)
case .cancelled:
throw CancellationError()
}
}
return try throwingFirstError {
try work()
} finally: {
let cancelled = withLock { state in
if case .cancelled = state {
db.uncancel()
return true
} else {
state = .expired
return false
}
}
if cancelled {
throw CancellationError()
}
}
}
}
+8 -5
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
@@ -141,7 +144,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)
+7 -4
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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)
+7 -4
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
+3 -1
View File
@@ -1,5 +1,8 @@
#if canImport(CoreGraphics)
import CoreGraphics
#elseif !canImport(Darwin)
import Foundation
#endif
/// CGFloat adopts DatabaseValueConvertible
extension CGFloat: DatabaseValueConvertible {
@@ -15,4 +18,3 @@ extension CGFloat: DatabaseValueConvertible {
return CGFloat(double)
}
}
#endif
+7 -4
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
+7 -6
View File
@@ -1,15 +1,17 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
#if !os(Linux)
/// NSDate is stored in the database using the format
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
extension NSDate: DatabaseValueConvertible {
@@ -38,7 +40,6 @@ extension NSDate: DatabaseValueConvertible {
return cast(date)
}
}
#endif
/// Date is stored in the database using the format
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
+7 -6
View File
@@ -1,11 +1,13 @@
#if !os(Linux)
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
@@ -65,4 +67,3 @@ extension Decimal: StatementColumnConvertible {
@usableFromInline
let _posixLocale = Locale(identifier: "en_US_POSIX")
#endif
@@ -1,4 +1,3 @@
#if !os(Linux)
import Foundation
/// NSData is convertible to and from DatabaseValue.
@@ -24,4 +23,3 @@ extension NSData: DatabaseValueConvertible {
return cast(data)
}
}
#endif
+11 -3
View File
@@ -1,4 +1,4 @@
#if !os(Linux) && !os(Windows)
#if !os(Windows)
import Foundation
private let integerRoundingBehavior = NSDecimalNumberHandler(
@@ -81,10 +81,18 @@ extension NSNumber: DatabaseValueConvertible {
/// Otherwise, returns nil.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
switch dbValue.storage {
case .int64(let int64) where self is NSDecimalNumber.Type:
let number = NSDecimalNumber(value: int64)
return number as? Self
case .int64(let int64):
return self.init(value: int64)
let number = NSNumber(value: int64)
return number as? Self
case .double(let double) where self is NSDecimalNumber.Type:
let number = NSDecimalNumber(value: double)
return number as? Self
case .double(let double):
return self.init(value: double)
let number = NSNumber(value: double)
return number as? Self
case let .string(string):
// Must match Decimal.fromDatabaseValue(_:)
guard let decimal = Decimal(string: string, locale: posixLocale) else { return nil }
@@ -1,4 +1,3 @@
#if !os(Linux)
import Foundation
/// NSString adopts DatabaseValueConvertible
@@ -24,4 +23,3 @@ extension NSString: DatabaseValueConvertible {
return self.init(string: string)
}
}
#endif
+6 -2
View File
@@ -1,12 +1,16 @@
import Foundation
#if !os(Linux) && !os(Windows)
#if !os(Windows)
/// NSURL stores its absoluteString in the database.
extension NSURL: DatabaseValueConvertible {
/// Returns a TEXT database value containing the absolute URL.
public var databaseValue: DatabaseValue {
absoluteString?.databaseValue ?? .null
#if !canImport(Darwin)
absoluteString.databaseValue
#else
absoluteString?.databaseValue ?? .null
#endif
}
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
+19 -9
View File
@@ -1,15 +1,18 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
#if !os(Linux) && !os(Windows)
#if !os(Windows)
/// NSUUID adopts DatabaseValueConvertible
extension NSUUID: DatabaseValueConvertible {
/// Returns a BLOB database value containing the uuid bytes.
@@ -33,10 +36,17 @@ extension NSUUID: DatabaseValueConvertible {
switch dbValue.storage {
case .blob(let data) where data.count == 16:
return data.withUnsafeBytes {
self.init(uuidBytes: $0.bindMemory(to: UInt8.self).baseAddress)
#if canImport(Darwin)
self.init(uuidBytes: $0.bindMemory(to: UInt8.self).baseAddress)
#else
guard let uuidBytes = $0.bindMemory(to: UInt8.self).baseAddress else {
return nil as Self?
}
return NSUUID(uuidBytes: uuidBytes) as? Self
#endif
}
case .string(let string):
return self.init(uuidString: string)
return NSUUID(uuidString: string) as? Self
default:
return nil
}
@@ -88,8 +98,8 @@ extension UUID: StatementColumnConvertible {
self.init(uuid: uuid.uuid)
case SQLITE_BLOB:
guard sqlite3_column_bytes(sqliteStatement, index) == 16,
let blob = sqlite3_column_blob(sqliteStatement, index) else
{
let blob = sqlite3_column_blob(sqliteStatement, index)
else {
return nil
}
self.init(uuid: blob.assumingMemoryBound(to: uuid_t.self).pointee)
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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 {
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
+16 -13
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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 {
@@ -1252,16 +1255,16 @@ private struct CopiedDatabaseEventImpl: DatabaseEventImpl {
public struct DatabasePreUpdateEvent {
/// An event kind
public enum Kind: CInt {
/// SQLITE_INSERT
case insert = 18
/// An event kind.
public enum Kind: CInt, Sendable {
/// An insertion event
case insert = 18 // SQLITE_INSERT
/// SQLITE_DELETE
case delete = 9
/// A deletion event
case delete = 9 // SQLITE_DELETE
/// SQLITE_UPDATE
case update = 23
/// An update event
case update = 23 // SQLITE_UPDATE
}
/// The event kind
@@ -1494,7 +1497,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)
+8 -17
View File
@@ -1,11 +1,14 @@
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
@@ -16,18 +19,6 @@ 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.
+8 -2
View File
@@ -1,4 +1,4 @@
#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
@@ -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)
+1 -1
View File
@@ -97,7 +97,7 @@ try dbQueue.write { db in
}
```
See ``DatabaseReader/read(_:)-4d1da`` and ``DatabaseWriter/write(_:)-3db50``.
See ``DatabaseReader/read(_:)-5mfwu`` and ``DatabaseWriter/write(_:)-4gnqx``.
Note the identical method names: `read`, `write`. The async version is only available in async Swift functions.
@@ -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``
+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
@@ -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/
+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: Database, 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
+1 -1
View File
@@ -324,7 +324,7 @@ extension Database {
}
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 {
+7 -4
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
+7 -4
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
+7 -4
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
+7 -4
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
+7 -4
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
+2 -2
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+
+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
+11 -8
View File
@@ -1,11 +1,14 @@
#if SQLITE_ENABLE_FTS5
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
@@ -117,8 +120,8 @@ public struct FTS5 {
///
/// 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
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)
+7 -4
View File
@@ -1,11 +1,14 @@
#if SQLITE_ENABLE_FTS5
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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.
+8 -5
View File
@@ -1,11 +1,14 @@
#if SQLITE_ENABLE_FTS5
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
@@ -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
+7 -4
View File
@@ -1,11 +1,14 @@
#if SQLITE_ENABLE_FTS5
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
@@ -154,7 +154,7 @@ extension SQLSpecificExpressible {
}
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
extension SQLJSONExpressible {
/// The `->>` SQL operator.
///
+1 -1
View File
@@ -1,4 +1,4 @@
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
// MARK: - JSON
extension Database {
+156 -14
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:
///
@@ -214,6 +214,107 @@ public struct DatabaseMigrator: Sendable {
_ identifier: String,
foreignKeyChecks: ForeignKeyChecks = .deferred,
migrate: @escaping @Sendable (Database) 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: Database, _ 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
@@ -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,32 +594,52 @@ 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 {
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)
}
}
}
+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: Database, _ 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: Database, 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: Database) throws {
if mergedIdentifiers.isEmpty == false {
try db.execute(literal: "DELETE FROM grdb_migrations WHERE identifier IN \(mergedIdentifiers)")
}
}
private func runWithImmediateForeignKeysChecks(_ db: Database, 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: Database, 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: Database, 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: Database) throws {
try deleteMergedIdentifiers(db)
try db.execute(literal: "INSERT INTO grdb_migrations (identifier) VALUES (\(identifier))")
}
}
@@ -305,13 +305,13 @@ extension AssociationToOne {
///
/// ### Building Association Aggregates
///
/// - ``average(_:)-4n3up``
/// - ``average(_:)-1ehdb``
/// - ``count``
/// - ``isEmpty``
/// - ``max(_:)-1upp8``
/// - ``min(_:)-7xc49``
/// - ``sum(_:)-5p74s``
/// - ``total(_:)-hudm``
/// - ``max(_:)-a32j``
/// - ``min(_:)-41jp8``
/// - ``sum(_:)-47yg7``
/// - ``total(_:)-6dd9d``
///
/// - ``AssociationAggregate``
///
@@ -179,11 +179,11 @@ extension AssociationToMany {
/// }
/// ```
public func average(
_ expression: (DatabaseComponents) -> some SQLSpecificExpressible
) -> AssociationAggregate<OriginRowDecoder>
_ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible
) rethrows -> AssociationAggregate<OriginRowDecoder>
where RowDecoder: TableRecord
{
average(expression(RowDecoder.databaseComponents))
try average(expression(RowDecoder.databaseComponents))
}
/// Returns the maximum value of the given expression in associated records.
@@ -276,11 +276,11 @@ extension AssociationToMany {
/// }
/// ```
public func max(
_ expression: (DatabaseComponents) -> some SQLSpecificExpressible
) -> AssociationAggregate<OriginRowDecoder>
_ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible
) rethrows -> AssociationAggregate<OriginRowDecoder>
where RowDecoder: TableRecord
{
max(expression(RowDecoder.databaseComponents))
try max(expression(RowDecoder.databaseComponents))
}
/// Returns the minimum value of the given expression in associated records.
@@ -373,11 +373,11 @@ extension AssociationToMany {
/// }
/// ```
public func min(
_ expression: (DatabaseComponents) -> some SQLSpecificExpressible
) -> AssociationAggregate<OriginRowDecoder>
_ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible
) rethrows -> AssociationAggregate<OriginRowDecoder>
where RowDecoder: TableRecord
{
min(expression(RowDecoder.databaseComponents))
try min(expression(RowDecoder.databaseComponents))
}
/// Returns the sum of the given expression in associated records.
@@ -434,7 +434,7 @@ extension AssociationToMany {
/// Returns the sum of the given expression in associated records.
///
/// This aggregate invokes the `SUM` SQL function.
/// See also ``AssociationToMany/total(_:)-hudm`` and
/// See also ``AssociationToMany/total(_:)-6dd9d`` and
/// <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
///
/// For example:
@@ -478,11 +478,11 @@ extension AssociationToMany {
/// }
/// ```
public func sum(
_ expression: (DatabaseComponents) -> some SQLSpecificExpressible
) -> AssociationAggregate<OriginRowDecoder>
_ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible
) rethrows -> AssociationAggregate<OriginRowDecoder>
where RowDecoder: TableRecord
{
sum(expression(RowDecoder.databaseComponents))
try sum(expression(RowDecoder.databaseComponents))
}
/// Returns the sum of the given expression in associated records.
@@ -541,7 +541,7 @@ extension AssociationToMany {
/// Returns the sum of the given expression in associated records.
///
/// This aggregate invokes the `TOTAL` SQL function.
/// See also ``AssociationToMany/sum(_:)-5p74s`` and
/// See also ``AssociationToMany/sum(_:)-47yg7`` and
/// <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
///
/// For example:
@@ -585,11 +585,11 @@ extension AssociationToMany {
/// }
/// ```
public func total(
_ expression: (DatabaseComponents) -> some SQLSpecificExpressible
) -> AssociationAggregate<OriginRowDecoder>
_ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible
) rethrows -> AssociationAggregate<OriginRowDecoder>
where RowDecoder: TableRecord
{
total(expression(RowDecoder.databaseComponents))
try total(expression(RowDecoder.databaseComponents))
}
}
@@ -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.
@@ -57,7 +57,7 @@
/// ### Changing The Type of Fetched Results
///
/// - ``asRequest(of:)``
/// - ``select(_:as:)-74lsr``
/// - ``select(_:as:)-4cj9h``
/// - ``select(literal:as:)``
/// - ``select(sql:arguments:as:)``
/// - ``selectID()``
@@ -228,12 +228,12 @@ extension QueryInterfaceRequest: SelectionRequest {
///
/// Any previous selection is discarded.
public func select<T>(
_ selection: (DatabaseComponents) -> any SQLSelectable,
as type: T.Type = T.self)
-> QueryInterfaceRequest<T>
_ selection: (DatabaseComponents) throws -> any SQLSelectable,
as type: T.Type = T.self
) rethrows -> QueryInterfaceRequest<T>
where RowDecoder: TableRecord
{
select(selection).asRequest(of: T.self)
try select(selection).asRequest(of: T.self)
}
/// Defines the result columns with an SQL string, and defines the type of
@@ -362,11 +362,13 @@ 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)
}
@@ -633,15 +635,18 @@ extension QueryInterfaceRequest {
@discardableResult
public func deleteAll(_ db: Database) 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:
@@ -702,8 +707,8 @@ extension QueryInterfaceRequest {
/// - precondition: The result of `select` is not empty.
public func deleteAndFetchStatement(
_ db: Database,
select: (DatabaseComponents) -> [any SQLSelectable])
throws -> Statement
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> Statement
where RowDecoder: TableRecord
{
try deleteAndFetchStatement(db, selection: select(RowDecoder.databaseComponents))
@@ -887,8 +892,8 @@ extension QueryInterfaceRequest {
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func deleteAndFetchStatement(
_ db: Database,
select: (DatabaseComponents) -> [any SQLSelectable])
throws -> Statement
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> Statement
where RowDecoder: TableRecord
{
try deleteAndFetchStatement(db, selection: select(RowDecoder.databaseComponents))
@@ -1059,7 +1064,7 @@ extension QueryInterfaceRequest {
public func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignment: (DatabaseComponents) -> ColumnAssignment
assignment: (DatabaseComponents) throws -> ColumnAssignment
) throws -> Int
where RowDecoder: TableRecord
{
@@ -1094,7 +1099,7 @@ extension QueryInterfaceRequest {
public func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) -> [ColumnAssignment]
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> Int
where RowDecoder: TableRecord
{
@@ -1133,8 +1138,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.
@@ -1168,7 +1176,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:
@@ -1208,9 +1216,9 @@ extension QueryInterfaceRequest {
public func updateAndFetchStatement(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) -> [ColumnAssignment],
select: (DatabaseComponents) -> [any SQLSelectable])
throws -> Statement
assignments: (DatabaseComponents) throws -> [ColumnAssignment],
select: (DatabaseComponents) -> [any SQLSelectable]
) throws -> Statement
where RowDecoder: TableRecord
{
try updateAndFetchStatement(
@@ -1303,8 +1311,8 @@ extension QueryInterfaceRequest {
public func updateAndFetchCursor(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) -> [ColumnAssignment])
throws -> RecordCursor<RowDecoder>
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
{
try updateAndFetchCursor(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
@@ -1382,8 +1390,8 @@ extension QueryInterfaceRequest {
public func updateAndFetchAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) -> [ColumnAssignment])
throws -> [RowDecoder]
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
{
try updateAndFetchAll(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
@@ -1453,8 +1461,8 @@ extension QueryInterfaceRequest {
public func updateAndFetchSet(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) -> [ColumnAssignment])
throws -> Set<RowDecoder>
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
{
try updateAndFetchSet(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
@@ -1532,9 +1540,9 @@ extension QueryInterfaceRequest {
public func updateAndFetchStatement(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) -> [ColumnAssignment],
select: (DatabaseComponents) -> [any SQLSelectable])
throws -> Statement
assignments: (DatabaseComponents) throws -> [ColumnAssignment],
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> Statement
where RowDecoder: TableRecord
{
try updateAndFetchStatement(
@@ -1629,8 +1637,8 @@ extension QueryInterfaceRequest {
public func updateAndFetchCursor(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) -> [ColumnAssignment])
throws -> RecordCursor<RowDecoder>
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
{
try updateAndFetchCursor(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
@@ -1710,8 +1718,8 @@ extension QueryInterfaceRequest {
public func updateAndFetchAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) -> [ColumnAssignment])
throws -> [RowDecoder]
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
{
try updateAndFetchAll(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
@@ -1783,8 +1791,8 @@ extension QueryInterfaceRequest {
public func updateAndFetchSet(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) -> [ColumnAssignment])
throws -> Set<RowDecoder>
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
{
try updateAndFetchSet(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
@@ -22,11 +22,11 @@ public protocol TypedRequest<RowDecoder> {
///
/// ### The SELECT Clause
///
/// - ``annotated(with:)-56y26``
/// - ``annotated(with:)-9nuwi``
/// - ``annotated(with:)-9wodv``
/// - ``annotated(with:)-69r3``
/// - ``annotatedWhenConnected(with:)``
/// - ``select(_:)-90gu2``
/// - ``select(_:)-4iv1w``
/// - ``select(_:)-270ge``
/// - ``select(_:)-4jw13``
/// - ``select(literal:)``
/// - ``select(sql:arguments:)``
/// - ``selectWhenConnected(_:)``
@@ -246,9 +246,9 @@ extension SelectionRequest where Self: TypedRequest, Self.RowDecoder: TableRecor
/// .select(\.score)
/// ```
public func select(
_ selection: (DatabaseComponents) -> any SQLSelectable
) -> Self {
select(selection(Self.RowDecoder.databaseComponents))
_ selection: (DatabaseComponents) throws -> any SQLSelectable
) rethrows -> Self {
try select(selection(Self.RowDecoder.databaseComponents))
}
/// Defines the result columns.
@@ -276,9 +276,9 @@ extension SelectionRequest where Self: TypedRequest, Self.RowDecoder: TableRecor
/// .select { [$0.score] }
/// ```
public func select(
_ selection: (DatabaseComponents) -> [any SQLSelectable]
) -> Self {
select(selection(Self.RowDecoder.databaseComponents))
_ selection: (DatabaseComponents) throws -> [any SQLSelectable]
) rethrows -> Self {
try select(selection(Self.RowDecoder.databaseComponents))
}
/// Appends a result column to the selected columns.
@@ -302,9 +302,9 @@ extension SelectionRequest where Self: TypedRequest, Self.RowDecoder: TableRecor
/// - parameter selection: A closure that accepts a database connection and
/// returns an array of result columns.
public func annotated(
with selection: (DatabaseComponents) -> any SQLSelectable
) -> Self {
annotated(with: selection(Self.RowDecoder.databaseComponents))
with selection: (DatabaseComponents) throws -> any SQLSelectable
) rethrows -> Self {
try annotated(with: selection(Self.RowDecoder.databaseComponents))
}
/// Appends result columns to the selected columns.
@@ -328,9 +328,9 @@ extension SelectionRequest where Self: TypedRequest, Self.RowDecoder: TableRecor
/// - parameter selection: A closure that accepts a database connection and
/// returns an array of result columns.
public func annotated(
with selection: (DatabaseComponents) -> [any SQLSelectable]
) -> Self {
annotated(with: selection(Self.RowDecoder.databaseComponents))
with selection: (DatabaseComponents) throws -> [any SQLSelectable]
) rethrows -> Self {
try annotated(with: selection(Self.RowDecoder.databaseComponents))
}
}
@@ -346,7 +346,7 @@ extension SelectionRequest where Self: TypedRequest, Self.RowDecoder: TableRecor
/// ### The WHERE and JOIN ON Clauses
///
/// - ``all()``
/// - ``filter(_:)-5l0gu``
/// - ``filter(_:)-7j0nw``
/// - ``filter(literal:)``
/// - ``filter(sql:arguments:)``
/// - ``filterWhenConnected(_:)``
@@ -463,9 +463,9 @@ extension FilteredRequest where Self: TypedRequest, Self.RowDecoder: TableRecord
/// let request = Player.all().filter { $0.name == name }
/// ```
public func filter(
_ predicate: (DatabaseComponents) -> any SQLSpecificExpressible
) -> Self {
filter(predicate(Self.RowDecoder.databaseComponents))
_ predicate: (DatabaseComponents) throws -> any SQLSpecificExpressible
) rethrows -> Self {
try filter(predicate(Self.RowDecoder.databaseComponents))
}
}
@@ -826,10 +826,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() }
@@ -964,15 +971,15 @@ extension TableRequest where Self: AggregatingRequest {
///
/// ### The GROUP BY Clause
///
/// - ``group(_:)-9z116``
/// - ``group(_:)-43p07``
/// - ``group(_:)-5soxm``
/// - ``group(_:)-32exm``
/// - ``group(literal:)``
/// - ``group(sql:arguments:)``
/// - ``groupWhenConnected(_:)``
///
/// ### The HAVING Clause
///
/// - ``having(_:)-6zfvb``
/// - ``having(_:)-27hlo``
/// - ``having(literal:)``
/// - ``having(sql:arguments:)``
/// - ``havingWhenConnected(_:)``
@@ -1199,16 +1206,16 @@ extension AggregatingRequest where Self: TypedRequest, Self.RowDecoder: TableRec
///
/// Any previous grouping is discarded.
public func group(
_ expression: (DatabaseComponents) -> any SQLExpressible
) -> Self {
group(expression(Self.RowDecoder.databaseComponents))
_ expression: (DatabaseComponents) throws -> any SQLExpressible
) rethrows -> Self {
try group(expression(Self.RowDecoder.databaseComponents))
}
/// Returns an aggregate request grouped on the given SQL expressions.
public func group(
_ expressions: (DatabaseComponents) -> [any SQLExpressible]
) -> Self {
group(expressions(Self.RowDecoder.databaseComponents))
_ expressions: (DatabaseComponents) throws -> [any SQLExpressible]
) rethrows -> Self {
try group(expressions(Self.RowDecoder.databaseComponents))
}
/// Filters the aggregated groups with a boolean SQL expression.
@@ -1233,9 +1240,9 @@ extension AggregatingRequest where Self: TypedRequest, Self.RowDecoder: TableRec
/// .having { max($0.score) > 1000 }
/// ```
public func having(
_ predicate: (DatabaseComponents) -> any SQLExpressible
) -> Self {
having(predicate(Self.RowDecoder.databaseComponents))
_ predicate: (DatabaseComponents) throws -> any SQLExpressible
) rethrows -> Self {
try having(predicate(Self.RowDecoder.databaseComponents))
}
}
@@ -1247,8 +1254,8 @@ extension AggregatingRequest where Self: TypedRequest, Self.RowDecoder: TableRec
///
/// ### The ORDER BY Clause
///
/// - ``order(_:)-54bt8``
/// - ``order(_:)-7jcay``
/// - ``order(_:)-5q7wj``
/// - ``order(_:)-711zj``
/// - ``order(literal:)``
/// - ``order(sql:arguments:)``
/// - ``orderWhenConnected(_:)``
@@ -1454,9 +1461,9 @@ extension OrderedRequest where Self: TypedRequest, Self.RowDecoder: TableRecord
/// .order(\.name)
/// ```
public func order(
_ ordering: (DatabaseComponents) -> any SQLOrderingTerm
) -> Self {
order(ordering(Self.RowDecoder.databaseComponents))
_ ordering: (DatabaseComponents) throws -> any SQLOrderingTerm
) rethrows -> Self {
try order(ordering(Self.RowDecoder.databaseComponents))
}
/// Sorts the fetched rows according to the given SQL ordering terms.
@@ -1485,9 +1492,9 @@ extension OrderedRequest where Self: TypedRequest, Self.RowDecoder: TableRecord
/// .order { [$0.name] }
/// ```
public func order(
_ orderings: (DatabaseComponents) -> [any SQLOrderingTerm]
) -> Self {
order(orderings(Self.RowDecoder.databaseComponents))
_ orderings: (DatabaseComponents) throws -> [any SQLOrderingTerm]
) rethrows -> Self {
try order(orderings(Self.RowDecoder.databaseComponents))
}
}
@@ -1800,12 +1807,12 @@ extension JoinableRequest where Self: SelectionRequest {
///
/// ### The SELECT Clause
///
/// - ``SelectionRequest/annotated(with:)-56y26``
/// - ``SelectionRequest/annotated(with:)-9nuwi``
/// - ``SelectionRequest/annotated(with:)-9wodv``
/// - ``SelectionRequest/annotated(with:)-69r3``
/// - ``SelectionRequest/annotatedWhenConnected(with:)``
/// - ``distinct()``
/// - ``SelectionRequest/select(_:)-90gu2``
/// - ``SelectionRequest/select(_:)-4iv1w``
/// - ``SelectionRequest/select(_:)-270ge``
/// - ``SelectionRequest/select(_:)-4jw13``
/// - ``SelectionRequest/select(literal:)``
/// - ``SelectionRequest/select(sql:arguments:)``
/// - ``SelectionRequest/selectWhenConnected(_:)``
@@ -1813,7 +1820,7 @@ extension JoinableRequest where Self: SelectionRequest {
/// ### The WHERE Clause
///
/// - ``FilteredRequest/all()``
/// - ``FilteredRequest/filter(_:)-5l0gu``
/// - ``FilteredRequest/filter(_:)-7j0nw``
/// - ``TableRequest/filter(id:)``
/// - ``TableRequest/filter(ids:)``
/// - ``TableRequest/filter(key:)-1p9sq``
@@ -1829,21 +1836,21 @@ extension JoinableRequest where Self: SelectionRequest {
///
/// ### The GROUP BY and HAVING Clauses
///
/// - ``AggregatingRequest/group(_:)-9z116``
/// - ``AggregatingRequest/group(_:)-43p07``
/// - ``AggregatingRequest/group(_:)-5soxm``
/// - ``AggregatingRequest/group(_:)-32exm``
/// - ``AggregatingRequest/group(literal:)``
/// - ``AggregatingRequest/group(sql:arguments:)``
/// - ``TableRequest/groupByPrimaryKey()``
/// - ``AggregatingRequest/groupWhenConnected(_:)``
/// - ``AggregatingRequest/having(_:)-6zfvb``
/// - ``AggregatingRequest/having(_:)-27hlo``
/// - ``AggregatingRequest/having(literal:)``
/// - ``AggregatingRequest/having(sql:arguments:)``
/// - ``AggregatingRequest/havingWhenConnected(_:)``
///
/// ### The ORDER BY Clause
///
/// - ``OrderedRequest/order(_:)-54bt8``
/// - ``OrderedRequest/order(_:)-7jcay``
/// - ``OrderedRequest/order(_:)-5q7wj``
/// - ``OrderedRequest/order(_:)-711zj``
/// - ``OrderedRequest/order(literal:)``
/// - ``OrderedRequest/order(sql:arguments:)``
/// - ``OrderedRequest/orderWhenConnected(_:)``
+7 -7
View File
@@ -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)
@@ -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 {
@@ -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 {
@@ -123,7 +123,7 @@ struct SQLForeignKeyRequest {
}
private func tableType(_ db: Database, for name: String) throws -> TableType? {
for schemaID in try db.schemaIdentifiers() {
for schemaID in try db.fetchSchemaIdentifiers() {
if try db.schema(schemaID).containsObjectNamed(name, ofType: .table) {
return TableType(isView: false)
}
+5 -5
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:
@@ -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:
+5 -3
View File
@@ -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 }
+4 -4
View File
@@ -1932,8 +1932,8 @@ extension Table {
public func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignment: (DatabaseComponents) -> ColumnAssignment)
throws -> Int
assignment: (DatabaseComponents) throws -> ColumnAssignment
) throws -> Int
where RowDecoder: TableRecord
{
try updateAll(db, onConflict: conflictResolution, [assignment(RowDecoder.databaseComponents)])
@@ -1968,8 +1968,8 @@ extension Table {
public func updateAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) -> [ColumnAssignment])
throws -> Int
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> Int
where RowDecoder: TableRecord
{
try updateAll(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
@@ -120,7 +120,7 @@ struct SQLTableGenerator {
var tableOptions: [String] = []
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
if options.contains(.strict) {
tableOptions.append("STRICT")
}
@@ -290,6 +290,12 @@ extension TableAliasBase {
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#table-aliases> for more information and examples.
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
/// ## Topics
///
/// ## Supporting Types
///
/// - ``TableAliasBase``
@dynamicMemberLookup
public final class TableAlias<RowDecoder>: TableAliasBase, @unchecked Sendable {
init(tableName: String, userName: String? = nil)
@@ -350,7 +350,7 @@ public final class ColumnDefinition {
return self
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Defines the column as a generated column.
///
/// For example:
@@ -79,7 +79,7 @@ public final class TableAlteration {
alterations.append(.addColumnLiteral(literal))
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Renames a column.
///
/// For example:
@@ -15,7 +15,7 @@ public struct TableOptions: OptionSet, Sendable {
/// Such tables can not be tracked with <doc:DatabaseObservation> tools.
public static let withoutRowID = TableOptions(rawValue: 1 << 2)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Creates a [STRICT](https://www.sqlite.org/stricttables.html) table.
public static let strict = TableOptions(rawValue: 1 << 3)
#else
@@ -78,9 +78,9 @@ extension TableRecord {
/// let request = Player.select(\.score)
/// ```
public static func select(
_ selection: (DatabaseComponents) -> any SQLSelectable
) -> QueryInterfaceRequest<Self> {
all().select(selection)
_ selection: (DatabaseComponents) throws -> any SQLSelectable
) rethrows -> QueryInterfaceRequest<Self> {
try all().select(selection)
}
/// Returns a request that selects the provided result columns.
@@ -94,9 +94,9 @@ extension TableRecord {
/// let request = Player.select { [$0.id, $0.score] }
/// ```
public static func select(
_ selection: (DatabaseComponents) -> [any SQLSelectable]
) -> QueryInterfaceRequest<Self> {
all().select(selection)
_ selection: (DatabaseComponents) throws -> [any SQLSelectable]
) rethrows -> QueryInterfaceRequest<Self> {
try all().select(selection)
}
/// Returns a request that selects the provided SQL string.
@@ -217,11 +217,11 @@ extension TableRecord {
/// let maxScore = try request.fetchOne(db) // Int?
/// ```
public static func select<RowDecoder>(
_ selection: (DatabaseComponents) -> any SQLSelectable,
as type: RowDecoder.Type = RowDecoder.self)
-> QueryInterfaceRequest<RowDecoder>
_ selection: (DatabaseComponents) throws -> any SQLSelectable,
as type: RowDecoder.Type = RowDecoder.self
) rethrows -> QueryInterfaceRequest<RowDecoder>
{
all().select(selection, as: type)
try all().select(selection, as: type)
}
/// Returns a request that selects the provided SQL string, and defines the
@@ -395,9 +395,9 @@ extension TableRecord {
/// let request = Player.annotated { ($0.score + $0.bonus).forKey("totalScore") }
/// ```
public static func annotated(
with selection: (DatabaseComponents) -> any SQLSelectable
) -> QueryInterfaceRequest<Self> {
all().annotated(with: selection)
with selection: (DatabaseComponents) throws -> any SQLSelectable
) rethrows -> QueryInterfaceRequest<Self> {
try all().annotated(with: selection)
}
/// Returns a request with the provided result columns appended to the
@@ -415,9 +415,9 @@ extension TableRecord {
/// let request = Player.annotated { [($0.score + $0.bonus).forKey("totalScore")] }
/// ```
public static func annotated(
with selection: (DatabaseComponents) -> [any SQLSelectable]
) -> QueryInterfaceRequest<Self> {
all().annotated(with: selection)
with selection: (DatabaseComponents) throws -> [any SQLSelectable]
) rethrows -> QueryInterfaceRequest<Self> {
try all().annotated(with: selection)
}
// Accept SQLSpecificExpressible instead of SQLExpressible, so that we
@@ -453,9 +453,9 @@ extension TableRecord {
/// let request = Player.filter { $0.name == name }
/// ```
public static func filter(
_ predicate: (DatabaseComponents) -> any SQLSpecificExpressible
) -> QueryInterfaceRequest<Self> {
all().filter(predicate)
_ predicate: (DatabaseComponents) throws -> any SQLSpecificExpressible
) rethrows -> QueryInterfaceRequest<Self> {
try all().filter(predicate)
}
/// Returns a request filtered by primary key.
@@ -632,9 +632,9 @@ extension TableRecord {
/// let request = Player.order(\.score.desc)
/// ```
public static func order(
_ orderings: (DatabaseComponents) -> any SQLOrderingTerm
) -> QueryInterfaceRequest<Self> {
all().order(orderings)
_ orderings: (DatabaseComponents) throws -> any SQLOrderingTerm
) rethrows -> QueryInterfaceRequest<Self> {
try all().order(orderings)
}
/// Returns a request sorted according to the given SQL ordering terms.
@@ -648,9 +648,9 @@ extension TableRecord {
/// let request = Player.order { [$0.score.desc, $0.name] }
/// ```
public static func order(
_ orderings: (DatabaseComponents) -> [any SQLOrderingTerm]
) -> QueryInterfaceRequest<Self> {
all().order(orderings)
_ orderings: (DatabaseComponents) throws -> [any SQLOrderingTerm]
) rethrows -> QueryInterfaceRequest<Self> {
try all().order(orderings)
}
/// Returns a request sorted by primary key.
+1 -1
View File
@@ -39,7 +39,7 @@ import Foundation // For JSONEncoder
/// - ``databaseChanges(from:)``
/// - ``databaseChanges(modify:)``
/// - ``databaseEquals(_:)``
public protocol EncodableRecord {
public protocol EncodableRecord: GRDBSendableMetatype {
/// Encodes the record into the provided persistence container.
///
/// In your implementation of this method, store in the `container` argument
+22 -23
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#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
@@ -212,20 +215,20 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
// swiftlint:disable comma
// swiftlint:disable line_length
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: String.Type, forKey key: Key) throws -> String { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
func decode(_ type: String.Type, forKey key: Key) throws -> String { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
// swiftlint:enable line_length
// swiftlint:enable comma
@@ -519,20 +522,16 @@ private struct SingleValueRowDecoder<R: FetchableRecord>: SingleValueDecodingCon
func decode(_ type: Int16.Type) throws -> Int16 { try columnDecoder.decode(type) }
func decode(_ type: Int32.Type) throws -> Int32 { try columnDecoder.decode(type) }
func decode(_ type: Int64.Type) throws -> Int64 { try columnDecoder.decode(type) }
#if compiler(>=6)
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
func decode(_ type: Int128.Type) throws -> Int128 { try columnDecoder.decode(type) }
#endif
func decode(_ type: UInt.Type) throws -> UInt { try columnDecoder.decode(type) }
func decode(_ type: UInt8.Type) throws -> UInt8 { try columnDecoder.decode(type) }
func decode(_ type: UInt16.Type) throws -> UInt16 { try columnDecoder.decode(type) }
func decode(_ type: UInt32.Type) throws -> UInt32 { try columnDecoder.decode(type) }
func decode(_ type: UInt64.Type) throws -> UInt64 { try columnDecoder.decode(type) }
#if compiler(>=6)
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
func decode(_ type: UInt128.Type) throws -> UInt128 { try columnDecoder.decode(type) }
#endif
func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
if let type = T.self as? any FetchableRecord.Type {
// Prefer FetchableRecord decoding over Decodable.
@@ -53,7 +53,10 @@ extension MutablePersistableRecord {
// Nil primary key
return false
}
try statement.execute()
return db.changesCount > 0
var changesCount = 0
try db.countChanges(&changesCount, forTable: type(of: self).databaseTableName) {
try statement.execute()
}
return changesCount > 0
}
}
@@ -90,7 +90,7 @@ extension MutablePersistableRecord {
// MARK: - Insert and Fetch
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -329,8 +329,8 @@ extension MutablePersistableRecord {
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
fetch: (Statement) throws -> T,
select: (DatabaseComponents) -> [any SQLSelectable])
throws -> T
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> T
where Self: TableRecord
{
try insertAndFetch(db, onConflict: conflictResolution, selection: select(Self.databaseComponents), fetch: fetch)
@@ -578,8 +578,8 @@ extension MutablePersistableRecord {
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
fetch: (Statement) throws -> T,
select: (DatabaseComponents) -> [any SQLSelectable])
throws -> T
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> T
where Self: TableRecord
{
try insertAndFetch(
@@ -86,7 +86,7 @@ extension MutablePersistableRecord {
// MARK: - Save and Fetch
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
@@ -213,7 +213,7 @@ extension MutablePersistableRecord {
// MARK: - Update and Fetch
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Executes an `UPDATE RETURNING` statement on all columns, and returns a
/// new record built from the updated row.
///
@@ -839,7 +839,7 @@ extension MutablePersistableRecord {
// MARK: - Internals
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
@inlinable // allow specialization so that empty callbacks are removed
func updateChangesAndFetch<T>(
_ db: Database,
@@ -956,8 +956,11 @@ extension MutablePersistableRecord {
// Nil primary key
try dao.recordNotFound()
}
let returned = try fetch(statement)
if db.changesCount == 0 {
var changesCount = 0
let returned = try db.countChanges(&changesCount, forTable: type(of: self).databaseTableName) {
try fetch(statement)
}
if changesCount == 0 {
// No row was updated
try dao.recordNotFound()
}
@@ -1,7 +1,7 @@
// MARK: - Upsert
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Executes an `INSERT ON CONFLICT DO UPDATE` statement.
///
/// The upsert behavior is triggered by a violation of any uniqueness
@@ -184,6 +184,11 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord {
/// }
/// ```
///
/// - important: Due to an SQLite limitation, this callback is
/// unreliable when the record type writes into a database view
/// through an INSTEAD OF trigger. The `inserted.rowID` value is
/// not the rowid of the inserted row.
///
/// - parameter inserted: Information about the inserted row.
mutating func didInsert(_ inserted: InsertionSuccess)
+5 -5
View File
@@ -55,7 +55,7 @@ extension PersistableRecord {
// MARK: - Insert and Fetch
extension PersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -261,8 +261,8 @@ extension PersistableRecord {
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
fetch: (Statement) throws -> T,
select: (DatabaseComponents) -> [any SQLSelectable])
throws -> T
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> T
where Self: TableRecord
{
try insertAndFetch(db, onConflict: conflictResolution, selection: select(Self.databaseComponents), fetch: fetch)
@@ -476,8 +476,8 @@ extension PersistableRecord {
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
fetch: (Statement) throws -> T,
select: (DatabaseComponents) -> [any SQLSelectable])
throws -> T
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> T
where Self: TableRecord
{
try insertAndFetch(
+1 -1
View File
@@ -38,7 +38,7 @@ extension PersistableRecord {
// MARK: - Save and Fetch
extension PersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
Loaded 100 of 192 files, more files were not shown because too many files have changed in this diff. Show more