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
Gwendal Roué a5a1be26b4 Merge branch 'development' 2025-05-11 14:25:02 +02:00
Gwendal Roué b84d1eaeef v7.5.0 2025-05-11 14:23:56 +02:00
Gwendal Roué e7a35dde06 Extend Usage section 2025-05-11 14:23:04 +02:00
Gwendal Roué c2e6c86934 Warn against the independent observation of each element in a list. 2025-05-11 13:32:50 +02:00
Gwendal Roué 7c2cbfe814 Merge pull request #1759 from groue/dev/expression-builder
Build request with closures
2025-05-11 13:28:01 +02:00
Gwendal Roué 034b241e71 Rename ColumnsProvider to DatabaseComponents 2025-05-11 13:10:19 +02:00
Gwendal Roué 814146c40d DocC 2025-05-11 11:56:21 +02:00
Gwendal Roué fedcdef65e Fix typo 2025-05-11 11:21:48 +02:00
Gwendal Roué 2316fb3831 Prefer key paths when possible 2025-05-11 11:12:19 +02:00
Gwendal Roué 98e2812089 Convenience api for updating a single column 2025-05-11 10:58:09 +02:00
Gwendal Roué 8f6f1aa264 TODO 2025-05-11 10:57:28 +02:00
Gwendal Roué 96d04716c2 Update more documentation with the closure syntax 2025-05-11 10:57:20 +02:00
Gwendal Roué 004968517e Update more documentation with the closure syntax 2025-05-10 17:43:22 +02:00
Gwendal Roué f635aea2f2 Update more documentation with the closure syntax 2025-05-10 16:38:02 +02:00
Gwendal Roué 5c9b772e65 Test CommonTableExpression aliases on Swift 6.1 2025-05-10 16:37:44 +02:00
Gwendal Roué d6ff3b14d4 DocC 2025-05-10 15:34:10 +02:00
Gwendal Roué fac0c22ecb Documentation for generic TableAlias 2025-05-10 14:52:48 +02:00
Gwendal Roué 5461caff04 Tests for generic TableAlias 2025-05-10 14:52:48 +02:00
Gwendal Roué 6cc3116ff4 TableAlias is generic 2025-05-10 14:52:48 +02:00
Gwendal Roué 55edcff97f Extract TableAlias 2025-05-10 09:40:16 +02:00
Gwendal Roué 430141344d Update more documentation with the closure syntax 2025-05-10 09:36:14 +02:00
Gwendal Roué 0567f69e66 Update AssociationBasics.md with the closure syntax 2025-05-10 09:36:14 +02:00
Gwendal Roué be2fb76d77 DocC 2025-05-10 09:36:14 +02:00
Gwendal Roué 503fb09270 Test that aggregate can be expressed with key-paths in Swift 6.1 2025-05-10 09:36:14 +02:00
Gwendal Roué ec6042e9c7 Update Tour.playground with closure syntax 2025-05-10 09:36:14 +02:00
Gwendal Roué 190ccda727 Rename deleteAndFetchStatement(_:select:) for consistency 2025-05-10 09:36:14 +02:00
Gwendal Roué af1adff71d More closure syntax for requests in README 2025-05-10 09:36:14 +02:00
Gwendal Roué 43e103d5f8 Recommend GRDB7 for CocoaPods 2025-05-10 09:36:14 +02:00
Gwendal Roué 7b2e9d838a Swift 6.1 compiler: test key-path requests. 2025-05-10 09:36:14 +02:00
Gwendal Roué 6b0faede2a Use closure syntax for insertAndFetch 2025-05-10 09:36:14 +02:00
Gwendal Roué ed402d5de6 Use closure syntax for batch updates 2025-05-10 09:36:14 +02:00
Gwendal Roué db5c4cc458 Use closure syntax for requests in README 2025-05-10 09:36:14 +02:00
Gwendal Roué 352f77f225 Stop recommending String enums for Columns.
We now recommend:

    enum Columns {
        static let id = Column("id")
        static let title = Column("title")
        static let latitude = Column("latitude")
        static let longitude = Column("longitude")
    }

Instead of the previous recommendation:

    enum Columns: String, ColumnExpression {
        case id, title, latitude, longitude
    }

This is because SE-0438 does not support Metatype Keypaths for enums. A request like `Place.order(\.title)` does not compile with a String enum.
2025-05-10 09:36:14 +02:00
Gwendal Roué ed98ac30e0 DocC 2025-05-10 09:36:14 +02:00
Gwendal Roué 35fa28ab90 QueryInterfaceRequest.select(_:as:) with ColumnsProvider 2025-05-10 09:36:14 +02:00
Gwendal Roué a89bd88340 Prefer key paths over closures, except in tests
Don't use key paths in tests because they are Swift 6.1+ only
2025-05-10 09:36:14 +02:00
Gwendal Roué b01f6da3cf Remove TODO 2025-05-10 09:36:14 +02:00
Gwendal Roué e7fdd65072 deleteAndFetchStatement(_,selection:) with ColumnsProvider 2025-05-10 09:36:14 +02:00
Gwendal Roué ff15f30a3b select(_, as:) with ColumnsProvider 2025-05-10 09:36:14 +02:00
Gwendal Roué f69ca1a573 Build aggregates from ColumnsProvider 2025-05-10 09:36:14 +02:00
Gwendal Roué e8b143e2ee Demo app uses ColumnsProvider 2025-05-10 09:36:14 +02:00
Gwendal Roué 5e9b965bee Test requests built from ColumnsProvider 2025-05-10 09:36:13 +02:00
Gwendal Roué ce238b6643 Build requests from ColumnsProvider 2025-05-10 09:36:13 +02:00
Gwendal Roué 787393db18 Fix Swiftlint warning 2025-05-10 09:36:13 +02:00
Gwendal Roué 8774497f31 Modernize QueryInterfaceRequestTests with an inner Columns type
so that we can use the new SQLExpressionBuilder
2025-05-10 09:36:13 +02:00
Gwendal Roué 94e90e7e6c Columns and ColumnsProvider associated types of TableRecord 2025-05-10 09:36:13 +02:00
Gwendal Roué 9064717b8a Merge pull request #1764 from groue/dev/fts-pattern-initializers
Make it possible to create a raw FTS5Pattern without any database connection
2025-05-08 13:07:27 +02:00
Gwendal Roué 00f462292b Documentation 2025-05-08 12:50:19 +02:00
Gwendal Roué 5a0622e5b8 Tests for FTS5Pattern.init(rawPattern:allowedColumns:) 2025-05-08 12:48:24 +02:00
Gwendal Roué 596db46407 Make FTS5Pattern.init(rawPattern:allowedColumns:) public
Fix #1763
2025-05-08 12:47:21 +02:00
Gwendal Roué 0aaa2a4f37 Adjust wording about Linux 2025-04-26 17:31:40 +02:00
Gwendal Roué 04e73c26c4 v7.4.1 2025-03-28 08:17:58 +01:00
Gwendal Roué a71c1d6e80 Removed unnecessary TODO warning 2025-03-28 08:15:54 +01:00
Gwendal Roué 52b7b7bd26 Merge branch 'development' 2025-03-22 14:57:59 +01:00
Gwendal Roué 9a9d2e9993 v7.4.0 2025-03-22 14:16:44 +01:00
Gwendal Roué 1ce8e38bea Merge pull request #1747 from groue/dev/issue-1746
Transaction observers are not impacted by Task Cancellation
2025-03-22 13:43:07 +01:00
Gwendal Roué 67b34dc57c TransactionObserver can access the database, even if the transaction was completed in a cancelled task.
Fix https://github.com/groue/GRDB.swift/discussions/1746
2025-03-22 12:13:42 +01:00
Gwendal Roué 515bd78d28 Failing test for https://github.com/groue/GRDB.swift/discussions/1746 2025-03-22 12:12:12 +01:00
Gwendal Roué f2aa6b386f Improve the documentation for table recreation 2025-03-15 12:06:31 +01:00
Gwendal Roué 71e09a38d4 Document that migrations that rename foreign key columns should use immediate foreign key checks
Fix #1740
2025-03-15 12:06:14 +01:00
Gwendal Roué d800a79d5d Merge pull request #1745 from groue/dev/multi-argument-max
Add the MIN and MAX multi-argument SQL functions to the query interface
2025-03-15 11:32:20 +01:00
Gwendal Roué 4065ff58e8 Add the min and max multi-argument functions 2025-03-15 10:02:24 +01:00
Gwendal Roué 18eab53f74 Document aggregate functions 2025-03-15 09:51:32 +01:00
Gwendal Roué 6eba24d169 Merge branch 'development' 2025-02-23 19:53:59 +01:00
Gwendal Roué bd3ac9ef75 v7.3.0 2025-02-23 18:44:22 +01:00
Gwendal Roué 392137c357 XCTestExpectation is Sendable starting Xcode 16.3 beta 2025-02-23 18:43:45 +01:00
Gwendal Roué b48a56ae03 Revert "Merge pull request #1732 from groue/dev/sending-closures"
This reverts commit bbd1eab402, reversing
changes made to 9b09c5342e.
2025-02-23 18:43:45 +01:00
Gwendal Roué bbd1eab402 Merge pull request #1732 from groue/dev/sending-closures
Async database accesses no longer require Sendable closures.
2025-02-23 15:33:54 +01:00
Gwendal Roué 53c9d12d29 Async database access no longer require Sendable closures. 2025-02-23 15:16:36 +01:00
Gwendal Roué 9b09c5342e Merge pull request #1731 from groue/dev/virtual-table-options
Support for temporary virtual tables
2025-02-23 13:59:48 +01:00
Gwendal Roué aed22fe0bc Support for temporary virtual tables. 2025-02-23 13:45:46 +01:00
Gwendal Roué eec220b652 Merge pull request #1730 from groue/dev/issue-1728
Undeprecate Date coding strategies based on DateFormatter
2025-02-23 11:13:02 +01:00
Gwendal Roué 79a782038e Undeprecate Date coding strategies based on DateFormatter
https://github.com/swiftlang/swift/issues/78635#issuecomment-2676324549
> DateFormatter is indeed thread safe and its conformance to Sendable is correct
2025-02-23 11:12:24 +01:00
Gwendal Roué 618e72d153 Merge pull request #1729 from groue/dev/issue-1728
Deprecate Date coding strategies based on DateFormatter
2025-02-22 14:29:08 +01:00
Gwendal Roué 824100990f Deprecate Date coding strategies based on DateFormatter
Fix #1728
2025-02-22 13:45:42 +01:00
Gwendal Roué c7205b172f Merge branch 'development' 2025-02-12 08:49:02 +01:00
Gwendal Roué 49d14e6b66 v7.2.0 2025-02-12 08:48:52 +01:00
Gwendal Roué 54ed7ec611 Merge pull request #1719 from groue/dev/selectID
Select ids with selectID()
2025-02-12 08:46:40 +01:00
Gwendal Roué 68e17351ff CI: iPhone 15 Pro simulator is no longer available 2025-02-12 08:31:34 +01:00
Gwendal Roué 494e697e94 Warn against selectID() when the ID type is an optional. 2025-02-12 08:25:27 +01:00
Gwendal Roué 87b236dfe0 selectID
This reverts 7ffc332327

At the time, selectID was replaced with selectPrimaryKey(as:) because:

> Since Optional is a database value like others, selectID would be a request of optionals for records with an optional ID type:
>
>     struct Player: Identifiable, MutablePersistableRecord {
>         var id: Int64?
>     }
>
>     Player.selectID() // QueryInterface<Int64?>
>
> This is not good, because primary keys are not null. And those requests would fetch impractical types such as [Int64?], Set<Int64?>, Int64??.

This problem is reintroduced, but we now recommend against optional ids in https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices. And record with optional ids can use selectPrimaryKey(as:).
2025-02-11 20:47:49 +01:00
Gwendal Roué ea6d8e0123 Merge branch 'development' 2025-02-05 15:34:18 +01:00
Gwendal Roué 073209f1dc v7.1.0 2025-02-05 15:34:09 +01:00
Gwendal Roué 430530f5f1 CHANGELOG 2025-02-05 14:08:28 +01:00
Gwendal Roué a716915280 Merge pull request #1717 from groue/dev/RxGRDB
Allow RxGRDB to compile without warning
2025-02-05 13:58:25 +01:00
Gwendal Roué ef36727d9a 🎵 Whatever Lola wants, Lola gets
Address https://github.com/RxSwiftCommunity/RxGRDB/issues/72

Based on https://github.com/swiftlang/swift-evolution/blob/main/proposals/0337-support-incremental-migration-to-concurrency-checking.md#preconcurrency-attribute-on-nominal-declarations

See also https://www.massicotte.org/preconcurrency#working-with-swift-5

"Whatever Lola wants, Lola gets" because the Swift language is a blind and cruel mistress.
2025-02-05 13:38:19 +01:00
Gwendal Roué 78b2796f46 CHANGELOG 2025-02-05 08:00:29 +01:00
Gwendal Roué 3535a42c53 Merge pull request #1716 from groue/dev/issue-1715
Fix: DatabaseQueue restores its read/write abilities when an async read-only database access is cancelled.
2025-02-04 20:51:58 +01:00
Gwendal Roué 5a4d9b5cb9 Let PRAGMA QUERY_ONLY statements run from a cancelled database access
Fix #1715
2025-02-04 19:35:39 +01:00
Gwendal Roué a64b09d121 Failing test for #1715 2025-02-04 19:35:39 +01:00
Gwendal Roué 287c4be82d Merge pull request #1713 from groue/dev/sqliteLibVersionNumber
Expose `sqlite3_libversion_number` as `Database.sqliteLibVersionNumber`
2025-02-01 12:59:42 +01:00
Gwendal Roué 32c9ba24ba Replace sqlite3_libversion_number() with Database.sqliteLibVersionNumber
and remove SQLite imports that are no longer necessary.
2025-02-01 12:19:11 +01:00
Gwendal Roué 0401d449bb Database.sqliteLibVersionNumber 2025-02-01 12:01:41 +01:00
Gwendal Roué 4de97e6903 Merge branch 'development' 2025-01-26 16:30:56 +01:00
Gwendal Roué 676636bae4 7.0.0 2025-01-26 16:30:06 +01:00
Gwendal Roué 8e7cbf098f Fix Realm integration 2025-01-26 16:29:51 +01:00
Gwendal Roué 7250d759fe Fix generatePerformanceReport.rb script 2025-01-26 16:29:51 +01:00
Gwendal Roué fe7b9955b1 Upgrade performance tests dependencies 2025-01-26 16:29:51 +01:00
Gwendal Roué 6df8e2bd34 Fix casing of swiftpackageindex.com urls 2025-01-26 15:31:12 +01:00
Gwendal Roué 81cd33b71c CHANGELOG 2025-01-26 15:26:01 +01:00
Gwendal Roué 2e2c0eaec1 Merge pull request #1699 from groue/dev/jsonb
Support for JSONB expressions
2025-01-26 15:22:25 +01:00
Gwendal Roué ed17710694 Add tests of JSON_GROUP_ARRAY output, from both JSON and JSONB input 2025-01-26 14:44:27 +01:00
Gwendal Roué 0f68d8b684 JSON_VALID options 2025-01-26 14:21:35 +01:00
Gwendal Roué 367f8f7e37 Add missing imports for C SQLite functions 2025-01-26 14:21:35 +01:00
Gwendal Roué 831e79ee82 JSONB functions and tests 2025-01-26 14:21:35 +01:00
Gwendal Roué 8b3f9c0936 Prefer JSONB when building JSON 2025-01-26 14:21:35 +01:00
Gwendal Roué 950db13d46 Declare JSONB functions behavior 2025-01-26 14:21:35 +01:00
Gwendal Roué 0e664cf22e Not only pluralization can be a problem 2025-01-23 08:10:36 +01:00
Gwendal Roué 1e5602ca9d Merge pull request #1703 from groue/dev/inflections-fixes
Fix pluralization of Bias, Focus, Gas, and Lens
2025-01-22 21:29:31 +01:00
Gwendal Roué 8147811ab4 Mention Bias, Focus, Gas, and Lens in the GRDB 7 Migration Guide 2025-01-22 21:02:09 +01:00
Gwendal Roué 4c9b0eb90e Fix failing tests for inflections 2025-01-22 20:41:55 +01:00
Gwendal Roué b63d75da21 Failing tests for inflections
- bias/biases
- focus/focuses
- gas/gases
- lens/lenses
2025-01-22 20:41:39 +01:00
Gwendal Roué 5a3db29e21 Remove link to X account 2025-01-21 13:14:03 +01:00
Gwendal Roué fa0985eb01 Documentation: add @retroactive to Tagged extensions 2025-01-21 08:03:46 +01:00
Gwendal Roué 495e76bb1a Fix performance tests for SQLite.swift 2025-01-20 08:51:01 +01:00
Gwendal Roué bbf39353b5 Merge branch 'development' 2025-01-19 18:20:47 +01:00
Gwendal Roué 442b8b0589 7.0.0-beta.7 2025-01-19 17:30:17 +01:00
Gwendal Roué 2c85bc2cfc CHANGELOG 2025-01-19 16:57:34 +01:00
Gwendal Roué 3f56bc8199 Merge pull request #1700 from groue/dev/all-columns-excluding
Select all columns from a table, but a few ones
2025-01-19 16:50:48 +01:00
Gwendal Roué 37ea21eb96 Test AllColumnsExcluding and Table 2025-01-19 16:26:59 +01:00
Gwendal Roué 96c9eb5699 Enhance documentation of generated columns 2025-01-19 16:26:59 +01:00
Gwendal Roué 33103bb373 AllColumnsExcluding tests 2025-01-19 16:26:59 +01:00
Gwendal Roué 6b23181337 Use .allColumns and .rowID instead of AllColumns() and Column.rowID 2025-01-19 16:26:59 +01:00
Gwendal Roué c5366f4a01 AllColumnsExcluding documentation 2025-01-19 16:26:59 +01:00
Gwendal Roué a642ac51aa AllColumnsExcluding 2025-01-19 16:26:59 +01:00
Gwendal Roué d03208b33a Remove unused code 2025-01-19 16:26:59 +01:00
Gwendal Roué a4132a00db Clarify code that aims at fixing #1357 2025-01-19 16:26:59 +01:00
Gwendal Roué 61c7fdf81b Github CI: use tvOS 18.1 2025-01-19 16:26:29 +01:00
265 changed files with 17370 additions and 4162 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 15 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.0,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
}
+135 -29
View File
@@ -7,7 +7,16 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 7.x Releases
- `7.0.0` Betas - [7.0.0-beta](#700-beta) - [7.0.0-beta.2](#700-beta2) - [7.0.0-beta.3](#700-beta3) - [7.0.0-beta.4](#700-beta4) - [7.0.0-beta.5](#700-beta5) - [7.0.0-beta.6](#700-beta6)
- `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)
- `7.2.x` Releases - [7.2.0](#720)
- `7.1.x` Releases - [7.1.0](#710)
- `7.0.x` Releases - [7.0.0](#700)
- `7.0.0` Betas - [7.0.0-beta](#700-beta) - [7.0.0-beta.2](#700-beta2) - [7.0.0-beta.3](#700-beta3) - [7.0.0-beta.4](#700-beta4) - [7.0.0-beta.5](#700-beta5) - [7.0.0-beta.6](#700-beta6) - [7.0.0-beta.7](#700-beta7)
#### 6.x Releases
@@ -131,6 +140,103 @@ 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
- **New**: Make it possible to create a raw FTS5Pattern without any database connection by [@groue](https://github.com/groue) in [#1764](https://github.com/groue/GRDB.swift/pull/1764)
- **New**: Build request with closures by [@groue](https://github.com/groue) in [#1759](https://github.com/groue/GRDB.swift/pull/1759)
## 7.4.1
Released March 28, 2025
- Removed a compiler warning
## 7.4.0
Released March 22, 2025
- **New**: Add the MIN and MAX multi-argument SQL functions to the query interface by [@groue](https://github.com/groue) in [#1745](https://github.com/groue/GRDB.swift/pull/1745)
- **Fixed**: Transaction observers are not impacted by Task Cancellation by [@groue](https://github.com/groue) in [#1747](https://github.com/groue/GRDB.swift/pull/1747). This fixes unexpected `ValueObservation` failures in applications that perform asynchronous writes.
## 7.3.0
Released February 23, 2025
- **New**: Support for temporary virtual tables by [@groue](https://github.com/groue) in [#1731](https://github.com/groue/GRDB.swift/pull/1731)
- Fixed a compiler error in Xcode 16.3 beta ([#1729](https://github.com/groue/GRDB.swift/pull/1729), [#1730](https://github.com/groue/GRDB.swift/pull/1730))
## 7.2.0
Released February 12, 2025
- **New**: Select ids with selectID() by [@groue](https://github.com/groue) in [#1719](https://github.com/groue/GRDB.swift/pull/1719)
## 7.1.0
Released February 5, 2025
- **New**: Expose `sqlite3_libversion_number` as `Database.sqliteLibVersionNumber` by [@groue](https://github.com/groue) in [#1713](https://github.com/groue/GRDB.swift/pull/1713)
- **Fixed**: DatabaseQueue restores its read/write abilities when an async read-only database access is cancelled by [@groue](https://github.com/groue) in [#1716](https://github.com/groue/GRDB.swift/pull/1716)
- **New**: Allow RxGRDB to compile without warning by [@groue](https://github.com/groue) in [#1717](https://github.com/groue/GRDB.swift/pull/1717)
## 7.0.0
Released January 26, 2025
- **New**: Support for JSONB expressions by [@groue](https://github.com/groue) in [#1699](https://github.com/groue/GRDB.swift/pull/1699)
- **Breaking Change**: Fix inflections of Bias, Focus, Gas, and Lens by [@groue](https://github.com/groue) in [#1703](https://github.com/groue/GRDB.swift/pull/1703)
## 7.0.0-beta.7
Released January 19, 2025
- **New**: Select all columns from a table, but a few ones by [@groue](https://github.com/groue) in [#1700](https://github.com/groue/GRDB.swift/pull/1700)
- **Fixed**: Fix typo in Readme.md by [@kevinlg](https://github.com/kevinlg) in [#1697](https://github.com/groue/GRDB.swift/pull/1697)
- **New**: Bump custom SQLite to 3.47.2 by [@groue](https://github.com/groue) in [#1696](https://github.com/groue/GRDB.swift/pull/1696)
- **Fixed**: Update LICENSE, fix copyright license year by [@JasonnnW3000](https://github.com/JasonnnW3000) in [#1695](https://github.com/groue/GRDB.swift/pull/1695)
- **Fixed**: Core: import `ucrt` on Windows for `strcmp` by [@compnerd](https://github.com/compnerd) in [#1662](https://github.com/groue/GRDB.swift/pull/1662)
- **Fixed**: Foundation: elide extensions on Windows to match Linux by [@compnerd](https://github.com/compnerd) in [#1661](https://github.com/groue/GRDB.swift/pull/1661)
- **Fixed**: Docs: fixes typos "FST"->"FTS" by [@nylki](https://github.com/nylki) in [#1660](https://github.com/groue/GRDB.swift/pull/1660)
## 7.0.0-beta.6
Released October 13, 2024
@@ -172,7 +278,7 @@ Released September 29, 2024
[Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md) describes in detail how to bump the GRDB version in your application.
The new [Swift Concurrency and GRDB](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/swiftconcurrency) guide explains how to best integrate GRDB and Swift Concurrency.
The new [Swift Concurrency and GRDB](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/swiftconcurrency) guide explains how to best integrate GRDB and Swift Concurrency.
The [demo app](Documentation/DemoApps/) was rewritten from scratch in a brand new Xcode 16 project.
@@ -231,8 +337,8 @@ Released July 11, 2024
Released April 21, 2024
- **Fixed**: [#1533](https://github.com/groue/GRDB.swift/pull/1533) by [@groue](https://github.com/groue): Fix a bug in Decodable support
- **Documentation Update**: [#1534](https://github.com/groue/GRDB.swift/pull/1534) The [Single-Row Tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables) guide was updated with guidance about default configuration values.
- **Documentation Update**: [#1535](https://github.com/groue/GRDB.swift/pull/1535) The [ValueObservation Scheduling](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation#ValueObservation-Scheduling) documentation chapter explains the default behavior of `ValueObservation` fetches, and explains how to make sure they are never performed on the main thread.
- **Documentation Update**: [#1534](https://github.com/groue/GRDB.swift/pull/1534) The [Single-Row Tables](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/singlerowtables) guide was updated with guidance about default configuration values.
- **Documentation Update**: [#1535](https://github.com/groue/GRDB.swift/pull/1535) The [ValueObservation Scheduling](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation#ValueObservation-Scheduling) documentation chapter explains the default behavior of `ValueObservation` fetches, and explains how to make sure they are never performed on the main thread.
## 6.26.0
@@ -257,7 +363,7 @@ Released February 25, 2024
Released January 21, 2024
- **Documentation Update**: [#1485](https://github.com/groue/GRDB.swift/pull/1485) The [Sharing a Database](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing) guide was updated with a new recommendation for databases shared between multiple processes. Writers should always perform IMMEDIATE transactions in order to avoid the `SQLITE_BUSY` error that can occur when transactions overlap. The new recommendation fits in a single line of code: `configuration.defaultTransactionKind = .immediate`.
- **Documentation Update**: [#1485](https://github.com/groue/GRDB.swift/pull/1485) The [Sharing a Database](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing) guide was updated with a new recommendation for databases shared between multiple processes. Writers should always perform IMMEDIATE transactions in order to avoid the `SQLITE_BUSY` error that can occur when transactions overlap. The new recommendation fits in a single line of code: `configuration.defaultTransactionKind = .immediate`.
- **New**: Associations that involve views instead of tables were already supported, with an explicit `ForeignKey` in their definition. When the foreign key is missing, a clear diagnostic message is now emitted, instead of an unhelpful "no such table" runtime error.
## 6.24.1
@@ -284,7 +390,7 @@ Released November 26, 2023
- **New**: [#1452](https://github.com/groue/GRDB.swift/pull/1452) by [@groue](https://github.com/groue): SQLite 3.44.0, FILTER and ORDER BY clauses in aggregate functions
- **New**: [#1460](https://github.com/groue/GRDB.swift/pull/1460) by [@groue](https://github.com/groue): Explicit change notifications help applications deal with undetected database changes.
- **Documentation Update**: The documentations of [`ValueObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation), [`DatabaseRegionObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation), and [`TransactionObserver`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver) have a new "Dealing with Undetected Changes" that documents possible strategies for notifying applications of undetected database changes.
- **Documentation Update**: The documentations of [`ValueObservation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation), [`DatabaseRegionObservation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseregionobservation), and [`TransactionObserver`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactionobserver) have a new "Dealing with Undetected Changes" that documents possible strategies for notifying applications of undetected database changes.
## 6.21.0
@@ -320,8 +426,8 @@ Released October 4, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compa
- **New**: [#1436](https://github.com/groue/GRDB.swift/pull/1436) by [@myyra](https://github.com/myyra) and [@groue](https://github.com/groue): JSON functions
- **New**: `Database` has learned to create indexes on expressions, and specify specific collations on indexed columns, with the `create(index:on:expressions:options:condition:)` method.
- **New**: Codable records can specify coding strategies for their `Data` properties. See [#1436](https://github.com/groue/GRDB.swift/pull/1436) for more information.
- **Documentation Update**: A new [JSON Support](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/json) article provides an overview of JSON handling.
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) now recommend that record types with an auto-incremented id avoid conforming to the `Identifiable` protocol.
- **Documentation Update**: A new [JSON Support](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/json) article provides an overview of JSON handling.
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) now recommend that record types with an auto-incremented id avoid conforming to the `Identifiable` protocol.
## 6.18.0
@@ -345,14 +451,14 @@ Released July 9, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/
- **New**: [#1403](https://github.com/groue/GRDB.swift/pull/1403) by [@groue](https://github.com/groue): GitHub CI: test Xcode 14.3.1, macOS 13
- **New**: :star: [#1405](https://github.com/groue/GRDB.swift/pull/1405) Simplify the declaration of BelongsTo associations in the database schema
- **Documentation Update**: The documentation was updated for the new recommended way to declare associations in the database schema, with the `belongsTo()` method introduced by [#1405](https://github.com/groue/GRDB.swift/pull/1405):
- [`belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tabledefinition/belongsto(_:intable:ondelete:onupdate:deferred:indexed:))
- [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema)
- [Migrations](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations)
- [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices)
- [`belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tabledefinition/belongsto(_:intable:ondelete:onupdate:deferred:indexed:))
- [The Database Schema](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema)
- [Migrations](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/migrations)
- [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices)
- [Associations](Documentation/AssociationsBasics.md)
- [`BelongsToAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/belongstoassociation)
- [`HasManyAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasmanyassociation)
- [`HasOneAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasoneassociation)
- [`BelongsToAssociation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/belongstoassociation)
- [`HasManyAssociation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/hasmanyassociation)
- [`HasOneAssociation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/hasoneassociation)
## 6.15.1
@@ -369,7 +475,7 @@ Released June 2, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/
- **New**: [#1382](https://github.com/groue/GRDB.swift/pull/1382) Add `DerivableRequest.all()`
- **New**: [#1384](https://github.com/groue/GRDB.swift/pull/1384) Allow ValueObservation to start from a truncated wal file
- **Documentation Update**: The [ValueObservation Performance](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation#ValueObservation-Performance) documentation chapter explains how truncating WAL checkpoints impact `ValueObservation`.
- **Documentation Update**: The [ValueObservation Performance](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation#ValueObservation-Performance) documentation chapter explains how truncating WAL checkpoints impact `ValueObservation`.
## 6.14.0
@@ -404,7 +510,7 @@ Released April 17, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compar
Released April 10, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.10.1...v6.10.2)
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) guide has moved to DocC.
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) guide has moved to DocC.
- **Documentation Update**: The [Demo Applications](Documentation/DemoApps/) demonstrate how their `AppDatabase` "database manager" can provide a base database configuration.
## 6.10.1
@@ -431,8 +537,8 @@ Released March 14, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compar
Released March 12, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.9.0...v6.9.1)
- **Documentation Updates**: Moved more README chapters into DocC:
- [`RowAdapter`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter)
- [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/splittingrowadapters(columncounts:))
- [`RowAdapter`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/rowadapter)
- [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/splittingrowadapters(columncounts:))
## 6.9.0
@@ -441,9 +547,9 @@ Released March 12, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compar
- **New**: [#1348](https://github.com/groue/GRDB.swift/pull/1348) by [@groue](https://github.com/groue): SQLite argument binding optimization
- **New**: `FTS5.api(db)` returns a pointer to the `fts5_api` structure, useful for low-level [FTS5 customization](https://www.sqlite.org/fts5.html#extending_fts5).
- **Documentation Updates**: Moved more README chapters into DocC, enhanced and extended DocC articles:
- [Database Connections](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections)
- [Prepared Statements](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statement)
- [DatabaseValueConvertible](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasevalueconvertible)
- [Database Connections](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections)
- [Prepared Statements](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statement)
- [DatabaseValueConvertible](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasevalueconvertible)
## 6.8.0
@@ -451,7 +557,7 @@ Released February 24, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/com
- **New**: [#1338](https://github.com/groue/GRDB.swift/pull/1338) by [@groue](https://github.com/groue): TimestampedRecord sample code
- **New**: `EncodableRecord.databaseChanges(modify:)` modifies a record and returns a dictionary of applied changes.
- **Documentation Update**: The [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps) article provides a sample `TimestampedRecord` protocol that application may adapt for their own use.
- **Documentation Update**: The [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordtimestamps) article provides a sample `TimestampedRecord` protocol that application may adapt for their own use.
## 6.7.0
@@ -462,7 +568,7 @@ Released February 19, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/com
- **Fixed**: [#1327](https://github.com/groue/GRDB.swift/pull/1327) by [@groue](https://github.com/groue): Remove dependency on any specific SwiftLint version.
- **New**: [#1331](https://github.com/groue/GRDB.swift/pull/1331) by [@groue](https://github.com/groue): Transaction Date
- **New**: [#1336](https://github.com/groue/GRDB.swift/pull/1336) by [@groue](https://github.com/groue): Enable FTS5 by default
- **Documentation Update**: The new [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps) article explains how applications can save the creation and modification date of records.
- **Documentation Update**: The new [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordtimestamps) article explains how applications can save the creation and modification date of records.
- Added support for `Table` in SQL interpolation.
## 6.6.1
@@ -492,11 +598,11 @@ Released November 28, 2022 &bull; [diff](https://github.com/groue/GRDB.swift/com
- **New**: `DatabaseReader.configuration.readQoS` and `writeQoS` return the effective quality of service of read-only and write database accesses. This helps application code avoid priority inversion and similar scheduling misuses when needed.
- **New**: `DatabaseReader.configuration.maximumReaderCount` returns the effective capacity for concurrent reads, so that application code can adapt when needed.
- **New**: `DatabasePool.makeSnapshot()` no longer throws an error when the database is not in the WAL mode. In such case, the returned snapshot prevents all database modifications during its lifetime.
- **New**: A new [`DatabaseSnapshotReader`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesnapshotreader) protocol was introduced for types that see an unchanging database content (`DatabaseSnapshot` and the new `DatabaseSnapshotPool`).
- **New**: [`Database.registerAccess(to:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/registeraccess(to:)) has `ValueObservation` track a region. This helps building optimized observations of a constant database region with [`ValueObservation.trackingConstantRegion(_:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/trackingconstantregion(_:)).
- **New**: Open several connections to the same in-memory database with [`DatabaseQueue(named:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue/init(named:configuration:)).
- **New**: [`TableDefinition`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tabledefinition) has new methods for defining primary keys, with automatic NOT NULL constraints. They workaround [an SQLite bug](https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls). Previous techniques for defining primary keys are preserved for backwards compatibility, but their use is not recommended.
- **New**: The [Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) documentation article has a brand new "Database Schema Recommendations" section.
- **New**: A new [`DatabaseSnapshotReader`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesnapshotreader) protocol was introduced for types that see an unchanging database content (`DatabaseSnapshot` and the new `DatabaseSnapshotPool`).
- **New**: [`Database.registerAccess(to:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/registeraccess(to:)) has `ValueObservation` track a region. This helps building optimized observations of a constant database region with [`ValueObservation.trackingConstantRegion(_:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/trackingconstantregion(_:)).
- **New**: Open several connections to the same in-memory database with [`DatabaseQueue(named:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasequeue/init(named:configuration:)).
- **New**: [`TableDefinition`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tabledefinition) has new methods for defining primary keys, with automatic NOT NULL constraints. They workaround [an SQLite bug](https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls). Previous techniques for defining primary keys are preserved for backwards compatibility, but their use is not recommended.
- **New**: The [Database Schema](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema) documentation article has a brand new "Database Schema Recommendations" section.
- **New**: Multiple improvements to the DocC documentation.
## 6.3.1
+1 -1
View File
@@ -1,4 +1,4 @@
Sharing a Database in an App Group Container
============================================
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing).
This guide [has moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing).
+134 -118
View File
@@ -58,15 +58,26 @@ GRDB Associations
Associations streamline common operations in your code, make them safer, and more efficient. For example, consider a library application that has two record types, author and book:
```swift
struct Author {
struct Author: Codable, Identifiable, FetchableRecord, PersistableRecord {
var id: Int64
var name: String
enum Columns {
static let id = Column(CodingKeys.id)
static let name = Column(CodingKeys.name)
}
}
struct Book {
struct Book: Codable, Identifiable, FetchableRecord, PersistableRecord {
var id: Int64
var authorId: Int64?
var title: String
enum Columns {
static let id = Column(CodingKeys.id)
static let authorId = Column(CodingKeys.authorId)
static let title = Column(CodingKeys.title)
}
}
```
@@ -75,7 +86,7 @@ Now, suppose we wanted to load all books from an existing author. We'd need to d
```swift
let author: Author = ...
let books = try Book
.filter(Column("authorId") == author.id)
.filter { $0.authorId == author.id }
.fetchAll(db)
```
@@ -121,7 +132,7 @@ let books = try author.books.fetchAll(db)
As for loading all pairs of books and authors, it is not only easier, but also *much more efficient*:
```swift
struct BookInfo: FetchableRecord, Decodable {
struct BookInfo: Decodable, FetchableRecord {
let book: Book
let author: Author?
}
@@ -130,7 +141,7 @@ let request = Book.including(optional: Book.author)
let bookInfos = BookInfo.fetchAll(db, request)
```
Before we dive in, please remember that associations can not generate all possible SQL queries that involve several tables. You may also *prefer* writing SQL, and this is just OK, because your SQL skills are welcome. The [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/splittingrowadapters(columncounts:)) method can help you consume the rows fetched from joined queries, as in `SELECT book.*, author.* FROM ...`.
Before we dive in, please remember that associations can not generate all possible SQL queries that involve several tables. You may also *prefer* writing SQL, and this is just OK, because your SQL skills are welcome. The [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/splittingrowadapters(columncounts:)) method can help you consume the rows fetched from joined queries, as in `SELECT book.*, author.* FROM ...`.
## Required Protocols
@@ -728,9 +739,15 @@ Your help is needed. You have to instruct GRDB which foreign key to use:
```swift
struct Book: TableRecord {
// Table columns
enum Columns {
static let authorId = Column("authorId")
static let translatorId = Column("translatorId")
}
// Define foreign keys
static let authorForeignKey = ForeignKey(["authorId"])
static let translatorForeignKey = ForeignKey(["translatorId"])
static let authorForeignKey = ForeignKey([Columns.authorId])
static let translatorForeignKey = ForeignKey([Columns.translatorId])
// Use foreign keys to define associations:
static let author = belongsTo(Person.self, using: authorForeignKey)
@@ -747,24 +764,11 @@ struct Person: TableRecord {
}
```
Foreign keys can also be defined from query interface columns:
```swift
struct Book: TableRecord {
enum Columns: String, ColumnExpression {
case id, title, authorId, translatorId
}
static let authorForeignKey = ForeignKey([Columns.authorId])
static let translatorForeignKey = ForeignKey([Columns.translatorId])
}
```
When the destination table of a foreign key does not define any primary key, you need to provide the full definition of a foreign key:
```swift
struct Book: TableRecord {
static let authorForeignKey = ForeignKey(["authorId"], to: ["id"])
static let authorForeignKey = ForeignKey([Columns.authorId], to: [Person.Columns.id])
static let author = belongsTo(Person.self, using: authorForeignKey)
}
```
@@ -836,8 +840,8 @@ Requests for associated records can be filtered and ordered like all [query inte
```swift
let novels = try author
.books
.filter(Column("kind") == BookKind.novel)
.order(Column("publishDate").desc)
.filter { $0.kind == BookKind.novel }
.order(\.publishDate.desc)
.fetchAll(db) // [Book]
```
@@ -921,7 +925,7 @@ struct BookInfo: Decodable, FetchableRecord {
var author: PartialAuthor
}
let bookInfos = try Book
.including(required: Book.author.select(Column("name"), Column("country")))
.including(required: Book.author.select { [$0.name, $0.country] })
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -935,7 +939,7 @@ struct BookInfo: Decodable, FetchableRecord {
var country: String
}
let bookInfos = try Book
.annotated(withRequired: Book.author.select(Column("country")))
.annotated(withRequired: Book.author.select(\.country)
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -982,7 +986,7 @@ struct BookInfo: Decodable, FetchableRecord {
var author: PartialAuthor?
}
let bookInfos = try Book
.including(optional: Book.author.select(Column("name"), Column("country")))
.including(optional: Book.author.select { [$0.name, $0.country] })
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -996,7 +1000,7 @@ struct BookInfo: Decodable, FetchableRecord {
var country: String?
}
let bookInfos = try Book
.annotated(withOptional: Book.author.select(Column("country")))
.annotated(withOptional: Book.author.select(\.country))
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -1064,7 +1068,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
var books: [PartialBook]
}
let authorInfos = try Author
.including(all: Author.books.select(Column("title"), Column("year")))
.including(all: Author.books.select { [$0.title, $0.year] })
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
@@ -1079,7 +1083,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
}
let authorInfos = try Author
.including(all: Author.books
.select(Column("title"))
.select(\.title)
.forKey("bookTitles"))
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
@@ -1093,7 +1097,7 @@ For example, fetch books along with the name and country of their author:
// SELECT book.*, author.name, author.country
// FROM book
// JOIN author ON author.id = book.authorId
let request = Book.annotated(withRequired: Book.author.select(Column("name"), Column("country")))
let request = Book.annotated(withRequired: Book.author.select { [$0.name, $0.country] })
```
This method accepts any association. The base record is annotated with the selected columns of one associated record. When the associated record does not exist, records are not present in the fetched results: the associated record is "required".
@@ -1108,7 +1112,7 @@ struct BookInfo: Decodable, FetchableRecord {
var country: String // A column of the required associated record
}
let bookInfos = try Book
.annotated(withRequired: Book.author.select(Column("name"), Column("country")))
.annotated(withRequired: Book.author.select { [$0.name, $0.country] })
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -1122,7 +1126,7 @@ struct BookInfo: Decodable, FetchableRecord {
var authorName: String
}
let bookInfos = try Book
.annotated(withRequired: Book.author.select(Column("name").forKey("authorName")))
.annotated(withRequired: Book.author.select { $0.name.forKey("authorName") })
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -1135,7 +1139,7 @@ For example, fetch books along with the name and country of their eventual autho
// SELECT book.*, author.name, author.country
// FROM book
// LEFT JOIN author ON author.id = book.authorId
let request = Book.annotated(withOptional: Book.author.select(Column("name"), Column("country")))
let request = Book.annotated(withOptional: Book.author.select { [$0.name, $0.country] })
```
This method accepts any association. The base record is annotated with the selected columns of one associated record. When the associated record does not exist, the columns of the associated record are NULL: the associated record is "optional".
@@ -1150,7 +1154,7 @@ struct BookInfo: Decodable, FetchableRecord {
var country: String? // A column of the optional associated record
}
let bookInfos = try Book
.annotated(withOptional: Book.author.select(Column("name"), Column("country")))
.annotated(withOptional: Book.author.select { [$0.name, $0.country] })
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -1164,7 +1168,7 @@ struct BookInfo: Decodable, FetchableRecord {
var authorName: String?
}
let bookInfos = try Book
.annotated(withOptional: Book.author.select(Column("name").forKey("authorName")))
.annotated(withOptional: Book.author.select { $0.name.forKey("authorName") })
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -1178,7 +1182,7 @@ For example, fetch books by French authors:
// FROM book
// JOIN author ON author.id = book.authorId
// AND author.country = 'France'
let request = Book.joining(required: Book.author.filter(Column("country") == "France"))
let request = Book.joining(required: Book.author.filter { $0.country == "France" })
```
This method accepts any association. It has the base record "joined" with one associated record, which is not included in the fetched results. When the associated record does not exist, the base record is not present in the fetched results: the associated record is "required".
@@ -1188,7 +1192,7 @@ To fetch results from such a request, you do not need to define a dedicated reco
```swift
// Fetch all books by French authors
let books = try Book
.joining(required: Book.author.filter(Column("country") == "France"))
.joining(required: Book.author.filter { $0.country == "France" })
.fetchAll(db)
```
@@ -1239,7 +1243,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
}
let bookInfos = try Book
.including(required: Book.author.select(Column("name"), Column("country")))
.including(required: Book.author.select { [$0.name, $0.country] })
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -1254,9 +1258,9 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
}
let bookInfos = try Book
.annotated(withRequired: Book.author.select(
Column("name").forKey("authorName"),
Column("country")))
.annotated(withRequired: Book.author.select {
[$0.name.forKey("authorName"), $0.country]
})
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -1286,7 +1290,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
}
let bookInfos = try Book
.including(optional: Book.author.select(Column("name"), Column("country")))
.including(optional: Book.author.select { [$0.name, $0.country] })
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -1301,9 +1305,9 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
}
let bookInfos = try Book
.annotated(withOptional: Book.author.select(
Column("name").forKey("authorName"),
Column("country")))
.annotated(withOptional: Book.author.select {
[$0.name.forKey("authorName"), $0.country]
})
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
@@ -1333,7 +1337,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
}
let authorInfos = try Author
.including(all: Author.books.select(Column("title"), Column("year")))
.including(all: Author.books.select { [$0.title, $0.year] })
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
@@ -1346,7 +1350,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
let authorInfos = try Author
.including(all: Author.books
.select(Column("title"))
.select(\.title)
.forKey("bookTitles"))
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
@@ -1460,7 +1464,7 @@ The `filter(_:)`, `filter(id:)`, `filter(ids:)`, `filter(key:)` and `filter(keys
// FROM book
// JOIN person ON person.id = book.authorId
// AND person.countryCode = 'FR'
let frenchAuthor = Book.author.filter(Column("countryCode") == "FR")
let frenchAuthor = Book.author.filter { $0.countryCode == "FR" }
let request = Book.joining(required: frenchAuthor)
// This request feeds the Book record:
@@ -1474,10 +1478,10 @@ The one below fetches all authors along with their novels and poems:
```swift
let request = Author
.including(all: Author.book
.filter(Column("kind") == "novel")
.filter { $0.kind == "novel" }
.forKey("novels"))
.including(all: Author.book
.filter(Column("kind") == "poems")
.filter { $0.kind == "poems" }
.forKey("poems"))
// This request can feed the following record:
@@ -1508,7 +1512,7 @@ The `order()` method, that you already know for [sorting simple requests](../REA
// FROM book
// JOIN person ON person.id = book.authorId
// ORDER BY person.name
let sortedAuthor = Book.author.order(Column("name"))
let sortedAuthor = Book.author.order(\.name)
let request = Book.including(required: sortedAuthor)
```
@@ -1519,10 +1523,10 @@ When you sort both the base record and the associated record, the request is sor
// FROM book
// JOIN person ON person.id = book.authorId
// ORDER BY book.publishDate DESC, person.name
let sortedAuthor = Book.author.order(Column("name"))
let sortedAuthor = Book.author.order(\.name)
let request = Book
.including(required: sortedAuthor)
.order(Column("publishDate").desc)
.order(\.publishDate.desc)
```
**There are more sorting options:**
@@ -1559,7 +1563,7 @@ The `Team.players` association is ordered by position, so that all team players
```swift
extension Team {
static let players = hasMany(Player.self).order(Column("position"))
static let players = hasMany(Player.self).order(\.position)
var players: QueryInterfaceRequest<Player> {
request(for: Team.players)
@@ -1591,7 +1595,7 @@ Again, the `Team.players` association is ordered by position, so that all team p
```swift
extension Team {
static let playerRoles = hasMany(PlayerRole.self).order(Column("position"))
static let playerRoles = hasMany(PlayerRole.self).order(\.position)
static let players = hasMany(Player.self, through: playerRoles, using: PlayerRole.player)
@@ -1623,9 +1627,9 @@ let teamInfos = try Team
// Custom ordering
let team: Team = ...
let players = try team.players.order(Column("name")).fetchAll(db)
let players = try team.players.order(\.name).fetchAll(db)
let teamInfos = try Team
.including(all: Team.players.order(Column("name")))
.including(all: Team.players.order(\.name))
.asRequest(of: TeamInfo.self)
.fetchAll(db)
```
@@ -1651,7 +1655,7 @@ To specify the selection in a specific request, use the `select` method:
// SELECT book.*, author.id, author.name
// FROM book
// JOIN author ON author.id = book.authorId
let restrictedAuthor = Book.author.select(Column("id"), Column("name"))
let restrictedAuthor = Book.author.select { [$0.id, $0.name] }
let request = Book.including(required: restrictedAuthor)
```
@@ -1673,7 +1677,7 @@ Associations support more refinements:
}
let distinctBookKinds = Author.books
.select(Column("kind"))
.select(\.kind)
.distinct()
.forKey("bookKinds")
@@ -1699,10 +1703,8 @@ Associations support more refinements:
}
let bookKindInfos = Author.books
.select(
Column("kind"),
max(Column("year")).forKey("maxYear"))
.group(Column("kind"))
.select { [$0.kind, max($0.year).forKey("maxYear")] }
.group(\.kind)
.forKey("bookKindInfos")
let authorInfos: [AuthorInfo] = try Author
@@ -1772,7 +1774,7 @@ Let's first see a wrong way to do it:
// WHERE book.publishDate >= book.deathDate
let request = Book
.joining(required: Book.author)
.filter(Column("publishDate") >= Column("deathDate"))
.filter { $0.publishDate >= $0.deathDate }
```
When executed, we'll get a DatabaseError of code 1, "no such column: book.deathDate".
@@ -1782,21 +1784,35 @@ That is because the "deathDate" column has been used for filtering books, when i
To fix this error, we need a **table alias**:
```swift
let authorAlias = TableAlias()
let authorAlias = TableAlias<Author>()
```
We modify the `Book.author` association so that it uses this table alias, and we use the table alias to qualify author columns where needed:
```swift
// SELECT book.*
// FROM book
// JOIN person ON person.id = book.authorId
// WHERE book.publishDate >= person.deathDate
// Swift 6.1
//
// > SELECT book.*
// > FROM book
// > JOIN person ON person.id = book.authorId
// > WHERE book.publishDate >= person.deathDate
let request = Book
.joining(required: Book.author.aliased(authorAlias))
.filter(Column("publishDate") >= authorAlias[Column("deathDate")])
.filter { $0.publishDate >= authorAlias.deathDate }
// Swift 6.0
//
// > SELECT book.*
// > FROM book
// > JOIN person ON person.id = book.authorId
// > WHERE book.publishDate >= person.deathDate
let request = Book
.joining(required: Book.author.aliased(authorAlias))
.filter { $0.publishDate >= authorAlias[Author.Columns.deathDate] }
```
Note that Swift 6.1 is required for the short syntac `alias.column`. From now on, we will only give examples in Swift 6.1.
**Table aliases** can also improve control over the ordering of request results. In the example below, we override the [default ordering](#sorting-associations) of associated records by sorting on author names first:
```swift
@@ -1806,7 +1822,7 @@ let request = Book
// ORDER BY person.name, book.publishDate
let request = Book
.joining(required: Book.author.aliased(authorAlias))
.order(authorAlias[Column("name")], Column("publishDate"))
.order { [authorAlias.name, $0.publishDate] }
```
**Table aliases** can be given a name. This name is guaranteed to be used as the table alias in the SQL query. This guarantee lets you write SQL snippets when you need it:
@@ -1817,8 +1833,8 @@ let request = Book
// JOIN person a ON a.id = b.authorId
// AND a.countryCode = 'FR'
// WHERE b.publishDate >= a.deathDate
let bookAlias = TableAlias(name: "b")
let authorAlias = TableAlias(name: "a")
let bookAlias = TableAlias<Book>(name: "b")
let authorAlias = TableAlias<Person>(name: "a")
let request = Book.aliased(bookAlias)
.joining(required: Book.author.aliased(authorAlias)
.filter(sql: "a.countryCode = ?", arguments: ["FR"]))
@@ -1838,11 +1854,11 @@ let request = Book.aliased(bookAlias)
>
> ```swift
> // NOT IMPLEMENTED: loading all authors along with their posthumous books
> let authorAlias = TableAlias()
> let authorAlias = TableAlias<Author>()
> let request = Author
> .aliased(authorAlias)
> .including(all: Author.books
> .filter(Column("publishDate") >= authorAlias[Column("deathDate")]))
> .filter { $0.publishDate >= authorAlias.deathDate })
> ```
@@ -1904,7 +1920,7 @@ For example, we can start by defining base requests as extensions to the [Deriva
extension DerivableRequest<Author> {
/// Filters authors by country
func filter(country: String) -> Self {
filter(Column("country") == country)
filter { $0.country == country }
}
}
@@ -1917,12 +1933,13 @@ extension DerivableRequest<Book> {
/// Order books by author name and then book title
func orderedByAuthorNameAndYear() -> Self {
let authorAlias = TableAlias()
let authorAlias = TableAlias<Author>()
return self
.joining(optional: Book.author.aliased(authorAlias))
.order(
authorAlias[Column("name")].collating(.localizedCaseInsensitiveCompare),
Column("year"))
.order { [
authorAlias.name.collating(.localizedCaseInsensitiveCompare),
$0.year,
] }
}
}
```
@@ -2063,7 +2080,7 @@ Keys can also be customized with the `forKey` method:
```swift
extension Author {
static let novels = books
.filter(Column("kind") == "novel")
.filter { $0.kind == "novel" }
.forKey("novels")
}
Author.including(all: Author.novels) // association key "novels"
@@ -2169,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.
@@ -2204,7 +2220,7 @@ struct AuthorInfo: FetchableRecord {
init(row: Row) throws {
author = try Author(row: row)
books = row["books"]
books = try row.decode(forKey: "books")
}
}
@@ -2288,7 +2304,7 @@ let author: Author = ...
let bookCount = try author.books.fetchCount(db) // Int
// The year of the most recent book by this author
let request = author.books.select(max(yearColumn))
let request = author.books.select { max($0.year) }
let maxBookYear = try Int.fetchOne(db, request) // Int?
```
@@ -2359,7 +2375,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
// GROUP BY author.id
let request = Author.annotated(with:
Author.books.count,
Author.books.max(Column("year")))
Author.books.max(\.year))
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
@@ -2376,13 +2392,13 @@ The default name is built from the aggregating method, the **[association key](#
| Method | Association Key | Aggregated Column | Aggregate name |
| ------ | --------------- | ----------------- | -------------- |
| `Author.books.isEmpty`. | `books` | - | `hasNoBook` |
| `Author.books.count`. | `books` | - | `bookCount` |
| `Author.books.min(Column("year"))` | `books` | `year` | `minBookYear` |
| `Author.books.max(Column("year"))` | `books` | `year` | `maxBookYear` |
| `Author.books.average(Column("price"))` | `books` | `price` | `averageBookPrice` |
| `Author.books.sum(Column("awards"))` | `books` | `awards` | `bookAwardsSum` |
| `Author.books.total(Column("awards"))` | `books` | `awards` | `bookAwardsSum` ¹ |
| `Author.books.isEmpty`. | `books` | - | `hasNoBook` |
| `Author.books.count`. | `books` | - | `bookCount` |
| `Author.books.min(\.year)` | `books` | `year` | `minBookYear` |
| `Author.books.max(\.year)` | `books` | `year` | `maxBookYear` |
| `Author.books.average(\.price)` | `books` | `price` | `averageBookPrice` |
| `Author.books.sum(\.awards)` | `books` | `awards` | `bookAwardsSum` |
| `Author.books.total((\.awards))` | `books` | `awards` | `bookAwardsSum` ¹ |
¹ The default name of the `total` aggregate has a `Sum` suffix, just like the `sum` aggregate. Both compute sums, one with the `SUM` SQL function, the other with `TOTAL`. See [SQLite documentation](https://www.sqlite.org/lang_aggfunc.html#sumunc) for the difference between these aggregate functions.
@@ -2511,7 +2527,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
</details>
```swift
let request = Author.having(Author.books.max(Column("year")) >= 2010)
let request = Author.having(Author.books.max(\.year) >= 2010)
```
- Authors who wrote at least one book of kind "novel":
@@ -2530,7 +2546,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
</details>
```swift
let novels = Author.books.filter(Column("kind") == "novel")
let novels = Author.books.filter { $0.kind == "novel" }
let request = Author.having(novels.isEmpty == false)
```
@@ -2616,7 +2632,7 @@ Aggregates can be modified and combined with Swift operators:
</details>
```swift
let request = Author.having(Author.books.max(Column("year")) >= 2010)
let request = Author.having(Author.books.max(\.year) >= 2010)
```
- Arithmetic operators `+`, `-`, `*`, `/`
@@ -2656,7 +2672,7 @@ Aggregates can be modified and combined with Swift operators:
</details>
```swift
let request = Team.annotated(with: Team.players.min(Column("score")) ?? 0)
let request = Team.annotated(with: Team.players.min(\.score) ?? 0)
```
- SQL functions `ABS`, `CAST`, and `LENGTH` are available as the `abs`, `cast`, and `length` Swift functions:
@@ -2674,7 +2690,7 @@ Aggregates can be modified and combined with Swift operators:
</details>
```swift
let request = Team.annotated(with: abs(Team.players.max(Column("score"))))
let request = Team.annotated(with: abs(Team.players.max(\.score)))
```
### Isolation of Multiple Aggregates
@@ -2711,8 +2727,8 @@ In the example below, we use compute two aggregates from the same association `A
}
let request = Author.annotated(with:
Author.books.min(Column("year")), // association key "books"
Author.books.max(Column("year"))) // association key "books"
Author.books.min(\.year), // association key "books"
Author.books.max(\.year)) // association key "books"
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
```
@@ -2782,11 +2798,11 @@ But in the following example, we use the same association `Author.books` twice,
}
let novelCount = Author.books
.filter(Column("kind") == "novel")
.filter { $0.kind == "novel" }
.forKey("novels") // association key "novels"
.count
let theatrePlayCount = Author.books
.filter(Column("kind") == "theatrePlay")
.filter { $0.kind == "theatrePlay" }
.forKey("theatrePlays") // association key "theatrePlays"
.count
let request = Author.annotated(with: novelCount, theatrePlayCount)
@@ -2813,11 +2829,11 @@ But in the following example, we use the same association `Author.books` twice,
```swift
// WRONG: not counting distinct sets of associated books
let novelCount = Author.books // association key "books"
.filter(Column("kind") == "novel")
.filter { $0.kind == "novel" }
.count
.forKey("novelCount")
let theatrePlayCount = Author.books // association key "books"
.filter(Column("kind") == "theatrePlay")
.filter { $0.kind == "theatrePlay" }
.count
.forKey("theatrePlayCount")
let request = Author.annotated(with: novelCount, theatrePlayCount)
@@ -2847,11 +2863,11 @@ Those methods are defined on extensions to the `DerivableRequest` protocol:
```swift
extension DerivableRequest<Author> {
func filter(country: String) -> Self {
filter(Column("country") == country)
filter { $0.country == country }
}
func orderedByName() -> Self {
order(Column("name").collating(.localizedCaseInsensitiveCompare))
order { $0.name.collating(.localizedCaseInsensitiveCompare) }
}
}
@@ -2882,11 +2898,11 @@ See [Recommended Practices for Designing Record Types] for more information.
```swift
// NOT IMPLEMENTED: loading all authors along with their posthumous books
let authorAlias = TableAlias()
let authorAlias = TableAlias<Author>()
let request = Author
.aliased(authorAlias)
.including(all: Author.books
.filter(Column("publishDate") >= authorAlias[Column("deathDate")]))
.filter { $0.publishDate >= authorAlias.deathDate })
```
- **You can't use the `including(all:)` method with a [HasMany] and a [HasManyThrough] associations that share the same base association in the same request**:
@@ -2963,7 +2979,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[Further Refinements to Associations]: #further-refinements-to-associations
[The Types of Associations]: #the-types-of-associations
[FetchableRecord]: ../README.md#fetchablerecord-protocols
[migration]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations
[migration]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/migrations
[Record]: ../README.md#records
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
[Associations and the Database Schema]: #associations-and-the-database-schema
@@ -2998,16 +3014,16 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[Isolation of Multiple Aggregates]: #isolation-of-multiple-aggregates
[DerivableRequest Protocol]: #derivablerequest-protocol
[Known Issues]: #known-issues
[Row Adapters]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter
[Row Adapters]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/rowadapter
[query interface requests]: ../README.md#requests
[TableRecord]: ../README.md#tablerecord-protocol
[Recommended Practices for Designing Record Types]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices
[Recommended Practices for Designing Record Types]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices
[regular aggregating methods]: ../README.md#fetching-aggregated-values
[EncodableRecord]: ../README.md#persistablerecord-protocol
[PersistableRecord]: ../README.md#persistablerecord-protocol
[Codable Records]: ../README.md#codable-records
[persistence methods]: ../README.md#persistence-methods
[database observation tools]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
[database observation tools]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseobservation
[FAQ]: ../README.md#faq-associations
[common table expressions]: CommonTableExpressions.md
[Common Table Expressions]: CommonTableExpressions.md
+12 -12
View File
@@ -226,11 +226,11 @@ This publisher has the same behavior as ValueObservation:
- It notifies an initial value before the eventual changes.
- It may coalesce subsequent changes into a single notification.
- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/removeduplicates()) GRDB operator also.
- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/removeduplicates()) GRDB operator also.
- It only completes when it is cancelled.
- By default, it notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously.
This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservationScheduler](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservationscheduler).
This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservationScheduler](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservationscheduler).
For example, the `.immediate` scheduler makes sure the initial value is notified immediately when the publisher is subscribed. It can help your application update the user interface without having to wait for any asynchronous notifications:
@@ -332,7 +332,7 @@ let hallOfFamePublisher = ValueObservation
// 2nd request
let bestPlayers = try Player
.order(Column("score").desc)
.order(\.score.desc)
.limit(10)
.fetchAll(db)
@@ -358,7 +358,7 @@ let totalPlayerCountPublisher = ValueObservation
// OK
let bestPlayerPublisher = ValueObservation
.tracking(Player
.order(Column("score").desc)
.order(\.score.desc)
.limit(10)
.fetchAll)
.publisher(in: dbQueue)
@@ -382,23 +382,23 @@ let cancellable = hallOfFamePublisher.sink(
[Usage]: #usage
[Asynchronous Database Access]: #asynchronous-database-access
[Combine]: https://developer.apple.com/documentation/combine
[Database Changes Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
[Database Changes Observation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseobservation
[Database Observation]: #database-observation
[Combine and Data Consistency]: #combine-and-data-consistency
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseregionobservation
[Demo Application]: DemoApps/GRDBCombineDemo/README.md
[SQLite]: http://sqlite.org
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
[SharedValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/sharedvalueobservation
[ValueObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation
[SharedValueObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/sharedvalueobservation
[`DatabaseRegionObservation.publisher(in:)`]: #databaseregionobservationpublisherin
[`ValueObservation.publisher(in:scheduling:)`]: #valueobservationpublisherinscheduling
[`SharedValueObservation.publisher()`]: #sharedvalueobservationpublisher
[`readPublisher(receiveOn:value:)`]: #databasereaderreadpublisherreceiveonvalue
[`writePublisher(receiveOn:updates:)`]: #databasewriterwritepublisherreceiveonupdates
[`writePublisher(receiveOn:updates:thenRead:)`]: #databasewriterwritepublisherreceiveonupdatesthenread
[`migratePublisher(_:receiveOn:)`]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator/migratepublisher(_:receiveon:)
[`migratePublisher(_:receiveOn:)`]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasemigrator/migratepublisher(_:receiveon:)
[configured]: ../README.md#databasepool-configuration
[database pool]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool
[database queue]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue
[database snapshot]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesnapshot
[database pool]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool
[database queue]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasequeue
[database snapshot]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesnapshot
[scheduler]: https://developer.apple.com/documentation/combine/scheduler
+16 -10
View File
@@ -31,7 +31,7 @@ The CTE request can be provided as a [query interface request]:
// WITH playerName AS (SELECT name FROM player) ...
let playerNameCTE = CommonTableExpression(
named: "playerName",
request: Player.select(Column("name")))
request: Player.select(\.name))
```
You can feed a CTE with raw SQL as well (second and third examples use [SQL Interpolation]):
@@ -123,7 +123,7 @@ And we can then filter the `player` table with a subquery:
// WHERE name = (SELECT * FROM playerName)
let request = Player
.with(playerNameCTE)
.filter(Column("name") == playerNameCTE.all())
.filter { $0.name == playerNameCTE.all() }
```
> **Note**: the `with(_:)` method can be called as many times as a there are common table expressions in your request.
@@ -167,13 +167,13 @@ Common table expressions can also be used as subqueries, when you update or dele
// UPDATE player SET name = (SELECT * FROM playerName)
try Player
.with(playerNameCTE)
.updateAll(db, Column("name").set(to: playerNameCTE.all()))
.updateAll(db) { $0.name.set(to: playerNameCTE.all()) }
// WITH playerName AS (SELECT 'O''Brien')
// DELETE FROM player WHERE name = (SELECT * FROM playerName)
try Player
.with(playerNameCTE)
.filter(Column("name") == playerNameCTE.all())
.filter { $0.name == playerNameCTE.all() }
.deleteAll(db)
```
@@ -281,9 +281,15 @@ struct Chat: Codable, FetchableRecord, PersistableRecord {
}
struct Message: Codable, FetchableRecord, PersistableRecord {
var chatID: Int64
var chatId: Int64
var date: Date
...
enum Columns {
static let chatId = Column("chatId")
static let date = Column("date")
...
}
}
```
@@ -315,8 +321,8 @@ We start by defining the CTE request, which loads the latest messages of all cha
```swift
// SELECT *, MAX(date) FROM message GROUP BY chatID
let latestMessageRequest = Message
.annotated(with: max(Column("date")))
.group(Column("chatID"))
.annotated { max($0.date) }
.group(\.chatId)
```
We can now define the CTE for the latest messages:
@@ -324,7 +330,7 @@ We can now define the CTE for the latest messages:
```swift
// WITH latestMessage AS
// (SELECT *, MAX(date) FROM message GROUP BY chatID)
let latestMessageCTE = CommonTableExpression(
let latestMessageCTE = CommonTableExpression<Message>(
named: "latestMessage",
request: latestMessageRequest)
```
@@ -337,9 +343,9 @@ The association from a chat to its latest message follows:
let latestMessage = Chat.association(
to: latestMessageCTE,
on: { chat, latestMessage in
chat[Column("id")] == latestMessage[Column("chatID")]
chat.id == latestMessage.chatId
})
.order(Column("date").desc)
.order(\.date.desc)
```
The final request can now be defined:
+1 -1
View File
@@ -1,4 +1,4 @@
:twisted_rightwards_arrows: Concurrency
=======================================
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
This guide [has moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency).
+34 -28
View File
@@ -5,54 +5,56 @@ By default, GRDB uses the version of SQLite that ships with the target operating
**You can build GRDB with a custom build of [SQLite 3.47.2](https://www.sqlite.org/changes.html).**
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver).
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactionobserver).
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).
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.
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,10 +12,10 @@ 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>
/// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections>
private let dbWriter: any DatabaseWriter
/// Creates a `AppDatabase`, and makes sure the database schema
@@ -30,19 +30,19 @@ final class AppDatabase: Sendable {
/// The DatabaseMigrator that defines the database schema.
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
/// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/migrations>
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
#if DEBUG
// Speed up development by nuking the database when migrations change
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations#The-eraseDatabaseOnSchemaChange-Option>
// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/migrations#The-eraseDatabaseOnSchemaChange-Option>
migrator.eraseDatabaseOnSchemaChange = true
#endif
migrator.registerMigration("v1") { db in
// Create a table
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema>
// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema>
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
@@ -77,7 +77,7 @@ extension AppDatabase {
// }
//
// Uncomment for enabling SQL logging if the `SQL_TRACE` environment variable is set.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/trace(options:_:)>
// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/trace(options:_:)>
// if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil {
// config.prepareDatabase { db in
// let dbName = db.description
@@ -93,7 +93,7 @@ extension AppDatabase {
// #if DEBUG
// // Protect sensitive information by enabling verbose debugging in
// // DEBUG builds only.
// // See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
// // See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/configuration/publicstatementarguments>
// config.publicStatementArguments = true
// #endif
@@ -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)
@@ -64,45 +64,3 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
id = inserted.rowID
}
}
// Convenience access to player columns in this file
private typealias Columns = Player.Columns
// MARK: - Player Database Requests
/// Define some player requests used by the application.
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
extension DerivableRequest<Player> {
/// A request of players ordered by name.
///
/// For example:
///
/// let players: [Player] = try dbWriter.read { db in
/// try Player.all().orderedByName().fetchAll(db)
/// }
func orderedByName() -> Self {
// Sort by name in a localized case insensitive fashion
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
order(Columns.name.collating(.localizedCaseInsensitiveCompare))
}
/// A request of players ordered by score.
///
/// For example:
///
/// let players: [Player] = try dbWriter.read { db in
/// try Player.all().orderedByScore().fetchAll(db)
/// }
/// let bestPlayer: Player? = try dbWriter.read { db in
/// try Player.all().orderedByScore().fetchOne(db)
/// }
func orderedByScore() -> Self {
// Sort by descending score, and then by name, in a
// localized case insensitive fashion
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
order(
Columns.score.desc,
Columns.name.collating(.localizedCaseInsensitiveCompare))
}
}
@@ -8,7 +8,7 @@ extension AppDatabase {
private static func makeShared() -> AppDatabase {
do {
// Apply recommendations from
// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
// <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections>
// Create the "Application Support/Database" directory if needed
let fileManager = FileManager.default
@@ -47,7 +47,7 @@ extension AppDatabase {
/// Creates an empty database for SwiftUI previews
static func empty() -> AppDatabase {
// Connect to an in-memory database
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
// See https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections
let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration())
return try! AppDatabase(dbQueue)
}
@@ -41,15 +41,22 @@ import GRDB
let observation = ValueObservation.tracking { [ordering] db in
switch ordering {
case .byName:
try Player.all().orderedByName().fetchAll(db)
try Player
.order { $0.name.collating(.localizedCaseInsensitiveCompare) }
.fetchAll(db)
case .byScore:
try Player.all().orderedByScore().fetchAll(db)
try Player
.order { [
$0.score.desc,
$0.name.collating(.localizedCaseInsensitiveCompare),
] }
.fetchAll(db)
}
}
// 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
@@ -11,8 +11,8 @@ The topics covered in this demo are:
- How to setup a database in an iOS app.
- How to define a simple [Codable Record](../../../README.md#codable-records).
- How to track database changes and animate a SwiftUI List with [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation).
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
- How to track database changes and animate a SwiftUI List with [ValueObservation](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation).
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices).
- How to feed SwiftUI previews with a transient database.
**Files of interest:**
@@ -23,7 +23,7 @@ The topics covered in this demo are:
- [AppDatabase.swift](GRDBDemo/Database/AppDatabase.swift)
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator) in order to setup the database schema, and provides methods that read and write.
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasemigrator) in order to setup the database schema, and provides methods that read and write.
`AppDatabase` is [tested](GRDBDemoTests/AppDatabaseTests.swift).
+1 -1
View File
@@ -2,4 +2,4 @@
FetchedRecordsController has been removed in GRDB 5.
See [Database Observation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation) for other ways to observe the database.
See [Database Observation](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseobservation) for other ways to observe the database.
+7 -7
View File
@@ -91,7 +91,7 @@ Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this do
**FTS3 and FTS4 full-text tables store and index textual content.**
Create tables with the `create(virtualTable:using:)` method:
Create tables with the `create(virtualTable:options:using:_:)` method:
```swift
// CREATE VIRTUAL TABLE document USING fts3(content)
@@ -301,7 +301,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
```
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statementarguments):
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
```swift
let documents = try Document.fetchAll(db,
@@ -316,7 +316,7 @@ Use them in the [query interface](../README.md#the-query-interface):
let documents = try Document.matching(pattern).fetchAll(db)
// Search in a specific column:
let documents = try Document.filter(Column("content").match(pattern)).fetchAll(db)
let documents = try Document.filter { $0.content.match(pattern) }.fetchAll(db)
```
@@ -326,7 +326,7 @@ let documents = try Document.filter(Column("content").match(pattern)).fetchAll(d
To use FTS5, you'll need a [custom SQLite build] that activates the `SQLITE_ENABLE_FTS5` compilation option.
Create FTS5 tables with the `create(virtualTable:using:)` method:
Create FTS5 tables with the `create(virtualTable:options:using:_:)` method:
```swift
// CREATE VIRTUAL TABLE document USING fts5(content)
@@ -550,7 +550,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
```
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statementarguments):
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
```swift
let documents = try Document.fetchAll(db,
@@ -565,7 +565,7 @@ Use them in the [query interface](../README.md#the-query-interface):
let documents = try Document.matching(pattern).fetchAll(db)
// Search in a specific column:
let documents = try Document.filter(Column("content").match(pattern)).fetchAll(db)
let documents = try Document.filter { $0.content.match(pattern) }.fetchAll(db)
```
@@ -689,7 +689,7 @@ let books = Book.fetchAll(db, sql: sql, arguments: [pattern])
**You can define [record](../README.md#records) types around the full-text virtual tables.**
The primary key of those tables is the hidden `rowid` column. If you need to fetch, delete, and update full-text records by primary key, you will have to expose this column to the record type. See [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) for more information.
The primary key of those tables is the hidden `rowid` column. If you need to fetch, delete, and update full-text records by primary key, you will have to expose this column to the record type. See [The Database Schema](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema) for more information.
## Unicode Full-Text Gotchas
+4 -4
View File
@@ -501,10 +501,10 @@ let publisher = observation
This change is innocuous for database boolean values that are `0`, `1`, or `NULL`. However, it is a breaking change for all other database values.
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation
[ValueObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseregionobservation
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
[removeDuplicates]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/removeduplicates()
[removeDuplicates]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/removeduplicates()
[Custom SQL functions]: ../README.md#custom-sql-functions
[Batch updates]: ../README.md#update-requests
[SQL Interpolation]: SQLInterpolation.md
@@ -512,4 +512,4 @@ let publisher = observation
[SQLRequest]: ../README.md#custom-requests
[QueryInterfaceRequest]: ../README.md#requests
[Combine publishers]: Combine.md
[Database Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
[Database Observation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseobservation
+1 -1
View File
@@ -195,7 +195,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi
To help you update your applications with persistence callbacks, let's look at two examples.
First, check the updated [Single-Row Tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables) guide, if your application defines a "singleton record".
First, check the updated [Single-Row Tables](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/singlerowtables) guide, if your application defines a "singleton record".
Next, let's consider a record that performs some validation before insertion and updates. In GRDB 5, this would look like:
+55 -7
View File
@@ -10,6 +10,7 @@ Migrating From GRDB 6 to GRDB 7
- [Column Coding Strategies](#column-coding-strategies)
- [Cancellable Async Database Accesses](#cancellable-async-database-accesses)
- [Default Transaction Kind](#default-transaction-kind)
- [Associations to record types named Bias, Focus, Gas, and Lens](#associations-to-record-types-named-bias-focus-gas-and-lens)
- [ValueObservation and the Main Actor](#valueobservation-and-the-main-actor)
- [Access to SQLite C functions](#access-to-sqlite-c-functions)
- [The Record Base Class is Discouraged](#the-record-base-class-is-discouraged)
@@ -96,6 +97,53 @@ try await task.value
Other asynchronous database accesses, such as methods accepting a completion blocks (`asyncRead`, etc.), Combine publishers, RxSwift observables, do not handle cancellation and will proceed to completion by default.
## Associations to record types named Bias, Focus, Gas, and Lens
GRDB 7 has fixed its singularization and pluralization rules for database tables named "bias", "focus", "gas", and "lens".
If your application defines associations to those tables, you can now rely on proper inflections (pluralization and singularization).
With GRDB 7, you can remove custom association keys:
```swift
struct Camera: TableRecord {
// GRDB 6: fix incorrect GRDB inflection
static let lenses = hasMany(Lens.self).forKey("lenses")
// GRDB 7
static let lenses = hasMany(Lens.self)
}
```
If your application was not specifying custom association keys in order to fix the wrong inflections, then it may define types that will no longer decode their properties as intended:
```swift
// Works in GRDB 6, breaks in GRDB 7
struct CameraWithLenses: Decodable, FetchableRecord {
var camera: Camera
var lens: [Lens] // <- incorrect pluralization
}
let results = Camera
.including(all: Camera.lenses)
.asRequest(of: CameraWithLenses.self)
.fetchAll(db)
```
There are two possible solutions. One is to rename properties, the other is to keep on using the wrong inflection (it's your call):
```swift
// GRDB 7, alternative 1
struct CameraWithLenses: Decodable, FetchableRecord {
var camera: Camera
var lenses: [Lens] // <- fixed pluralization
}
// GRDB 7, alternative 2
struct Camera: TableRecord {
// Use "lens" instead of "lenses" for GRDB 6 compatibility.
static let lenses = hasMany(Lens.self).forKey("lens")
}
```
## Default Transaction Kind
Some applications specify a default transaction kind, which was previously recommended in the [Sharing a Database] guide:
@@ -114,7 +162,7 @@ You can still specify a transaction kind explicitly when necessary. See [Transac
In GRDB 7, `ValueObservation` fosters the main actor, because it is frequently used to automatically update database values on screen.
By default, its [`start`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/start(in:scheduling:onerror:onchange:)) method must be started on the main actor, and its notification callbacks run on the main actor as well.
By default, its [`start`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/start(in:scheduling:onerror:onchange:)) method must be started on the main actor, and its notification callbacks run on the main actor as well.
It is not necessary to call `MainActor.assumeIsolated` in `ValueObservation` callbacks:
@@ -221,14 +269,14 @@ Do not miss [Swift Concurrency and GRDB], for more recommendations regarding non
## Other Changes
- `DatabasePool.concurrentRead` has been removed. Use [`asyncConcurrentRead`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool/asyncconcurrentread(_:)) instead.
- `DatabasePool.concurrentRead` has been removed. Use [`asyncConcurrentRead`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool/asyncconcurrentread(_:)) instead.
- The `PersistenceContainer` subscript no longer guarantees that the value returned is the same as what was previously set. It only guarantees that both values are encoded identically in the database.
- The async sequence returned by [`ValueObservation.values`](https://swiftpackageindex.com/groue/grdb.swiftdocumentation/grdb/valueobservation/values(in:scheduling:bufferingpolicy:)) now iterates on the cooperative thread pool by default. Use .mainActor as the scheduler if you need the previous behavior.
- The async sequence returned by [`ValueObservation.values`](https://swiftpackageindex.com/groue/GRDB.swiftdocumentation/grdb/valueobservation/values(in:scheduling:bufferingpolicy:)) now iterates on the cooperative thread pool by default. Use .mainActor as the scheduler if you need the previous behavior.
[Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide
[Sharing a Database]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/databasesharing
[Transaction Kinds]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/transactions#Transaction-Kinds
[Swift Concurrency and GRDB]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/swiftconcurrency
[Record]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/record
[Sharing a Database]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing
[Transaction Kinds]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactions#Transaction-Kinds
[Swift Concurrency and GRDB]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/swiftconcurrency
[Record]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/record
@@ -1,4 +1,4 @@
Good Practices for Designing Record Types
=========================================
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
This guide [has moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices).
+1 -1
View File
@@ -1,3 +1,3 @@
# Migrations
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations).
This guide [has moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/migrations).
@@ -32,14 +32,14 @@ try dbQueue.inDatabase { db in
CREATE TABLE place (
id INTEGER PRIMARY KEY,
title TEXT,
favorite BOOLEAN NOT NULL,
isFavorite BOOLEAN NOT NULL,
latitude DOUBLE NOT NULL,
longitude DOUBLE NOT NULL
)
""")
try db.execute(sql: """
INSERT INTO place (title, favorite, latitude, longitude)
INSERT INTO place (title, isFavorite, latitude, longitude)
VALUES (?, ?, ?, ?)
""", arguments: ["Paris", true, 48.85341, 2.3488])
let parisId = db.lastInsertedRowID
@@ -52,11 +52,11 @@ try! dbQueue.inDatabase { db in
let rows = try Row.fetchCursor(db, sql: "SELECT * FROM place")
while let row = try rows.next() {
let title: String = row["title"]
let favorite: Bool = row["favorite"]
let isFavorite: Bool = row["isFavorite"]
let coordinate = CLLocationCoordinate2D(
latitude: row["latitude"],
longitude: row["longitude"])
print("Fetched", title, favorite, coordinate)
print("Fetched", title, isFavorite, coordinate)
}
let placeCount = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM place")! // Int
@@ -69,35 +69,43 @@ try! dbQueue.inDatabase { db in
struct Place {
var id: Int64?
var title: String?
var favorite: Bool
var isFavorite: Bool
var coordinate: CLLocationCoordinate2D
}
// Adopt FetchableRecord
extension Place : FetchableRecord {
init(row: Row) {
id = row["id"]
title = row["title"]
favorite = row["favorite"]
id = row[Columns.id]
title = row[Columns.title]
isFavorite = row[Columns.isFavorite]
coordinate = CLLocationCoordinate2DMake(
row["latitude"],
row["longitude"])
row[Columns.latitude],
row[Columns.longitude])
}
}
// Adopt TableRecord
extension Place : TableRecord {
static let databaseTableName = "place"
enum Columns {
static let id = Column("id")
static let title = Column("title")
static let isFavorite = Column("isFavorite")
static let latitude = Column("latitude")
static let longitude = Column("longitude")
}
}
// Adopt MutablePersistableRecord
extension Place : MutablePersistableRecord {
func encode(to container: inout PersistenceContainer) throws {
container["id"] = id
container["title"] = title
container["favorite"] = favorite
container["latitude"] = coordinate.latitude
container["longitude"] = coordinate.longitude
container[Columns.id] = id
container[Columns.title] = title
container[Columns.isFavorite] = isFavorite
container[Columns.latitude] = coordinate.latitude
container[Columns.longitude] = coordinate.longitude
}
mutating func didInsert(_ inserted: InsertionSuccess) {
@@ -109,13 +117,13 @@ try dbQueue.inDatabase { db in
var berlin = Place(
id: nil,
title: "Berlin",
favorite: false,
isFavorite: false,
coordinate: CLLocationCoordinate2DMake(52.52437, 13.41053))
try berlin.insert(db)
berlin.id // some value
berlin.favorite = true
berlin.isFavorite = true
try berlin.update(db)
// Fetch from SQL
@@ -124,13 +132,10 @@ try dbQueue.inDatabase { db in
//: Avoid SQL with the query interface:
let title = Column("title")
let favorite = Column("favorite")
berlin = try Place.filter(title == "Berlin").fetchOne(db)! // Place
berlin = try Place.filter { $0.title == "Berlin" }.fetchOne(db)! // Place
let paris = try Place.fetchOne(db, key: 1) // Place?
let favoritePlaces = try Place // [Place]
.filter(favorite == true)
.order(title)
.filter { $0.isFavorite == true }
.order { $0.title }
.fetchAll(db)
}
+14 -13
View File
@@ -93,7 +93,7 @@ Columns are special expressions that allow some optimizations and niceties:
ValueObservation.tracking { db in
try Player.fetchOne(db, id: 1)
// or
try Player.filter(Column("id") == 1).fetchOne(db)
try Player.filter { $0.id == 1 }.fetchOne(db)
}
// Non-optimized observations
@@ -110,7 +110,7 @@ Columns are special expressions that allow some optimizations and niceties:
// Nicer SQL
// SELECT * FROM player WHERE id = 1
try Player.fetchOne(db, id: 1)
try Player.filter(Column("id") == 1).fetchOne(db)
try Player.filter { $0.id == 1 }.fetchOne(db)
// Less nice SQL
// SELECT * FROM player WHERE id = 1 LIMIT 1
@@ -195,7 +195,7 @@ protocol DerivableRequest<RowDecoder>: AggregatingRequest, FilteredRequest,
- `SelectionRequest` provides selection methods such as `select(selection)` or `annotated(with: selection)`
- `TableRequest` provides table targeting methods such as `aliased(tableAlias)`
DerivableRequest makes it possible to build reusable code snippets that apply to both requests and associations. You'll read more about it in the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) and [Associations](AssociationsBasics.md).
DerivableRequest makes it possible to build reusable code snippets that apply to both requests and associations. You'll read more about it in the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) and [Associations](AssociationsBasics.md).
### FetchRequest
@@ -261,7 +261,7 @@ The basic value types conform to [DatabaseValueConvertible] so that they can fee
```swift
// SELECT * FROM player WHERE name = 'O''Brien'
// ~~~~~~~~~~
Player.filter(Column("name") == "O'Brien")
Player.filter { $0.name == "O'Brien" }
```
### QueryInterfaceRequest
@@ -346,8 +346,9 @@ Functions and methods that build an SQL expression should return an SQLExpressio
```swift
// SELECT * FROM player WHERE LENGTH(name) > 0
let expression = length(Column("name")) > 0 // SQLExpression
Player.filter(expression)
Player.filter {
length($0.name) > 0 // SQLExpression
}
```
When it looks like GRDB APIs are unable to build a particular expression, use [SQL]:
@@ -358,7 +359,7 @@ func date(_ value: SQLSpecificExpressible) -> SQLExpression {
}
// SELECT * FROM player WHERE DATE(createdAt) = '2020-01-23'
let request = Player.filter(date(Column("createdAt")) == "2020-01-23")
let request = Player.filter { date($0.createdAt) == "2020-01-23" }
```
This technique, based on [SQL Interpolation], is composable and works well even when several tables are involved. See how the `createdAt` column below is correctly attributed to the `player` table:
@@ -368,7 +369,7 @@ This technique, based on [SQL Interpolation], is composable and works well even
// JOIN team ON team.id = player.teamId
// WHERE DATE(player.createdAt) = '2020-01-23'
let request = Player
.filter(date(Column("createdAt")) == "2020-01-23")
.filter { date($0.createdAt) == "2020-01-23" }
.including(required: Player.team)
```
@@ -497,7 +498,7 @@ protocol SQLSelectable {
SQLSelectable feeds the `select()` method of the query interface:
```swift
Player.select(AllColumns())
Player.select(.allColumns)
Player.select(Column("name"), Column("score"))
```
@@ -505,7 +506,7 @@ All [SQLSpecificExpressible] values are selectable. Other selectable values are:
```swift
// SELECT * FROM player
Player.select(AllColumns())
Player.select(.allColumns)
// SELECT MAX(score) AS maxScore FROM player
Player.select(max(Column("score")).forKey("maxScore"))
@@ -583,7 +584,7 @@ SQLSubqueryable provides the GRDB support for subqueries. Its [SQLSpecificExpres
// SELECT * FROM player
// WHERE score >= (SELECT AVG(score) FROM player)
let averageScore = Player.select(average(Column("score")))
Player.filter(Column("score") >= averageScore)
Player.filter { $0.score >= averageScore }
```
SQLSubqueryable has the `contains(_:)` and `exists()` methods that support the `value IN (subquery)` and `EXISTS (subquery)` expressions.
@@ -607,8 +608,8 @@ myRequest(Player.select(...).filter(...))
[association aggregates]: AssociationsBasics.md#association-aggregates
[Column]: #column
[ColumnExpression]: #columnexpression
[DatabaseRegionConvertible]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionconvertible
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation
[DatabaseRegionConvertible]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseregionconvertible
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseregionobservation
[DatabaseValue]: #databasevalue
[DatabaseValueConvertible]: #databasevalueconvertible
[DerivableRequest]: #derivablerequest
+2 -2
View File
@@ -175,7 +175,7 @@ func date(_ expression: SQLExpressible) -> SQLExpression {
SQL("DATE(\(expression))").sqlExpression
}
let request = Player.filter(date(Column("createdAt")) == "2020-01-23")
let request = Player.filter { date($0.createdAt) == "2020-01-23" }
```
@@ -365,7 +365,7 @@ Let's extend Player with database methods.
This chapter lists all kinds of supported interpolations.
- Types adopting the [TableRecord] protocol and [Table](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/table) instances:
- Types adopting the [TableRecord] protocol and [Table](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/table) instances:
```swift
struct Player: TableRecord { ... }
+1 -1
View File
@@ -1,4 +1,4 @@
Sharing a Database
==================
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing).
This guide [has moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing).
+1 -1
View File
@@ -1,4 +1,4 @@
Single-Row Tables
=================
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables).
This guide [has moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/singlerowtables).
+10 -10
View File
@@ -90,7 +90,7 @@ For your convenience, those record protocols can be derived from the [Decodable
Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with **database change notifications**, with many advantages.
See [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) for some practical advice.
See [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) for some practical advice.
### Allow database records to cross threads
@@ -149,16 +149,16 @@ Next, you choose the dispatch queue on which notifications happen (generally the
Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, or SQL triggers. GRDB roots its notification system in the rock-solid SQLite itself, so that high-level requests and raw SQL queries are equally supported.
See [Database Observation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation) for further information.
See [Database Observation](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseobservation) for further information.
### Non-blocking database reads
GRDB ships with two ways to access databases, [database queues](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue) and [pools](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool).
GRDB ships with two ways to access databases, [database queues](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasequeue) and [pools](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool).
Database queues look a lot like FMDB's [FMDatabaseQueue](https://github.com/ccgus/fmdb#using-fmdatabasequeue-and-thread-safety): they serialize database accesses in a serial dispatch queue. There is never more than one thread that is accessing the database. This means that a long running database transaction that happens in a background thread, such as the synchronization of your local database from a remote server, can block your UI. As long as the queue is busy, the main thread can't fetch the values it wants to display on screen.
[Database pools](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured).
[Database pools](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured).
### Strong and clear multi-threading guarantees
@@ -190,7 +190,7 @@ Finally, raw FMDatabase, SQLite.swift, and Core Data are the hardest tools, and
For detailed information about GRDB concurrency, check the [Concurrency Guide].
For practical advice on designing the database access layer of your application, see the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
For practical advice on designing the database access layer of your application, see the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices).
### Never pay for using raw SQL
@@ -207,13 +207,13 @@ try player.updateChanges {
// SELECT * FROM player ORDER BY score DESC LIMIT 10
let bestPlayers: [Player] = try Player
.order(scoreColumn.desc)
.order(\.score.desc)
.limit(10)
.fetchAll(db)
// SELECT MAX(score) FROM player
let maximumScore: Int? = try Player
.select(max(scoreColumn))
.select { max($0.score) }
.asRequestOf(Int.self)
.fetchOne(db)
@@ -285,12 +285,12 @@ If this little tour of GRDB has convinced you, the real trip starts here: [GRDB]
Happy GRDB! :gift:
[Concurrency Guide]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency
[Concurrency Guide]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency
[Core Data]: https://developer.apple.com/documentation/coredata
[DatabasePool]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool
[DatabasePool]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool
[Diesel]: http://diesel.rs
[FCModel]: https://github.com/marcoarment/FCModel
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
[ValueObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation
[Fluent]: https://github.com/vapor/fluent
[FMDB]: https://github.com/ccgus/fmdb
[GRDB]: https://github.com/groue/GRDB.swift
+3 -3
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '7.0.0-beta.6'
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
+27 -2
View File
@@ -68,6 +68,7 @@
562206071E420EA4005860AC /* DatabasePoolConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */; };
562206081E420EA4005860AC /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; };
5622060C1E420EB3005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */; };
56231A442DCF3A19007676E4 /* TableAlias.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56231A432DCF3A19007676E4 /* TableAlias.swift */; };
562393181DECC02000A6B01F /* RowFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393171DECC02000A6B01F /* RowFetchTests.swift */; };
562393301DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; };
5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */; };
@@ -80,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 */; };
@@ -222,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 */; };
@@ -272,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 */; };
@@ -286,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 */; };
@@ -487,6 +492,7 @@
561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = "<group>"; };
561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = "<group>"; };
561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = "<group>"; };
56231A432DCF3A19007676E4 /* TableAlias.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableAlias.swift; sourceTree = "<group>"; };
562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = "<group>"; };
5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = "<group>"; };
5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = "<group>"; };
@@ -500,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>"; };
@@ -671,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>"; };
@@ -767,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>"; };
@@ -788,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>"; };
@@ -993,6 +1003,7 @@
56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */,
563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */,
563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */,
568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */,
);
name = PersistableRecord;
sourceTree = "<group>";
@@ -1284,6 +1295,7 @@
568D13182207213E00674B58 /* SQLQueryGenerator.swift */,
56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */,
56F89E0B2A57EC16002FE2AA /* SQLTableGenerator.swift */,
56231A432DCF3A19007676E4 /* TableAlias.swift */,
);
path = SQLGeneration;
sourceTree = "<group>";
@@ -1481,6 +1493,7 @@
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */,
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */,
568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */,
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */,
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */,
@@ -1587,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 */,
@@ -1608,6 +1622,7 @@
56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */,
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
56B7EE822863781300C0525F /* WALSnapshot.swift */,
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
5605F1471C672E4000235C62 /* Support */,
);
path = Core;
@@ -1836,8 +1851,9 @@
DC3773EA19C8CBB3004FCF85 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = YES;
LastSwiftUpdateCheck = 0730;
LastUpgradeCheck = 1400;
LastUpgradeCheck = 2600;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
56E5D7F81B4D422D00430942 = {
@@ -2003,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 */,
@@ -2107,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 */,
@@ -2168,6 +2186,7 @@
buildActionMask = 2147483647;
files = (
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */,
56231A442DCF3A19007676E4 /* TableAlias.swift in Sources */,
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
5685C1932AD52EE600DA4B7A /* ListDumpFormat.swift in Sources */,
56158780288D875E00A67323 /* Optional.swift in Sources */,
@@ -2176,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 */,
@@ -2199,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 */,
@@ -2531,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 = (
@@ -2538,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;
@@ -2562,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 = (
@@ -2569,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"
+29 -10
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
@@ -144,7 +147,7 @@ public struct Configuration: Sendable {
/// do {
/// // The sensitive information to protect
/// let email = "..."
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
/// let player = try Player.filter { $0.email == email }.fetchOne(db)
/// } catch {
/// // By default, sensitive information is NOT printed
/// // when an error occurs:
@@ -173,7 +176,7 @@ public struct Configuration: Sendable {
/// do {
/// // The sensitive information to protect
/// let email = "..."
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
/// let player = try Player.filter { $0.email == email }.fetchOne(db)
/// } catch {
/// // Sensitive information is printed in DEBUG builds:
/// print(error)
@@ -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
+11 -10
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,
@@ -494,11 +497,9 @@ extension Database {
switch ResultCode(rawValue: resultCode) {
case .SQLITE_INTERRUPT, .SQLITE_ABORT:
if suspensionMutex.load().isCancelled {
// The only error that a user sees when a Task is cancelled
// is CancellationError.
throw CancellationError()
}
// The only error that a user sees when a Task is cancelled
// is CancellationError.
try suspensionMutex.load().checkCancellation()
default:
break
}
+149 -28
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:)``
@@ -121,6 +129,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``clearSchemaCache()``
/// - ``logError``
/// - ``releaseMemory()``
/// - ``sqliteLibVersionNumber``
/// - ``trace(options:_:)``
///
/// ### Supporting Types
@@ -168,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
@@ -186,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``
@@ -302,6 +324,21 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
/// An integer equal to [`SQLITE_VERSION_NUMBER`](https://www.sqlite.org/c3ref/c_source_id.html).
///
/// This property returns the result of `sqlite3_libversion_number()`.
///
/// ```swift
/// // Prints, for example, "3048000"
/// print(Database.sqliteLibVersionNumber)
/// ```
@inline(__always)
@inlinable
public static var sqliteLibVersionNumber: CInt {
sqlite3_libversion_number()
}
/// Whether the database region selected by statement execution is
/// recorded into `selectedRegion` by `track(_:)`.
///
@@ -325,10 +362,22 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// If true, the database access has been cancelled.
var isCancelled: Bool
/// If true, the database throws an error when it is cancelled.
var interruptsWhenCancelled: Bool
func checkCancellation() throws {
if isCancelled, interruptsWhenCancelled {
throw CancellationError()
}
}
}
/// Support for `checkForSuspensionViolation(from:)`
let suspensionMutex = Mutex(Suspension(isSuspended: false, isCancelled: false))
let suspensionMutex = Mutex(Suspension(
isSuspended: false,
isCancelled: false,
interruptsWhenCancelled: true))
// MARK: - Transaction Date
@@ -414,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
@@ -431,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
@@ -778,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.
@@ -1121,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
@@ -1195,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 true
}
if needsInterrupt {
interrupt()
if needsInterrupt {
if let sqliteConnection = connection.sqliteConnection {
sqlite3_interrupt(sqliteConnection)
}
}
}
}
@@ -1221,6 +1282,24 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
/// Within the given closure, Task cancellation does not interrupt
/// database accesses.
func ignoringCancellation<T>(_ value: () throws -> T) rethrows -> T {
let previous = suspensionMutex.withLock {
let previous = $0.interruptsWhenCancelled
$0.interruptsWhenCancelled = false
return previous
}
defer {
suspensionMutex.withLock {
$0.interruptsWhenCancelled = previous
}
}
return try value()
}
/// Support for `checkForSuspensionViolation(from:)`
private func journalMode() throws -> String {
if let journalMode = journalModeCache {
@@ -1229,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) }
@@ -1272,6 +1351,17 @@ 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 {
return
}
// How should we interrupt the statement?
enum Interrupt {
case abort // Rollback and throw SQLITE_ABORT
@@ -1281,7 +1371,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
let interrupt: Interrupt? = try suspensionMutex.withLock { suspension in
// Check for cancellation first, so that the only error that
// a user sees when a Task is cancelled is CancellationError.
if suspension.isCancelled {
if suspension.isCancelled, suspension.interruptsWhenCancelled {
return .cancel
}
@@ -1415,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()
@@ -1558,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()
@@ -1676,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.
@@ -1931,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
@@ -2058,6 +2176,9 @@ extension Database {
/// That's the reason why it is recommended to store JSON as text.
public static let jsonText = ColumnType(rawValue: "TEXT")
/// The `BLOB` column type, suitable for JSONB columns.
public static let jsonb = ColumnType(rawValue: "BLOB")
/// The `INTEGER` column type.
public static let integer = ColumnType(rawValue: "INTEGER")
+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
+61 -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
/// 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.
@@ -173,13 +199,20 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// }
/// return int * int
/// }
///
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// let dbQueue = try DatabaseQueue()
/// try dbQueue.read { db in
/// db.add(function: square)
///
/// // SELECT square(score) FROM player
/// let squaredScores = let Player
/// .select(square(Column("score")), as: Int.self)
/// .select({ square($0.score) }, as: Int.self)
/// .fetchAll(db)
/// }
/// ```
@@ -249,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
}
}
@@ -276,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)
@@ -289,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)
}
@@ -305,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)
}
@@ -457,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
+7 -2
View File
@@ -83,6 +83,7 @@ extension DatabaseRegionObservation {
/// - parameter onChange: The closure to execute when a transaction has
/// modified the observed region.
/// - returns: A DatabaseCancellable that can stop the observation.
@preconcurrency // For RxGRDB, see <https://github.com/RxSwiftCommunity/RxGRDB/issues/72#issuecomment-2631125658>
public func start(
in writer: any DatabaseWriter,
onError: @escaping @Sendable (Error) -> Void,
@@ -200,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,
@@ -211,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
+65 -16
View File
@@ -541,13 +541,20 @@ extension DatabaseValueConvertible {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .select(Column("score"))
/// .filter(Column("lastName") == lastName)
/// .select(\.score)
/// .filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -584,13 +591,20 @@ extension DatabaseValueConvertible {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .select(Column("score"))
/// .filter(Column("lastName") == lastName)
/// .select(\.score)
/// .filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -623,13 +637,20 @@ extension DatabaseValueConvertible {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .select(Column("score"))
/// .filter(Column("lastName") == lastName)
/// .select(\.score)
/// .filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -657,13 +678,20 @@ extension DatabaseValueConvertible where Self: Hashable {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .select(Column("score"))
/// .filter(Column("lastName") == lastName)
/// .select(\.score)
/// .filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -696,13 +724,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .filter(Column("lastName") == lastName)
/// .select(Column("score"), as: Int.self)
/// .filter { $0.lastName == lastName }
/// .select(\.score, as: Int.self)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -736,13 +771,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .filter(Column("lastName") == lastName)
/// .select(Column("score"), as: Int.self)
/// .filter { $0.lastName == lastName }
/// .select(\.score, as: Int.self)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -772,13 +814,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .filter(Column("lastName") == lastName)
/// .select(Column("score"), as: Int.self)
/// .filter { $0.lastName == lastName }
/// .select(\.score, as: Int.self)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -808,8 +857,8 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable {
///
/// // Query interface request
/// let request = Player
/// .filter(Column("lastName") == lastName)
/// .select(Column("score"), as: Int.self)
/// .filter { $0.lastName == lastName }
/// .select(\.score, as: Int.self)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
+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
+393 -121
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 {
@@ -1735,11 +1983,17 @@ extension Row {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
/// let request = Player.filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Row> = """
@@ -1784,11 +2038,17 @@ extension Row {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
/// let request = Player.filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Row> = """
@@ -1816,11 +2076,17 @@ extension Row {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
/// let request = Player.filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Row> = """
@@ -1852,11 +2118,17 @@ extension Row {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player.filter(Column("lastName") == lastName)
/// let request = Player.filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Row> = """
+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] = []
+2 -2
View File
@@ -118,7 +118,7 @@ public struct SQL: Sendable {
}
}
fileprivate func qualified(with alias: TableAlias) -> Element {
fileprivate func qualified(with alias: TableAliasBase) -> Element {
switch self {
case .sql:
// A raw SQL string can't be qualified with a table alias,
@@ -192,7 +192,7 @@ public struct SQL: Sendable {
try elements.map { try $0.sql(context) }.joined()
}
func qualified(with alias: TableAlias) -> SQL {
func qualified(with alias: TableAliasBase) -> SQL {
SQL(elements: elements.map { $0.qualified(with: alias) })
}
}
+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()
}
}
}
}
+12 -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
@@ -92,6 +95,9 @@ public final class Statement {
/// The effects on the database (reported by `sqlite3_set_authorizer`).
private(set) var authorizerEventKinds: [DatabaseEventKind] = []
/// If true, the statement executes is a `PRAGMA QUERY_ONLY` statement.
private(set) var isQueryOnlyPragma = false
/// A boolean value indicating if the prepared statement makes no direct
/// changes to the content of the database file.
///
@@ -138,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)
@@ -160,6 +166,7 @@ public final class Statement {
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
self.transactionEffect = authorizer.transactionEffect
self.authorizerEventKinds = authorizer.databaseEventKinds
self.isQueryOnlyPragma = authorizer.isQueryOnlyPragma
}
deinit {
+16 -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)
@@ -41,6 +44,9 @@ final class StatementAuthorizer {
/// savepoint statement.
var transactionEffect: Statement.TransactionEffect?
/// If true, the statement executes is a `PRAGMA QUERY_ONLY` statement.
var isQueryOnlyPragma = false
private var isDropStatement = false
init(_ database: Database) {
@@ -67,6 +73,7 @@ final class StatementAuthorizer {
databaseEventKinds = []
invalidatesDatabaseSchemaCache = false
transactionEffect = nil
isQueryOnlyPragma = false
isDropStatement = false
}
@@ -192,6 +199,11 @@ final class StatementAuthorizer {
}
return SQLITE_OK
case SQLITE_PRAGMA:
if let cString1 {
isQueryOnlyPragma = sqlite3_stricmp(cString1, "query_only") == 0
}
return SQLITE_OK
default:
return SQLITE_OK
}
+79 -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 type that can decode itself from the low-level C interface to
@@ -563,13 +566,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .select(Column("score"))
/// .filter(Column("lastName") == lastName)
/// .select(\.score)
/// .filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -608,13 +618,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .select(Column("score"))
/// .filter(Column("lastName") == lastName)
/// .select(\.score)
/// .filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -647,13 +664,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .select(Column("score"))
/// .filter(Column("lastName") == lastName)
/// .select(\.score)
/// .filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -681,13 +705,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .select(Column("score"))
/// .filter(Column("lastName") == lastName)
/// .select(\.score)
/// .filter { $0.lastName == lastName }
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -720,13 +751,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .filter(Column("lastName") == lastName)
/// .select(Column("score"), as: Int.self)
/// .filter { $0.lastName == lastName }
/// .select(\.score, as: Int.self)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -760,13 +798,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .filter(Column("lastName") == lastName)
/// .select(Column("score"), as: Int.self)
/// .filter { $0.lastName == lastName }
/// .select(\.score, as: Int.self)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -796,13 +841,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .filter(Column("lastName") == lastName)
/// .select(Column("score"), as: Int.self)
/// .filter { $0.lastName == lastName }
/// .select(\.score, as: Int.self)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
@@ -827,13 +879,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// static let lastName = Column("lastName")
/// }
/// }
///
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .filter(Column("lastName") == lastName)
/// .select(Column("score"), as: Int.self)
/// .filter { $0.lastName == lastName }
/// .select(\.score, as: Int.self)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
+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
@@ -650,8 +653,7 @@ extension DatabaseFunction {
/// ``SQLSpecificExpressible/capitalized``:
///
/// ```swift
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.capitalized)
/// let request = Player.select { $0.name.capitalized }
/// let names = try String.fetchAll(dbQueue, request) // [String]
/// ```
public static let capitalize =
@@ -672,8 +674,7 @@ extension DatabaseFunction {
/// ``SQLSpecificExpressible/lowercased``:
///
/// ```swift
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.lowercased)
/// let request = Player.select { $0.name.lowercased }
/// let names = try String.fetchAll(dbQueue, request) // [String]
/// ```
public static let lowercase =
@@ -694,8 +695,7 @@ extension DatabaseFunction {
/// ``SQLSpecificExpressible/uppercased``:
///
/// ```swift
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.uppercased)
/// let request = Player.select { $0.name.uppercased }
/// let names = try String.fetchAll(dbQueue, request) // [String]
/// ```
public static let uppercase =
@@ -716,8 +716,7 @@ extension DatabaseFunction {
/// ``SQLSpecificExpressible/localizedCapitalized``:
///
/// ```swift
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.localizedCapitalized)
/// let request = Player.select { $0.name.localizedCapitalized }
/// let names = try String.fetchAll(dbQueue, request) // [String]
/// ```
public static let localizedCapitalize =
@@ -739,8 +738,7 @@ extension DatabaseFunction {
/// ``SQLSpecificExpressible/localizedLowercased``:
///
/// ```swift
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.localizedLowercase)
/// let request = Player.select { $0.name.localizedLowercase }
/// let names = try String.fetchAll(dbQueue, request) // [String]
/// ```
public static let localizedLowercase =
@@ -761,8 +759,7 @@ extension DatabaseFunction {
/// ``SQLSpecificExpressible/localizedUppercased``:
///
/// ```swift
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.localizedUppercase)
/// let request = Player.select { $0.name.localizedUppercase }
/// let names = try String.fetchAll(dbQueue, request) // [String]
/// ```
public static let localizedUppercase =
+29 -17
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 {
@@ -549,8 +552,12 @@ class DatabaseObservationBroker {
savepointStack.clear()
if !database.isReadOnly {
for observation in transactionObservations {
observation.databaseDidCommit(database)
// Observers must be able to access the database, even if the
// task that has performed the commit is cancelled.
database.ignoringCancellation {
for observation in transactionObservations {
observation.databaseDidCommit(database)
}
}
}
@@ -613,8 +620,13 @@ class DatabaseObservationBroker {
if notifyTransactionObservers {
assert(!database.isReadOnly, "Read-only transactions are not notified")
for observation in transactionObservations {
observation.databaseDidRollback(database)
// Observers must be able to access the database, even if the
// task that has performed the commit is cancelled.
database.ignoringCancellation {
for observation in transactionObservations {
observation.databaseDidRollback(database)
}
}
}
databaseDidEndTransaction()
@@ -1243,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
@@ -1485,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``
@@ -252,8 +252,8 @@ Unique constraints and unique indexes are somewhat different: don't miss the tip
- ``Database/alter(table:body:)``
- ``Database/create(table:options:body:)``
- ``Database/create(virtualTable:ifNotExists:using:)``
- ``Database/create(virtualTable:ifNotExists:using:_:)``
- ``Database/create(virtualTable:options:using:)``
- ``Database/create(virtualTable:options:using:_:)``
- ``Database/drop(table:)``
- ``Database/dropFTS4SynchronizationTriggers(forTable:)``
- ``Database/dropFTS5SynchronizationTriggers(forTable:)``
@@ -265,6 +265,7 @@ Unique constraints and unique indexes are somewhat different: don't miss the tip
- ``TableDefinition``
- ``TableOptions``
- ``VirtualTableModule``
- ``VirtualTableOptions``
### Database Views
@@ -288,3 +289,5 @@ Those are legacy interfaces that are preserved for backwards compatibility. Thei
- ``Database/create(index:on:columns:unique:ifNotExists:condition:)``
- ``Database/create(table:temporary:ifNotExists:withoutRowID:body:)``
- ``Database/create(virtualTable:ifNotExists:using:)``
- ``Database/create(virtualTable:ifNotExists:using:_:)``
@@ -151,7 +151,7 @@ extension Player: FetchableRecord, MutablePersistableRecord {
// Required because the primary key
// is the hidden rowid column.
static var databaseSelection: [any SQLSelectable] {
[AllColumns(), Column.rowID]
[.allColumns, .rowID]
}
// Update id upon successful insertion
@@ -262,11 +262,11 @@ try dbQueue.write { db in
// Use instead:
let player = try Player
.filter(Column("teamId") == 42 && Column("position") == 1)
.filter { $0.teamId == 42 && $0.position == 1 }
.fetchOne(db)
try Player
.filter(Column("name") == "Arthur")
.filter { $0.name == "Arthur" }
.deleteAll(db)
}
```
@@ -96,6 +96,7 @@ do {
- ``persistentReadOnlyConnections``
- ``prepareDatabase(_:)``
- ``publicStatementArguments``
- ``schemaSource``
- ``transactionClock``
- ``TransactionClock``
@@ -106,3 +107,7 @@ do {
- ``writeQoS``
- ``targetQueue``
- ``writeTargetQueue``
### Supporting Types
- ``DatabaseSchemaSource``
@@ -59,7 +59,7 @@ You can feed `DatabaseRegionObservation` with any type that conforms to the ``Da
```swift
// Observe the score column of the 'player' table
let observation = DatabaseRegionObservation(
tracking: Player.select(Column("score")))
tracking: Player.select(\.score))
// Observe the 'score' column of the 'player' table
let observation = DatabaseRegionObservation(
@@ -107,10 +107,10 @@ import GRDB
import Tagged
// Add database support to Tagged values
extension Tagged: SQLExpressible where RawValue: SQLExpressible { }
extension Tagged: StatementBinding where RawValue: StatementBinding { }
extension Tagged: StatementColumnConvertible where RawValue: StatementColumnConvertible { }
extension Tagged: DatabaseValueConvertible where RawValue: DatabaseValueConvertible { }
extension Tagged: @retroactive SQLExpressible where RawValue: SQLExpressible { }
extension Tagged: @retroactive StatementBinding where RawValue: StatementBinding { }
extension Tagged: @retroactive StatementColumnConvertible where RawValue: StatementColumnConvertible { }
extension Tagged: @retroactive DatabaseValueConvertible where RawValue: DatabaseValueConvertible { }
```
This makes it possible to use `Tagged` values in all the expected places:
@@ -214,7 +214,7 @@ Consider a scenario where you'd like to get a specific Player's row, but only wh
let observation = ValueObservation.tracking(
// Define the tracked database region
// (the score column of the player with id 1)
region: Player.select(Column("score")).filter(id: 1),
region: Player.select(\.score).filter(id: 1),
// Define what to fetch upon such change to the tracked region
// (the player with id 1)
fetch: { db in try Player.fetchOne(db, id: 1) }
@@ -263,6 +263,10 @@ You can filter out undesired duplicate notifications with the ``removeDuplicates
When needed, you can help GRDB optimize observations and reduce database contention:
> Important: **Keep your number of observations bounded.**
>
> In particular, do not observe independently all elements in a list. Instead, observe the whole list in a single observation.
> Tip: Stop observations when possible.
>
> For example, if a `UIViewController` needs to display database values, it can start the observation in `viewWillAppear`, and stop it in `viewWillDisappear`.
+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
+14 -2
View File
@@ -36,10 +36,16 @@ try db.create(table: "player") { t in
> JSONColumn("address")["country"],
> ])
>
> struct Player: FetchableRecord, TableRecord {
> enum Columns {
> static let address = JSONColumn("address")
> }
> }
>
> // SELECT * FROM player
> // WHERE address ->> 'country' = 'DE'
> let germanPlayers = try Player
> .filter(JSONColumn("address")["country"] == "DE")
> .filter { $0.address["country"] == "DE" }
> .fetchAll(db)
> ```
@@ -104,10 +110,16 @@ extension Team: FetchableRecord, PersistableRecord {
> struct Address: Codable { ... }
> extension Address: DatabaseValueConvertible {}
>
> struct Player: FetchableRecord, TableRecord {
> enum Columns {
> static let address = JSONColumn("address")
> }
> }
>
> // SELECT * FROM player
> // WHERE address = '{"street": "...", "city": "...", "country": "..."}'
> let players = try Player
> .filter(JSONColumn("address") == Address(...))
> .filter { $0.address == Address(...) }
> .fetchAll(db)
> ```
>
+47 -7
View File
@@ -94,6 +94,26 @@ migrator.registerMigration("Create authors") { db in
}
```
#### How to Rename a Foreign Key
When a migration **renames a foreign key**, make sure the migration runs with `.immediate` foreign key checks, in order to avoid database integrity problems:
```swift
// IMPORTANT: rename foreign keys with immediate foreign key checks.
migrator.registerMigration("Guilds", foreignKeyChecks: .immediate) { db in
try db.rename(table: "team", to: "guild")
try db.alter(table: "player") { t in
// Rename a foreign key
t.rename(column: "teamId", to: "guildId")
}
}
```
Note: migrations that run with `.immediate` foreign key checks can not be used to recreated database tables, as described below. When needed, define two migrations instead of one.
#### How to Recreate a Database Table
When you need to modify a table in a way that is not directly supported by SQLite, or not available on your target operating system, you will need to recreate the database table.
For example:
@@ -113,19 +133,39 @@ migrator.registerMigration("Add NOT NULL check on author.name") { db in
The detailed sequence of operations for recreating a database table from a migration is:
1. When relevant, remember the format of all indexes, triggers, and views associated with table X. This information will be needed in steps 6 and 7 below. One way to do this is to run a query like the following: `SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'`.
1. When relevant, remember the format of all indexes, triggers, and views associated with table `X`. This information will be needed in steps 6 below. One way to do this is to run the following statement and examine the output in the console:
2. Use `CREATE TABLE` to construct a new table "new_X" that is in the desired revised format of table X. Make sure that the name "new_X" does not collide with any existing table name, of course.
```swift
try db.dumpSQL("SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'")
```
3. Transfer content from X into new_X using a statement like: `INSERT INTO new_X SELECT ... FROM X`.
2. Construct a new table `new_X` that is in the desired revised format of table `X`. Make sure that the name `new_X` does not collide with any existing table name, of course.
4. Drop the old table X: `DROP TABLE X`.
```swift
try db.create(table: "new_X") { t in ... }
```
5. Change the name of new_X to X using: `ALTER TABLE new_X RENAME TO X`.
3. Transfer content from `X` into `new_X` using a statement like:
6. When relevant, use `CREATE INDEX`, `CREATE TRIGGER`, and `CREATE VIEW` to reconstruct indexes, triggers, and views associated with table X. Perhaps use the old format of the triggers, indexes, and views saved from step 3 above as a guide, making changes as appropriate for the alteration.
```swift
try db.execute(sql: "INSERT INTO new_X SELECT ... FROM X")
```
7. If any views refer to table X in a way that is affected by the schema change, then drop those views using `DROP VIEW` and recreate them with whatever changes are necessary to accommodate the schema change using `CREATE VIEW`.
4. Drop the old table `X`:
```swift
try db.drop(table: "X")
```
5. Change the name of `new_X` to `X` using:
```swift
try db.rename(table: "new_X", to: "X")
```
6. When relevant, reconstruct indexes, triggers, and views associated with table `X`.
7. If any views refer to table `X` in a way that is affected by the schema change, then drop those views using `DROP VIEW` and recreate them with whatever changes are necessary to accommodate the schema change using `CREATE VIEW`.
> Important: When recreating a table, be sure to follow the above procedure exactly, in the given order, or you might corrupt triggers, views, and foreign key constraints.
>
@@ -214,7 +214,7 @@ extension Book.Kind: DatabaseValueConvertible { }
// Fetch all novels
let novels = try dbQueue.read { db in
try Book.filter(Column("kind") == Book.Kind.novel).fetchAll(db)
try Book.filter { $0.kind == Book.Kind.novel }.fetchAll(db)
}
```
@@ -297,7 +297,7 @@ Once we have record types that are able to read and write in the database, we'd
### Columns
Requests that filter or sort records are defined with **columns**, defined in a dedicated enumeration. When the record type conforms to [`Codable`], columns can be derived from the `CodingKeys` enum:
Requests that filter or sort records are defined with **columns**, defined in a dedicated enumeration, with the name `Columns`, nested inside the record type. When the record type conforms to [`Codable`], columns can be derived from the `CodingKeys` enum:
```swift
// HOW TO define columns for a Codable record
@@ -310,13 +310,15 @@ extension Author {
}
```
For other record types, declare a plain `String` enum that conforms to the ``ColumnExpression`` protocol:
For non-Codable record types, declare columns with their names:
```swift
// HOW TO define columns for a non-Codable record
extension Author {
enum Columns: String, ColumnExpression {
case id, name, countryCode
enum Columns {
static let id = Column("id")
static let name = Column("name")
static let countryCode = Column("countryCode")
}
}
```
@@ -328,12 +330,12 @@ try dbQueue.read { db in
// Fetch all authors, ordered by name,
// in a localized case-insensitive fashion
let sortedAuthors: [Author] = try Author.all()
.order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare))
.order { $0.name.collating(.localizedCaseInsensitiveCompare) }
.fetchAll(db)
// Count French authors
let frenchAuthorCount: Int = try Author.all()
.filter(Author.Columns.countryCode == "FR")
.filter { $0.countryCode == "FR" }
.fetchCount(db)
}
```
@@ -349,13 +351,12 @@ Define those methods in extensions of the ``DerivableRequest`` protocol, as belo
extension DerivableRequest<Author> {
/// Order authors by name, in a localized case-insensitive fashion
func orderByName() -> Self {
let name = Author.Columns.name
return order(name.collating(.localizedCaseInsensitiveCompare))
order { $0.name.collating(.localizedCaseInsensitiveCompare) }
}
/// Filters authors from a country
func filter(countryCode: String) -> Self {
filter(Author.Columns.countryCode == countryCode)
filter { $0.countryCode == countryCode }
}
}
@@ -363,13 +364,12 @@ extension DerivableRequest<Author> {
extension DerivableRequest<Book> {
/// Order books by title, in a localized case-insensitive fashion
func orderByTitle() -> Self {
let title = Book.Columns.title
return order(title.collating(.localizedCaseInsensitiveCompare))
order { $0.title.collating(.localizedCaseInsensitiveCompare) }
}
/// Filters books by kind
func filter(kind: Book.Kind) -> Self {
filter(Book.Columns.kind == kind)
filter { $0.kind == kind }
}
}
```
@@ -393,16 +393,16 @@ Extensions to the `DerivableRequest` protocol can not change the type of request
```swift
extension QueryInterfaceRequest<Author> {
// Selects author ids
func selectId() -> QueryInterfaceRequest<Int64> {
selectPrimaryKey(as: Int64.self)
// Selects authors' name
func selectName() -> QueryInterfaceRequest<String> {
select(\.name)
}
}
// The ids of Japanese authors
let ids: Set<Int64> = try Author.all()
// The names of Japanese authors
let names: Set<String> = try Author.all()
.filter(countryCode: "JP")
.selectId()
.selectName()
.fetchSet(db)
```
+1 -1
View File
@@ -332,7 +332,7 @@ The full implementation of `TimestampedRecord` follows:
```swift
/// A record type that tracks its creation and modification dates. See
/// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps>
/// <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordtimestamps>
protocol TimestampedRecord: MutablePersistableRecord {
var creationDate: Date? { get set }
var modificationDate: Date? { get set }
+14 -2
View File
@@ -91,8 +91,14 @@ extension Player: FetchableRecord, PersistableRecord {
// because non-'Sendable' type '[any SQLSelectable]'
// may have shared mutable state
static let databaseSelection: [any SQLSelectable] = [
Column("id"), Column("name"), Column("score")
Columns.id, Columns.name, Columns.score
]
enum Columns {
static let id = Column("id")
static let name = Column("name")
static let score = Column("score")
}
}
```
@@ -101,7 +107,7 @@ extension Player: FetchableRecord, PersistableRecord {
```swift
extension Player: FetchableRecord, PersistableRecord {
static var databaseSelection: [any SQLSelectable] {
[Column("id"), Column("name"), Column("score")]
[Columns.id, Columns.name, Columns.score]
}
}
```
@@ -223,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
+2 -2
View File
@@ -324,9 +324,9 @@ 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 sqlite3_libversion_number() >= 3037000 {
if Database.sqliteLibVersionNumber >= 3037000 {
guard let table = try table(tableName) else {
// Not a table
return false
+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
+5 -5
View File
@@ -1,7 +1,7 @@
/// The virtual table module for the FTS3 full-text engine.
///
/// To create FTS3 tables, use the ``Database`` method
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
/// ``Database/create(virtualTable:options:using:_:)``:
///
/// ```swift
/// // CREATE VIRTUAL TABLE document USING fts3(content)
@@ -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+
@@ -63,7 +63,7 @@ public struct FTS3 {
/// }
/// ```
///
/// See ``Database/create(virtualTable:ifNotExists:using:_:)``
/// See ``Database/create(virtualTable:options:using:_:)``
public init() { }
/// Returns an array of tokens found in the string argument.
@@ -143,7 +143,7 @@ extension FTS3: VirtualTableModule {
/// virtual table.
///
/// You don't create instances of this class. Instead, you use the `Database`
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method:
/// ``Database/create(virtualTable:options:using:_:)`` method:
///
/// ```swift
/// try db.create(virtualTable: "document", using: FTS3()) { t in // t is FTS3TableDefinition
+4 -4
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
@@ -106,13 +106,13 @@ public struct FTS3TokenizerDescriptor: Sendable {
if !separators.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as separators, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
// and Database.create(virtualTable:options:using:_:)
arguments.append("separators=" + separators.sorted().map { String($0) }.joined())
}
if !tokenCharacters.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
// and Database.create(virtualTable:options:using:_:)
arguments.append("tokenchars=" + tokenCharacters.sorted().map { String($0) }.joined())
}
return FTS3TokenizerDescriptor("unicode61", arguments: arguments)
+13 -3
View File
@@ -1,7 +1,7 @@
/// The virtual table module for the FTS4 full-text engine.
///
/// To create FTS4 tables, use the ``Database`` method
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
/// ``Database/create(virtualTable:options:using:_:)``:
///
/// ```swift
/// // CREATE VIRTUAL TABLE document USING fts4(content)
@@ -31,7 +31,7 @@ public struct FTS4 {
/// }
/// ```
///
/// See ``Database/create(virtualTable:ifNotExists:using:_:)``
/// See ``Database/create(virtualTable:options:using:_:)``
public init() { }
}
@@ -102,6 +102,16 @@ extension FTS4: VirtualTableModule {
case .synchronized(let contentTable):
// https://www.sqlite.org/fts3.html#_external_content_fts4_tables_
if definition.configuration.temporary {
// SQLite can't rebuild the index of temporary tables:
//
// sqlite> CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
// sqlite> CREATE VIRTUAL TABLE temp.ft USING fts4(content="t", b, c);
// sqlite> INSERT INTO ft(ft) VALUES('rebuild');
// Runtime error: SQL logic error
fatalError("Temporary external content FTS4 tables are not supported.")
}
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
let ftsTable = tableName.quotedDatabaseIdentifier
let content = contentTable.quotedDatabaseIdentifier
@@ -149,7 +159,7 @@ extension FTS4: VirtualTableModule {
/// virtual table.
///
/// You don't create instances of this class. Instead, you use the `Database`
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method:
/// ``Database/create(virtualTable:options:using:_:)`` method:
///
/// ```swift
/// try db.create(virtualTable: "document", using: FTS4()) { t in // t is FTS4TableDefinition
+26 -13
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
@@ -13,7 +16,7 @@ import Foundation
/// The virtual table module for the FTS5 full-text engine.
///
/// To create FTS5 tables, use the ``Database`` method
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
/// ``Database/create(virtualTable:options:using:_:)``:
///
/// ```swift
/// // CREATE VIRTUAL TABLE document USING fts5(content)
@@ -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
@@ -85,7 +88,7 @@ public struct FTS5 {
/// }
/// ```
///
/// See ``Database/create(virtualTable:ifNotExists:using:_:)``
/// See ``Database/create(virtualTable:options:using:_:)``
public init() { }
// Support for FTS5Pattern initializers. Don't make public. Users tokenize
@@ -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)
@@ -143,7 +146,7 @@ extension FTS5: VirtualTableModule {
/// Reserved; part of the VirtualTableModule protocol.
///
/// See Database.create(virtualTable:using:)
/// See Database.create(virtualTable:options:using:_:)
public func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS5TableDefinition {
FTS5TableDefinition(configuration: configuration)
}
@@ -219,7 +222,7 @@ extension FTS5: VirtualTableModule {
/// Reserved; part of the VirtualTableModule protocol.
///
/// See Database.create(virtualTable:using:)
/// See Database.create(virtualTable:options:using:_:)
public func database(_ db: Database, didCreate tableName: String, using definition: FTS5TableDefinition) throws {
switch definition.contentMode {
case .raw:
@@ -227,6 +230,16 @@ extension FTS5: VirtualTableModule {
case .synchronized(let contentTable):
// https://sqlite.org/fts5.html#external_content_tables
if definition.configuration.temporary {
// SQLite can't rebuild the index of temporary tables:
//
// sqlite> CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
// sqlite> CREATE VIRTUAL TABLE temp.ft USING fts5(content="t",content_rowid="a",b,c);
// sqlite> INSERT INTO ft(ft) VALUES('rebuild');
// Runtime error: SQL logic error
fatalError("Temporary external content FTS5 tables are not supported.")
}
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
let ftsTable = tableName.quotedDatabaseIdentifier
let content = contentTable.quotedDatabaseIdentifier
@@ -274,7 +287,7 @@ extension FTS5: VirtualTableModule {
/// virtual table.
///
/// You don't create instances of this class. Instead, you use the `Database`
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method:
/// ``Database/create(virtualTable:options:using:_:)`` method:
///
/// ```swift
/// try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition
+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.
Loaded 100 of 265 files, more files were not shown because too many files have changed in this diff. Show more