Compare commits

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

To reproduce the failure:

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

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

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

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

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

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

> https://sqlite.org/c3ref/changes.html
> Changes to a view that are intercepted by INSTEAD OF triggers are not counted.

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

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

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

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

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

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

Signed-off-by: dependabot[bot] <support@github.com>
2025-08-18 09:08:53 +00:00
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
311 changed files with 18964 additions and 5745 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
+248 -142
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
@@ -1625,7 +1731,7 @@ The [Advanced DatabasePool](README.md#advanced-databasepool) chapter has been ex
```diff
class DatabasePool {
+ func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
+ func barrierWriteWithoutTransaction<T>(_ updates: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T
+ func invalidateReadOnlyConnections()
}
@@ -1745,7 +1851,7 @@ The [ValueObservation](README.md#valueobservation) chapter has been updated so t
}
extension ValueObservation where Reducer == Void {
+ static func tracking<Value>(fetch: @escaping (Database) throws -> Value) -> ValueObservation<ValueReducers.Fetch<Value>>
+ static func tracking<Value>(fetch: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Value) -> ValueObservation<ValueReducers.Fetch<Value>>
}
```
@@ -1790,7 +1896,7 @@ The [ValueObservation Error Handling](README.md#valueobservation-error-handling)
+ var configuration: Configuration { get }
+
+ #if compiler(>=5.0)
+ func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void)
+ func asyncRead(_ block: @escaping (Result<DatabaseBase<some SQLiteAPI>, Error>) -> Void)
+ #endif
}
@@ -1798,7 +1904,7 @@ The [ValueObservation Error Handling](README.md#valueobservation-error-handling)
+ func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
+
+ #if compiler(>=5.0)
+ func asyncWrite<T>(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result<T, Error>) -> Void)
+ func asyncWrite<T>(_ updates: @escaping (DatabaseBase<some SQLiteAPI>) throws -> T, completion: @escaping (Database, Result<T, Error>) -> Void)
+ #endif
}
```
@@ -1878,8 +1984,8 @@ The [ValueObservation Error Handling](README.md#valueobservation-error-handling)
protocol FetchRequest {
+ // deprecated
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
+ func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
func prepare(_ db: DatabaseBase<some SQLiteAPI>, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
+ func makePreparedRequest(_ db: DatabaseBase<some SQLiteAPI>, forSingleResult singleResult: Bool) throws -> PreparedRequest
}
```
@@ -2083,37 +2189,37 @@ It comes with new features, but also a few breaking changes. The [GRDB 4 Migrati
}
class Row {
- static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor
- static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row]
- static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row?
+ static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RowCursor
+ static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Row]
+ static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Row?
- static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor
- static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row]
- static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row?
+ static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RowCursor
+ static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Row]
+ static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Row?
}
extension FetchableRecord {
- static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self>
- static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
- static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
+ static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RecordCursor<Self>
+ static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self]
+ static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self?
- static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self>
- static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
- static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
+ static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RecordCursor<Self>
+ static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self]
+ static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self?
}
extension DatabaseValueConvertible {
- static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self>
- static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
- static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
+ static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self>
+ static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self]
+ static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self?
- static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self>
- static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
- static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
+ static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self>
+ static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self]
+ static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self?
}
extension Optional where Wrapped: DatabaseValueConvertible {
- static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped>
- static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?]
+ static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped>
+ static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?]
- static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped>
- static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?]
+ static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped>
+ static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?]
}
extension TableRecord {
@@ -2218,7 +2324,7 @@ It comes with new features, but also a few breaking changes. The [GRDB 4 Migrati
struct ValueObservation<Reducer> {
- var extent: Database.TransactionObservationExtent
- static func tracking(_ regions: DatabaseRegionConvertible..., reducer: Reducer) -> ValueObservation
- static func tracking<Value>(_ regions: DatabaseRegionConvertible..., fetchDistinct fetch: @escaping (Database) throws -> Value) -> ValueObservation<DistinctUntilChangedValueReducer<RawValueReducer<Value>>> where Value: Equatable
- static func tracking<Value>(_ regions: DatabaseRegionConvertible..., fetchDistinct fetch: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Value) -> ValueObservation<DistinctUntilChangedValueReducer<RawValueReducer<Value>>> where Value: Equatable
}
```
@@ -2361,12 +2467,12 @@ It comes with new features, but also a few breaking changes. The [GRDB 4 Migrati
+ class DatabaseFuture<Value> { }
protocol FetchRequest {
- func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
+ func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
- func prepare(_ db: DatabaseBase<some SQLiteAPI>) throws -> (SelectStatement, RowAdapter?)
+ func prepare(_ db: DatabaseBase<some SQLiteAPI>, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
}
struct AnyFetchRequest<T> : FetchRequest {
- init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?))
- init(_ prepare: @escaping (DatabaseBase<some SQLiteAPI>) throws -> (SelectStatement, RowAdapter?))
+ init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?))
}
@@ -2489,24 +2595,24 @@ This release comes with:
}
extension MutablePersistableRecord {
+ mutating func updateChanges(_ db: Database, with change: (inout Self) throws -> Void) throws -> Bool
+ mutating func updateChanges(_ db: DatabaseBase<some SQLiteAPI>, with change: (inout Self) throws -> Void) throws -> Bool
}
extension PersistableRecord {
+ func updateChanges(_ db: Database, with change: (Self) throws -> Void) throws -> Bool
+ func updateChanges(_ db: DatabaseBase<some SQLiteAPI>, with change: (Self) throws -> Void) throws -> Bool
}
struct ValueObservation<Reducer> {
+ static func tracking(
+ _ regions: [DatabaseRegionConvertible],
+ reducer: @escaping (Database) throws -> Reducer)
+ reducer: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Reducer)
+ -> ValueObservation
}
+extension ValueObservation where Reducer == Void {
+ static func tracking<Value>(
+ _ regions: [DatabaseRegionConvertible],
+ fetch: @escaping (Database) throws -> Value)
+ fetch: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Value)
+ -> ValueObservation<ValueReducers.Raw<Value>>
+ static func combine<R1: ValueReducer, ...>(_ o1: ValueObservation<R1>, ...)
+ -> ValueObservation<...>
@@ -2591,13 +2697,13 @@ It used to be possible to define custom types that adopt the [DatabaseReader and
}
+protocol DatabaseRegionConvertible {
+ func databaseRegion(_ db: Database) throws -> DatabaseRegion
+ func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
+}
+
+extension DatabaseRegion: DatabaseRegionConvertible { }
+
+struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
+ init(_ region: @escaping (Database) throws -> DatabaseRegion)
+ init(_ region: @escaping (DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion)
+ init(_ region: DatabaseRegionConvertible)
+}
@@ -2613,7 +2719,7 @@ It used to be possible to define custom types that adopt the [DatabaseReader and
+protocol ValueReducer {
+ associatedtype Fetched
+ associatedtype Value
+ func fetch(_ db: Database) throws -> Fetched
+ func fetch(_ db: DatabaseBase<some SQLiteAPI>) throws -> Fetched
+ mutating func value(_ fetched: Fetched) -> Value?
+}
+
@@ -2622,7 +2728,7 @@ It used to be possible to define custom types that adopt the [DatabaseReader and
+}
+
+struct AnyValueReducer<Fetched, Value>: ValueReducer {
+ init(fetch: @escaping (Database) throws -> Fetched, value: @escaping (Fetched) -> Value?)
+ init(fetch: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Fetched, value: @escaping (Fetched) -> Value?)
+ init<Reducer: ValueReducer>(_ reducer: Reducer) where Reducer.Fetched == Fetched, Reducer.Value == Value
+}
@@ -2645,12 +2751,12 @@ It used to be possible to define custom types that adopt the [DatabaseReader and
+extension ValueObservation where Reducer == Void {
+ static func tracking<Value>(
+ _ regions: DatabaseRegionConvertible...,
+ fetch: @escaping (Database) throws -> Value)
+ fetch: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Value)
+ -> ValueObservation<ValueReducers.Raw<Value>>
+
+ static func tracking<Value>(
+ _ regions: DatabaseRegionConvertible...,
+ fetchDistinct: @escaping (Database) throws -> Value)
+ fetchDistinct: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Value)
+ -> ValueObservation<ValueReducers.Distinct<Value>>
+ where Value: Equatable
+
@@ -2695,7 +2801,7 @@ This release comes with **Association Aggregates**. They let you compute values
```diff
protocol AggregatingRequest {
- func group(_ expressions: [SQLExpressible]) -> Self
+ func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self
+ func group(_ expressions: @escaping (DatabaseBase<some SQLiteAPI>) throws -> [SQLExpressible]) -> Self
}
+extension AggregatingRequest {
@@ -2773,7 +2879,7 @@ Released September 16, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/co
```diff
protocol DatabaseWriter : DatabaseReader {
+ func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> Future<T>
+ func concurrentRead<T>(_ block: @escaping (DatabaseBase<some SQLiteAPI>) throws -> T) -> Future<T>
+ @available(*, deprecated)
func readFromCurrentState(_ block: @escaping (Database) -> Void) throws
}
@@ -2832,10 +2938,10 @@ Fixes:
```diff
class DatabaseQueue {
- func write<T>(_ block: (Database) throws -> T) rethrows -> T {
+ func write<T>(_ block: (Database) throws -> T) throws -> T {
- func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
+ func unsafeReentrantRead<T>(_ block: (Database) throws -> T) rethrows -> T {
- func write<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T {
+ func write<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T {
- func unsafeReentrantRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T {
+ func unsafeReentrantRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T {
}
```
@@ -3083,14 +3189,14 @@ Released February 25, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/com
extension MutablePersistable {
+ @discardableResult
+ func updateChanges(_ db: Database, from record: MutablePersistable) throws -> Bool
+ func updateChanges(_ db: DatabaseBase<some SQLiteAPI>, from record: MutablePersistable) throws -> Bool
+ func databaseEqual(_ record: Self) -> Bool
+ func databaseChanges(from record: MutablePersistable) -> [String: DatabaseValue]
}
class Record {
- final func updateChanges(_ db: Database) throws
- final func updateChanges(_ db: DatabaseBase<some SQLiteAPI>) throws
+ @discardableResult
+ final func updateChanges(_ db: Database) throws -> Bool
+ final func updateChanges(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
}
+@available(*, deprecated, message: "Prefer changes methods defined on the MutablePersistable protocol: databaseEqual(_:), databaseChanges(from:), updateChanges(from:)")
@@ -3106,7 +3212,7 @@ Released February 25, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/com
extension TableMapping {
+ static func selectionSQL(alias: String? = nil) -> String
+ static func numberOfSelectedColumns(_ db: Database) throws -> Int
+ static func numberOfSelectedColumns(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int
}
+struct EmptyRowAdapter: RowAdapter { }
@@ -3229,7 +3335,7 @@ Released January 18, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/comp
protocol Request {
+ // Default implementation
+ func fetchedRegion(_ db: Database) throws -> DatabaseRegion
+ func fetchedRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
}
+extension Row: RandomAccessCollection {
@@ -3296,8 +3402,8 @@ Released January 11, 2018 &bull; [diff](https://github.com/groue/GRDB.swift/comp
}
extension RowConvertible where Self: TableMapping {
- static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Self?
+ static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]?) throws -> Self?
- static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, key: [String: DatabaseValueConvertible?]) throws -> Self?
+ static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, key: [String: DatabaseValueConvertible?]?) throws -> Self?
}
```
@@ -3427,7 +3533,7 @@ Released October 24, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/comp
```diff
extension Request {
+ func asSQLRequest(_ db: Database, cached: Bool = false) throws -> SQLRequest
+ func asSQLRequest(_ db: DatabaseBase<some SQLiteAPI>, cached: Bool = false) throws -> SQLRequest
}
struct SQLRequest {
+ let sql: String
@@ -3678,15 +3784,15 @@ New features have been added in order to plug a few holes and support the [RxGRD
-extension TableMapping {
+extension MutablePersistable {
@discardableResult static func deleteAll(_ db: Database) throws -> Int
@discardableResult static func deleteAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> Int where Sequence.Element: DatabaseValueConvertible
@discardableResult static func deleteOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: Database, key: PrimaryKeyType?) throws -> Bool
@discardableResult static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int
@discardableResult static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool
@discardableResult static func deleteAll(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int
@discardableResult static func deleteAll<Sequence: Swift.Sequence>(_ db: DatabaseBase<some SQLiteAPI>, keys: Sequence) throws -> Int where Sequence.Element: DatabaseValueConvertible
@discardableResult static func deleteOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: DatabaseBase<some SQLiteAPI>, key: PrimaryKeyType?) throws -> Bool
@discardableResult static func deleteAll(_ db: DatabaseBase<some SQLiteAPI>, keys: [[String: DatabaseValueConvertible?]]) throws -> Int
@discardableResult static func deleteOne(_ db: DatabaseBase<some SQLiteAPI>, key: [String: DatabaseValueConvertible?]) throws -> Bool
}
-extension QueryInterfaceRequest {
+extension QueryInterfaceRequest where RowDecoder: MutablePersistable {
@discardableResult func deleteAll(_ db: Database) throws -> Int
@discardableResult func deleteAll(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int
}
protocol TableMapping {
@@ -3756,30 +3862,30 @@ New features have been added in order to plug a few holes and support the [RxGRD
+ static func fetchCursor(...) throws -> RecordCursor<Self>
}
extension TypedRequest where RowDecoder: RowConvertible {
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder>
+ func fetchCursor(_ db: Database) throws -> RecordCursor<RowDecoder>
- func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseCursor<RowDecoder>
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> RecordCursor<RowDecoder>
}
extension TypedRequest where RowDecoder: DatabaseValueConvertible {
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder>
+ func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder>
- func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseCursor<RowDecoder>
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseValueCursor<RowDecoder>
}
extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible {
+ func fetchCursor(_ db: Database) throws -> ColumnCursor<RowDecoder>
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> ColumnCursor<RowDecoder>
}
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible {
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder._Wrapped?>
+ func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped>
- func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseCursor<RowDecoder._Wrapped?>
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped>
}
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
+ func fetchCursor(_ db: Database) throws -> NullableColumnCursor<RowDecoder._Wrapped>
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> NullableColumnCursor<RowDecoder._Wrapped>
}
extension TypedRequest where RowDecoder: Row {
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<Row>
+ func fetchCursor(_ db: Database) throws -> RowCursor
- func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseCursor<Row>
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> RowCursor
}
extension TableMapping {
- @available(*, deprecated) static func primaryKeyRowComparator(_ db: Database) throws -> (Row, Row) -> Bool
- @available(*, deprecated) static func primaryKeyRowComparator(_ db: DatabaseBase<some SQLiteAPI>) throws -> (Row, Row) -> Bool
}
+final class AnyDatabaseReader : DatabaseReader {
@@ -3942,7 +4048,7 @@ Released July 13, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/compare
}
protocol DatabaseReader {
+ func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T
+ func unsafeReentrantRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T
}
```
@@ -4004,7 +4110,7 @@ Released July 1, 2017 &bull; [diff](https://github.com/groue/GRDB.swift/compare/
extension TableMapping {
+ @available(*, deprecated)
static func primaryKeyRowComparator(_ db: Database) throws -> (Row, Row) -> Bool
static func primaryKeyRowComparator(_ db: DatabaseBase<some SQLiteAPI>) throws -> (Row, Row) -> Bool
}
```
@@ -4129,8 +4235,8 @@ It comes with breaking changes, but the good news is that they are the last (unt
}
extension Request {
- func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AnyRequest
+ func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedRequest<Self>
- func adapted(_ adapter: @escaping (DatabaseBase<some SQLiteAPI>) throws -> RowAdapter) -> AnyRequest
+ func adapted(_ adapter: @escaping (DatabaseBase<some SQLiteAPI>) throws -> RowAdapter) -> AdaptedRequest<Self>
}
protocol TypedRequest : Request {
@@ -4139,8 +4245,8 @@ protocol TypedRequest : Request {
}
extension TypedRequest {
- func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AnyTypedRequest<Fetched>
+ func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedTypedRequest<Self>
- func adapted(_ adapter: @escaping (DatabaseBase<some SQLiteAPI>) throws -> RowAdapter) -> AnyTypedRequest<Fetched>
+ func adapted(_ adapter: @escaping (DatabaseBase<some SQLiteAPI>) throws -> RowAdapter) -> AdaptedTypedRequest<Self>
}
```
@@ -4260,7 +4366,7 @@ Released April 3, 2017
- Support for [reactive](https://reactivex.io) extensions:
- `SelectStatement.SelectionInfo` is an opaque value that knows which database tables and columns are read by a [select statement](https://github.com/groue/GRDB.swift#prepared-statements).
- `DatabaseEventKind.impacts(_ selectionInfo:SelectStatement.SelectionInfo)` tells whether a database change has any impact on the results of a select statement. See [Database Changes Observation](https://github.com/groue/GRDB.swift#database-changes-observation)
- `TableMapping.primaryKeyRowComparator(_ db: Database)` returns a function that compares two database rows and return true if and only if they have the same non-null primary key.
- `TableMapping.primaryKeyRowComparator(_ db: DatabaseBase<some SQLiteAPI>)` returns a function that compares two database rows and return true if and only if they have the same non-null primary key.
**Breaking Changes**
@@ -4578,19 +4684,19 @@ Many APIs were changed:
}
final class DatabasePool {
- func read<T>(_ block: (Database) throws -> T) rethrows -> T
- func nonIsolatedRead<T>(_ block: (Database) throws -> T) rethrows -> T
- func read<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T
- func nonIsolatedRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T
- func readFromWrite(_ block: @escaping (Database) -> Void)
+ func read<T>(_ block: (Database) throws -> T) throws -> T
+ func nonIsolatedRead<T>(_ block: (Database) throws -> T) throws -> T
+ func read<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T
+ func nonIsolatedRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T
+ func readFromWrite(_ block: @escaping (Database) -> Void) throws
}
protocol DatabaseReader {
- func read<T>(_ block: (Database) throws -> T) rethrows -> T
- func nonIsolatedRead<T>(_ block: (Database) throws -> T) rethrows -> T
+ func read<T>(_ block: (Database) throws -> T) throws -> T
+ func nonIsolatedRead<T>(_ block: (Database) throws -> T) throws -> T
- func read<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T
- func nonIsolatedRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T
+ func read<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T
+ func nonIsolatedRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T
}
protocol DatabaseWriter {
@@ -4641,13 +4747,13 @@ Many APIs were changed:
}
protocol MutablePersistable : TableMapping {
- func exists(_ db: Database) -> Bool
+ func exists(_ db: Database) throws -> Bool
- func exists(_ db: DatabaseBase<some SQLiteAPI>) -> Bool
+ func exists(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
}
extension MutablePersistable {
- func performExists(_ db: Database) -> Bool
+ func performExists(_ db: Database) throws -> Bool
- func performExists(_ db: DatabaseBase<some SQLiteAPI>) -> Bool
+ func performExists(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
}
extension QueryInterfaceRequest {
@@ -4674,8 +4780,8 @@ Many APIs were changed:
}
extension TableMapping {
- static func fetchCount(_ db: Database) -> Int
+ static func fetchCount(_ db: Database) throws -> Int
- static func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) -> Int
+ static func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int
}
```
@@ -4853,7 +4959,7 @@ Released October 16, 2016
protocol VirtualTableModule {
- func moduleArguments(_ definition: TableDefinition) -> [String]
+ func moduleArguments(for definition: TableDefinition, in db: Database) throws -> [String]
+ func database(_ db: Database, didCreate tableName: String, using definition: TableDefinition) throws
+ func database(_ db: DatabaseBase<some SQLiteAPI>, didCreate tableName: String, using definition: TableDefinition) throws
}
```
@@ -4926,7 +5032,7 @@ Released September 28, 2016
**Breaking Changes**
- The SQLForeignKeyAction, SQLColumnType, SQLConflictResolution, and SQLCollation types have been renamed Database.ForeignKeyAction, Database.ColumnType, Database.ConflictResolution, and Database.CollationName.
- The SQLForeignKeyAction, SQLColumnType, SQLConflictResolution, and SQLCollation types have been renamed Database.ForeignKeyAction, Database.ColumnType, DatabaseConflictResolution, and Database.CollationName.
## 0.84.0
@@ -5189,8 +5295,8 @@ Released September 11, 2016
- func databaseDidRollback(db: Database)
+ func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
+ func databaseDidChange(with event: DatabaseEvent)
+ func databaseDidCommit(_ db: Database)
+ func databaseDidRollback(_ db: Database)
+ func databaseDidCommit(_ db: DatabaseBase<some SQLiteAPI>)
+ func databaseDidRollback(_ db: DatabaseBase<some SQLiteAPI>)
#if SQLITE_ENABLE_PREUPDATE_HOOK
- func databaseWillChangeWithEvent(event: DatabasePreUpdateEvent)
+ func databaseWillChange(with event: DatabasePreUpdateEvent)
@@ -5213,19 +5319,19 @@ Released September 11, 2016
- func delete(db: Database) throws -> Bool
- func exists(db: Database) -> Bool
+ mutating func didInsert(with rowID: Int64, for column: String?)
+ mutating func insert(_ db: Database) throws
+ func update(_ db: Database, columns: Set<String>) throws
+ mutating func save(_ db: Database) throws
+ @discardableResult func delete(_ db: Database) throws -> Bool
+ func exists(_ db: Database) -> Bool
+ mutating func insert(_ db: DatabaseBase<some SQLiteAPI>) throws
+ func update(_ db: DatabaseBase<some SQLiteAPI>, columns: Set<String>) throws
+ mutating func save(_ db: DatabaseBase<some SQLiteAPI>) throws
+ @discardableResult func delete(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
+ func exists(_ db: DatabaseBase<some SQLiteAPI>) -> Bool
}
protocol Persistable : MutablePersistable {
- func didInsertWithRowID(rowID: Int64, forColumn column: String?)
- func insert(db: Database) throws
- func save(db: Database) throws
+ func didInsert(with rowID: Int64, for column: String?)
+ func insert(_ db: Database) throws
+ func save(_ db: Database) throws
+ func insert(_ db: DatabaseBase<some SQLiteAPI>) throws
+ func save(_ db: DatabaseBase<some SQLiteAPI>) throws
}
protocol TableMapping {
- static func databaseTableName() -> String
@@ -5245,10 +5351,10 @@ Released September 11, 2016
+ class var databaseTableName: String
+ func awakeFromFetch(row: Row)
+ func didInsert(with rowID: Int64, for column: String?)
+ func update(_ db: Database, columns: Set<String>) throws
+ func insert(_ db: Database) throws
+ func save(_ db: Database) throws
+ @discardableResult func delete(_ db: Database) throws -> Bool
+ func update(_ db: DatabaseBase<some SQLiteAPI>, columns: Set<String>) throws
+ func insert(_ db: DatabaseBase<some SQLiteAPI>) throws
+ func save(_ db: DatabaseBase<some SQLiteAPI>) throws
+ @discardableResult func delete(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
}
```
@@ -5257,7 +5363,7 @@ Released September 11, 2016
```diff
protocol FetchRequest {
- func prepare(db: Database) throws -> (SelectStatement, RowAdapter?)
+ func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
+ func prepare(_ db: DatabaseBase<some SQLiteAPI>) throws -> (SelectStatement, RowAdapter?)
}
-struct SQLColumn {}
+struct Column {}
@@ -5837,10 +5943,10 @@ Released May 17, 2016
```diff
struct DatabaseMigrator {
- mutating func registerMigration(identifier: String, withDisabledForeignKeyChecks disabledForeignKeyChecks: Bool = false, migrate: (Database) throws -> Void)
+ mutating func registerMigration(identifier: String, migrate: (Database) throws -> Void)
- mutating func registerMigration(identifier: String, withDisabledForeignKeyChecks disabledForeignKeyChecks: Bool = false, migrate: (DatabaseBase<some SQLiteAPI>) throws -> Void)
+ mutating func registerMigration(identifier: String, migrate: (DatabaseBase<some SQLiteAPI>) throws -> Void)
+ @available(iOS 8.2, OSX 10.10, *)
+ mutating func registerMigrationWithDisabledForeignKeyChecks(identifier: String, migrate: (Database) throws -> Void)
+ mutating func registerMigrationWithDisabledForeignKeyChecks(identifier: String, migrate: (DatabaseBase<some SQLiteAPI>) throws -> Void)
```
+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)
@@ -165,7 +165,7 @@ extension AppDatabase {
}
/// Support for `createRandomPlayersIfEmpty()` and `refreshPlayers()`.
private func createRandomPlayers(_ db: Database) throws {
private func createRandomPlayers(_ db: DatabaseBase<some SQLiteAPI>) throws {
for _ in 0..<8 {
_ = try Player.makeRandom().inserted(db) // insert but ignore inserted id
}
@@ -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
+10 -10
View File
@@ -178,12 +178,12 @@ The record protocols have been refactored. We tried to keep the amount of modifi
```swift
// GRDB 6: remove those methods from your code
func insert(_ db: Database) throws
func insert(_ db: DatabaseBase<some SQLiteAPI>) throws
func didInsert(with rowID: Int64, for column: String?)
func update(_ db: Database, columns: Set<String>) throws
func save(_ db: Database) throws
func delete(_ db: Database) throws -> Bool
func exists(_ db: Database) throws -> Bool
func update(_ db: DatabaseBase<some SQLiteAPI>, columns: Set<String>) throws
func save(_ db: DatabaseBase<some SQLiteAPI>) throws
func delete(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
func exists(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
```
- `insert(_:)`: customization is now made with [persistence callbacks].
@@ -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:
@@ -204,12 +204,12 @@ The record protocols have been refactored. We tried to keep the amount of modifi
struct Link: PersistableRecord {
var url: URL
func insert(_ db: Database) throws {
func insert(_ db: DatabaseBase<some SQLiteAPI>) throws {
try validate()
try performInsert(db)
}
func update(_ db: Database, columns: Set<String>) throws {
func update(_ db: DatabaseBase<some SQLiteAPI>, columns: Set<String>) throws {
try validate()
try performUpdate(db, columns: columns)
}
@@ -229,7 +229,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi
struct Link: PersistableRecord {
var url: URL
func willSave(_ db: Database) throws {
func willSave(_ db: DatabaseBase<some SQLiteAPI>) throws {
if url.host == nil {
throw ValidationError("url must be absolute.")
}
@@ -249,7 +249,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi
class Link: Record {
var url: URL
override func willSave(_ db: Database) throws {
override func willSave(_ db: DatabaseBase<some SQLiteAPI>) throws {
try super.willSave(db)
if url.host == nil {
throw ValidationError("url must be absolute.")
+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)
}
@@ -40,12 +40,12 @@ class TableChangeObserver : NSObject, TransactionObserver {
changedTableNames.insert(event.tableName)
}
func databaseDidCommit(_ db: Database) {
func databaseDidCommit(_ db: DatabaseBase<some SQLiteAPI>) {
print("Changed table(s): \(changedTableNames.joined(separator: ", "))")
changedTableNames = []
}
func databaseDidRollback(_ db: Database) {
func databaseDidRollback(_ db: DatabaseBase<some SQLiteAPI>) {
changedTableNames = []
}
}
+17 -16
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
@@ -123,7 +123,7 @@ Columns are special expressions that allow some optimizations and niceties:
```swift
protocol DatabaseRegionConvertible {
func databaseRegion(_ db: Database) throws -> DatabaseRegion
func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
}
```
@@ -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
@@ -207,10 +207,10 @@ protocol FetchRequest<RowDecoder>: SQLSubqueryable, DatabaseRegionConvertible {
associatedtype RowDecoder
/// Returns a PreparedRequest that is ready to be executed.
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
func makePreparedRequest(_ db: DatabaseBase<some SQLiteAPI>, forSingleResult singleResult: Bool) throws -> PreparedRequest
/// Returns the number of rows fetched by the request.
func fetchCount(_ db: Database) throws -> Int
func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int
}
```
@@ -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
+3 -3
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" }
```
@@ -204,7 +204,7 @@ Let's extend Player with database methods.
```swift
extension Player {
/// Deletes all player with no score
static func deleteAllWithoutScore(_ db: Database) throws {
static func deleteAllWithoutScore(_ db: DatabaseBase<some SQLiteAPI>) throws {
try db.execute(literal: "DELETE FROM \(self) WHERE \(CodingKeys.score) IS NULL")
}
}
@@ -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"
+36 -17
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
#if !canImport(Darwin)
@preconcurrency
@@ -87,7 +90,7 @@ public struct Configuration: Sendable {
/// with the number of snapshots.
///
/// The default configuration label is nil.
public var label: String? = nil
public var label: String?
/// A boolean value indicating whether SQLite 3.29+ interprets
/// double-quoted strings as string literals when they does not match any
@@ -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)
@@ -198,7 +201,7 @@ public struct Configuration: Sendable {
// MARK: - Managing SQLite Connections
private var setups: [@Sendable (Database) throws -> Void] = []
private var setups: [@Sendable (DatabaseBase<some SQLiteAPI>) throws -> Void] = []
/// Defines a function to run whenever an SQLite connection is opened.
///
@@ -235,7 +238,7 @@ public struct Configuration: Sendable {
///
/// On newly created databases files, ``DatabasePool`` activates the WAL
/// mode after the preparation functions have run.
public mutating func prepareDatabase(_ setup: @escaping @Sendable (Database) throws -> Void) {
public mutating func prepareDatabase(_ setup: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> Void) {
setups.append(setup)
}
@@ -329,7 +332,7 @@ public struct Configuration: Sendable {
/// The behavior in case of SQLITE_BUSY error, for read-only connections.
/// If nil, GRDB picks a default one.
var readonlyBusyMode: Database.BusyMode? = nil
var readonlyBusyMode: Database.BusyMode?
/// The maximum number of concurrent reader connections.
///
@@ -387,7 +390,7 @@ public struct Configuration: Sendable {
/// ``qos`` property.
///
/// The default is nil.
public var targetQueue: DispatchQueue? = nil
public var targetQueue: DispatchQueue?
/// The target dispatch queue for write database accesses.
///
@@ -395,7 +398,7 @@ public struct Configuration: Sendable {
/// by ``targetQueue``.
///
/// The default is nil.
public var writeTargetQueue: DispatchQueue? = nil
public var writeTargetQueue: DispatchQueue?
#if os(iOS)
/// A boolean value indicating whether the database connection releases
@@ -421,6 +424,22 @@ public struct Configuration: Sendable {
/// reveals that a lot of time is spent opening new SQLite connections.
public var persistentReadOnlyConnections = false
// MARK: - Database Schema
/// A custom schema source.
///
/// The use case for a custom schema source is enabling GRDB features that
/// would not work with the built-in schema introspection that is provided
/// by SQLite. For example, a custom schema source can help record types
/// that read or write in a database view.
///
/// The schema source is automatically disabled during database
/// migrations performed by ``DatabaseMigrator``: those access the raw
/// SQLite schema, unaltered. If a migration needs a schema source,
/// you may call ``Database/withSchemaSource(_:execute:)`` from within
/// the body of a migration.
public var schemaSource: (any DatabaseSchemaSource)?
// MARK: - Factory Configuration
/// Creates a factory configuration.
@@ -462,7 +481,7 @@ public struct Configuration: Sendable {
return threadingMode.SQLiteOpenFlags | flags
}
func setUp(_ db: Database) throws {
func setUp(_ db: DatabaseBase<some SQLiteAPI>) throws {
for f in setups {
try f(db)
}
File diff suppressed because it is too large. Load diff
+27 -26
View File
@@ -1,15 +1,18 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
extension Database {
extension DatabaseBase {
// MARK: - Statements
@@ -387,7 +390,7 @@ extension SQLStatementCursor: Cursor {
let baseAddress = buffer.baseAddress! // never nil because the buffer contains the trailing \0.
// Compile next statement
var statementEnd: UnsafePointer<CChar>? = nil
var statementEnd: UnsafePointer<CChar>?
let statement = try Statement(
database: database,
statementStart: baseAddress + offset,
@@ -431,10 +434,10 @@ extension SQLStatementCursor: Cursor {
}
}
extension Database {
extension DatabaseBase {
/// Makes sure statement can be executed, and prepares database observation.
@usableFromInline
func statementWillExecute(_ statement: Statement) throws {
func statementWillExecute(_ statement: StatementBase<API>) throws {
// Aborted transactions prevent statement execution (see the
// documentation of this method for more information).
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
@@ -455,7 +458,7 @@ extension Database {
/// May throw a cancelled commit error, if a transaction observer cancels
/// an empty transaction.
@usableFromInline
func statementDidExecute(_ statement: Statement) throws {
func statementDidExecute(_ statement: StatementBase<API>) throws {
if statement.invalidatesDatabaseSchemaCache {
clearSchemaCache()
}
@@ -468,7 +471,7 @@ extension Database {
/// Always throws an error
@usableFromInline
func statementDidFail(_ statement: Statement, withResultCode resultCode: CInt) throws -> Never {
func statementDidFail(_ statement: StatementBase<API>, withResultCode resultCode: CInt) throws -> Never {
// Failed statements can not be reused, because `sqlite3_reset` won't
// be able to restore the statement to its initial state:
// https://www.sqlite.org/c3ref/reset.html
@@ -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
}
@@ -533,15 +534,15 @@ extension Database {
}
/// A thread-unsafe statement cache
struct StatementCache {
unowned let db: Database
private var statements: [String: Statement] = [:]
struct StatementCache<API: SQLiteAPI> {
unowned let db: DatabaseBase<API>
private var statements: [String: StatementBase<API>] = [:]
init(database: Database) {
init(database: DatabaseBase<API>) {
self.db = database
}
mutating func statement(_ sql: String) throws -> Statement {
mutating func statement(_ sql: String) throws -> StatementBase<API> {
if let statement = statements[sql] {
return statement
}
@@ -561,11 +562,11 @@ struct StatementCache {
statements = [:]
}
mutating func remove(_ statement: Statement) {
mutating func remove(_ statement: StatementBase<API>) {
statements.removeFirst { $0.value === statement }
}
mutating func removeAll(where shouldBeRemoved: (Statement) -> Bool) {
mutating func removeAll(where shouldBeRemoved: (StatementBase<API>) -> Bool) {
statements = statements.filter { (_, statement) in !shouldBeRemoved(statement) }
}
}
+233 -82
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -113,6 +116,11 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``resumeNotification``
/// - ``suspendNotification``
///
/// ### The Schema Source
///
/// - ``schemaSource``
/// - ``withSchemaSource(_:execute:)``
///
/// ### Other Database Operations
///
/// - ``add(tokenizer:)``
@@ -121,6 +129,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``clearSchemaCache()``
/// - ``logError``
/// - ``releaseMemory()``
/// - ``sqliteLibVersionNumber``
/// - ``trace(options:_:)``
///
/// ### Supporting Types
@@ -133,7 +142,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``StorageClass``
/// - ``TraceEvent``
/// - ``TracingOptions``
public final class Database: CustomStringConvertible, CustomDebugStringConvertible {
public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, CustomDebugStringConvertible {
// The Database class is not thread-safe. An instance should always be
// used through a SerializedDatabase.
@@ -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``
@@ -293,7 +315,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
///
/// It is nil in read-only connections, because we do not report read-only
/// transactions to transaction observers.
private(set) var observationBroker: DatabaseObservationBroker?
private(set) var observationBroker: DatabaseObservationBroker<API>?
/// The list of compile options used when building SQLite
static func sqliteCompileOptions() throws -> Set<String> {
@@ -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
}
@@ -1401,7 +1491,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// either ``TransactionCompletion/commit`` or ``TransactionCompletion/rollback``.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the
/// error thrown by `operations`.
public func inTransaction(_ kind: TransactionKind? = nil, _ operations: () throws -> TransactionCompletion) throws {
public func inTransaction(_ kind: DatabaseTransactionKind? = nil, _ operations: () throws -> DatabaseTransactionCompletion) throws {
// Begin transaction
try beginTransaction(kind)
@@ -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()
@@ -1613,7 +1703,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// If nil, the transaction kind is DEFERRED when the current
/// database access is read-only, and IMMEDIATE otherwise.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
public func beginTransaction(_ kind: DatabaseTransactionKind? = nil) throws {
// SQLite throws an error for non-deferred transactions when read-only.
// We prefer immediate transactions for writes, so that write
// transactions can not overlap. This reduces the opportunity for
@@ -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.
@@ -1855,10 +1945,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// Explicit non-conformance to Sendable: `Database` must be used from a
// serialized database access dispatch queue (see `SerializedDatabase`).
@available(*, unavailable)
extension Database: Sendable { }
extension DatabaseBase: Sendable { }
#if SQLITE_HAS_CODEC
extension Database {
extension DatabaseBase {
// MARK: - Encryption
@@ -1931,7 +2021,35 @@ extension Database {
}
#endif
extension Database {
extension DatabaseBase {
/// Returns the count of changes executed by one statement execution.
func countChanges<T>(_ count: inout Int, forTable tableName: String, updates: () throws -> T) throws -> T {
// Database.changesCount calls sqlite3_changes(), whose documentation says:
//
// > https://sqlite.org/c3ref/changes.html
// > Changes to a view that are intercepted by INSTEAD OF triggers are not counted.
//
// We want to support INSTEAD OF triggers, so we prefer to use
// sqlite3_total_changes() for views.
//
// At the same time, FTS5 has sqlite3_total_changes() report changes
// even when database is not changed (https://github.com/groue/GRDB.swift/issues/1820)
//
// Well, let's do our best:
if try viewExists(tableName) {
let prevCount = totalChangesCount
let result = try updates()
count = totalChangesCount - prevCount
return result
} else {
let result = try updates()
count = changesCount
return result
}
}
}
extension DatabaseBase {
// MARK: - Database-Related Types
@@ -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")
@@ -2086,26 +2207,6 @@ extension Database {
public static let any = ColumnType(rawValue: "ANY")
}
/// An SQLite conflict resolution.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_conflict.html>
public enum ConflictResolution: String, Sendable {
/// The `ROLLBACK` conflict resolution.
case rollback = "ROLLBACK"
/// The `ABORT` conflict resolution.
case abort = "ABORT"
/// The `FAIL` conflict resolution.
case fail = "FAIL"
/// The `IGNORE` conflict resolution.
case ignore = "IGNORE"
/// The `REPLACE` conflict resolution.
case replace = "REPLACE"
}
/// A foreign key action.
///
/// Related SQLite documentation: <https://www.sqlite.org/foreignkeys.html>
@@ -2292,29 +2393,6 @@ extension Database {
}
}
/// A transaction commit, or rollback.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
@frozen
public enum TransactionCompletion: Sendable {
case commit
case rollback
}
/// A transaction kind.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
public enum TransactionKind: String, Sendable {
/// The `DEFERRED` transaction kind.
case deferred = "DEFERRED"
/// The `IMMEDIATE` transaction kind.
case immediate = "IMMEDIATE"
/// The `EXCLUSIVE` transaction kind.
case exclusive = "EXCLUSIVE"
}
/// An SQLite threading mode. See <https://www.sqlite.org/threadsafe.html>.
///
/// - Note: Only the multi-thread mode (`SQLITE_OPEN_NOMUTEX`) is currently
@@ -2338,6 +2416,79 @@ extension Database {
}
}
#warning("TODO: export as DatabaseConflictResolution")
/// An SQLite conflict resolution.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_conflict.html>
public enum DatabaseConflictResolution: String, Sendable {
/// The `ROLLBACK` conflict resolution.
case rollback = "ROLLBACK"
/// The `ABORT` conflict resolution.
case abort = "ABORT"
/// The `FAIL` conflict resolution.
case fail = "FAIL"
/// The `IGNORE` conflict resolution.
case ignore = "IGNORE"
/// The `REPLACE` conflict resolution.
case replace = "REPLACE"
}
#warning("TODO: export as Database.StorageClass")
/// An SQLite storage class.
///
/// For more information, see
/// [Datatypes In SQLite](https://www.sqlite.org/datatype3.html).
public struct DatabaseStorageClass: RawRepresentable, Hashable, Sendable {
/// The SQL for the storage class (`"INTEGER"`, `"REAL"`, etc.)
public let rawValue: String
/// Creates an SQL storage class.
public init(rawValue: String) {
self.rawValue = rawValue
}
/// The `INTEGER` storage class.
public static let integer = StorageClass(rawValue: "INTEGER")
/// The `REAL` storage class.
public static let real = StorageClass(rawValue: "REAL")
/// The `TEXT` storage class.
public static let text = StorageClass(rawValue: "TEXT")
/// The `BLOB` storage class.
public static let blob = StorageClass(rawValue: "BLOB")
}
#warning("TODO: export as Database.TransactionCompletion")
/// A transaction commit, or rollback.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
@frozen
public enum DatabaseTransactionCompletion: Sendable {
case commit
case rollback
}
#warning("TODO: export as Database.TransactionKind")
/// A transaction kind.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
public enum DatabaseTransactionKind: String, Sendable {
/// The `DEFERRED` transaction kind.
case deferred = "DEFERRED"
/// The `IMMEDIATE` transaction kind.
case immediate = "IMMEDIATE"
/// The `EXCLUSIVE` transaction kind.
case exclusive = "EXCLUSIVE"
}
// Explicit non-conformance to Sendable: a trace event contains transient
// information.
@available(*, unavailable)
+31 -24
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -53,12 +56,21 @@ public final class DatabaseCollation: Identifiable, Sendable {
}
}
/// Feeds the `xCompare` parameter of sqlite3_create_collation_v2
/// <https://www.sqlite.org/c3ref/create_collation.html>
typealias XCompare = @Sendable (
_ length1: CInt,
_ buffer1: UnsafeRawPointer,
_ length2: CInt,
_ buffer2: UnsafeRawPointer
) -> CInt
/// The identifier of the collation.
public var id: ID { ID(name: name) }
/// The name of the collation.
public let name: String
let function: @Sendable (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
let xCompare: XCompare
/// Creates a collation.
///
@@ -75,21 +87,16 @@ public final class DatabaseCollation: Identifiable, Sendable {
/// - parameters:
/// - name: The collation name.
/// - function: A function that compares two strings.
public init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
public convenience init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
self.init(name, xCompare: { (length1, buffer1, length2, buffer2) in
let string1 = String(decoding: UnsafeRawBufferPointer(start: buffer1, count: Int(length1)), as: UTF8.self)
let string2 = String(decoding: UnsafeRawBufferPointer(start: buffer2, count: Int(length2)), as: UTF8.self)
return CInt(function(string1, string2).rawValue)
})
}
init(_ name: String, xCompare: @escaping XCompare) {
self.name = name
self.function = { (length1, buffer1, length2, buffer2) in
// Buffers are not C strings: they do not end with \0.
let string1 = String(
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped),
length: Int(length1),
encoding: .utf8,
freeWhenDone: false)!
let string2 = String(
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped),
length: Int(length2),
encoding: .utf8,
freeWhenDone: false)!
return function(string1, string2)
}
self.xCompare = xCompare
}
}
+11 -8
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
+67 -29
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
/// A custom SQL function or aggregate.
///
@@ -82,20 +85,43 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// such as `Int`, `String`, `Date`, etc. The array is guaranteed to
/// have exactly `argumentCount` elements, provided `argumentCount` is
/// not nil.
public init(
public convenience init(
_ name: String,
argumentCount: Int? = nil,
pure: Bool = false,
function: @escaping @Sendable ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
{
self.init(name, argumentCount: argumentCount, pure: pure) { (argc, argv, context) in
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv[index]!)
}
let result = try function(arguments)
switch result?.databaseValue.storage ?? .null {
case .null:
sqlite3_result_null(context)
case .int64(let int64):
sqlite3_result_int64(context, int64)
case .double(let double):
sqlite3_result_double(context, double)
case .string(let string):
sqlite3_result_text(context, string, -1, SQLITE_TRANSIENT)
case .blob(let data):
data.withUnsafeBytes {
sqlite3_result_blob(context, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
}
}
}
}
init(
_ name: String,
argumentCount: Int? = nil,
pure: Bool = false,
xFunc: @escaping XFunc)
{
self.id = ID(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
self.isPure = pure
self.kind = .function { (argc, argv) in
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
}
return try function(arguments)
}
self.kind = .function(xFunc)
}
/// Creates an SQL aggregate function.
@@ -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)
/// }
/// ```
@@ -204,7 +237,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// Calls sqlite3_create_function_v2
/// See <https://sqlite.org/c3ref/create_function.html>
func install(in db: Database) {
func install(in db: DatabaseBase<some SQLiteAPI>) {
// Retain the function definition
let definition = kind.definition
let definitionP = Unmanaged.passRetained(definition).toOpaque()
@@ -231,7 +264,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// Calls sqlite3_create_function_v2
/// See <https://sqlite.org/c3ref/create_function.html>
func uninstall(in db: Database) {
func uninstall(in db: DatabaseBase<some SQLiteAPI>) {
let code = sqlite3_create_function_v2(
db.sqliteConnection,
id.name,
@@ -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.
+87 -93
View File
@@ -4,8 +4,8 @@ import Foundation
import UIKit
#endif
public final class DatabasePool {
private let writer: SerializedDatabase
public final class DatabasePoolBase<API: SQLiteAPI> {
private let writer: SerializedDatabase<API>
/// The pool of reader connections.
/// It is constant, until close() sets it to nil.
@@ -143,9 +143,9 @@ public final class DatabasePool {
}
// @unchecked because of readerPool and suspensionObservers
extension DatabasePool: @unchecked Sendable { }
extension DatabasePoolBase: @unchecked Sendable { }
extension DatabasePool {
extension DatabasePoolBase {
// MARK: - Memory management
@@ -263,7 +263,7 @@ extension DatabasePool {
#endif
}
extension DatabasePool: DatabaseReader {
extension DatabasePoolBase: DatabaseReaderBase {
public func close() throws {
try readerPool?.barrier {
@@ -336,7 +336,7 @@ extension DatabasePool: DatabaseReader {
// MARK: - Reading from Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ value: (Database) throws -> T) throws -> T {
public func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
@@ -352,45 +352,34 @@ extension DatabasePool: DatabaseReader {
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<API>) 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)
}
}
}
public func asyncRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
@@ -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 {
@@ -422,7 +418,7 @@ extension DatabasePool: DatabaseReader {
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
public func unsafeRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
@@ -436,41 +432,22 @@ extension DatabasePool: DatabaseReader {
}
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<API>) 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)
}
}
}
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
@@ -498,7 +475,7 @@ extension DatabasePool: DatabaseReader {
}
}
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
if let reader = currentReader {
return try reader.reentrantSync(value)
} else if writer.onValidQueue {
@@ -517,7 +494,7 @@ extension DatabasePool: DatabaseReader {
}
public func spawnConcurrentRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
asyncConcurrentRead(value)
}
@@ -560,7 +537,7 @@ extension DatabasePool: DatabaseReader {
///
/// - parameter value: A function that accesses the database.
public func asyncConcurrentRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
// Check that we're on the writer queue...
writer.execute { db in
@@ -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,15 +684,15 @@ extension DatabasePool: DatabaseReader {
// MARK: - WAL Snapshot Transactions
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
/// Returns a long-lived WAL snapshot transaction on a reader connection.
func walSnapshotTransaction() throws -> WALSnapshotTransaction {
func walSnapshotTransaction() throws -> WALSnapshotTransactionBase<API> {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
let (reader, releaseReader) = try readerPool.get()
return try WALSnapshotTransaction(onReader: reader, release: { isInsideTransaction in
return try WALSnapshotTransactionBase(onReader: reader, release: { isInsideTransaction in
// Discard the connection if the transaction could not be
// properly ended. If we'd reuse it, the next read would
// fail because we'd fail starting a read transaction.
@@ -721,7 +705,7 @@ extension DatabasePool: DatabaseReader {
/// - important: The `completion` argument is executed in a serial
/// dispatch queue, so make sure you use the transaction asynchronously.
func asyncWALSnapshotTransaction(
_ completion: @escaping @Sendable (Result<WALSnapshotTransaction, Error>) -> Void
_ completion: @escaping @Sendable (Result<WALSnapshotTransactionBase<API>, Error>) -> Void
) {
guard let readerPool else {
completion(.failure(DatabaseError.connectionIsClosed()))
@@ -793,22 +777,22 @@ extension DatabasePool: DatabaseReader {
}
}
extension DatabasePool: DatabaseWriter {
extension DatabasePoolBase: DatabaseWriterBase {
// MARK: - Writing in Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
public func writeWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
try writer.sync(updates)
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
public func barrierWriteWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
}
@@ -818,27 +802,37 @@ extension DatabasePool: DatabaseWriter {
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (DatabaseBase<API>) 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?() }
}
}
public func asyncBarrierWriteWithoutTransaction(
_ updates: @escaping @Sendable (Result<Database, Error>) -> Void
_ updates: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
guard let readerPool else {
updates(.failure(DatabaseError.connectionIsClosed()))
@@ -879,7 +873,7 @@ extension DatabasePool: DatabaseWriter {
/// - throws: The error thrown by `updates`, or by the wrapping transaction.
public func writeInTransaction(
_ kind: Database.TransactionKind? = nil,
_ updates: (Database) throws -> Database.TransactionCompletion)
_ updates: (DatabaseBase<API>) throws -> Database.TransactionCompletion)
throws
{
try writer.sync { db in
@@ -889,18 +883,18 @@ extension DatabasePool: DatabaseWriter {
}
}
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
public func unsafeReentrantWrite<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(
_ updates: @escaping @Sendable (Database) -> Void
_ updates: @escaping @Sendable (DatabaseBase<API>) -> Void
) {
writer.async(updates)
}
}
extension DatabasePool {
extension DatabasePoolBase {
// MARK: - Snapshots
@@ -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.
+40 -28
View File
@@ -4,8 +4,8 @@ import Foundation
import UIKit
#endif
public final class DatabaseQueue {
private let writer: SerializedDatabase
public final class DatabaseQueueBase<API: SQLiteAPI> {
private let writer: SerializedDatabase<API>
/// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers.
private var suspensionObservers: [NSObjectProtocol] = []
@@ -124,9 +124,9 @@ public final class DatabaseQueue {
}
// @unchecked because of suspensionObservers
extension DatabaseQueue: @unchecked Sendable { }
extension DatabaseQueueBase: @unchecked Sendable { }
extension DatabaseQueue {
extension DatabaseQueueBase {
// MARK: - Memory management
@@ -183,7 +183,7 @@ extension DatabaseQueue {
#endif
}
extension DatabaseQueue: DatabaseReader {
extension DatabaseQueueBase: DatabaseReaderBase {
public func close() throws {
try writer.sync { try $0.close() }
}
@@ -225,7 +225,7 @@ extension DatabaseQueue: DatabaseReader {
// MARK: - Reading from Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ value: (Database) throws -> T) throws -> T {
public func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
try writer.sync { db in
try db.isolated(readOnly: true) {
try value(db)
@@ -234,7 +234,7 @@ extension DatabaseQueue: DatabaseReader {
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await writer.execute { db in
try db.isolated(readOnly: true) {
@@ -244,12 +244,18 @@ extension DatabaseQueue: DatabaseReader {
}
public func asyncRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
writer.async { db in
defer {
// Ignore 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()
}
@@ -267,28 +273,28 @@ extension DatabaseQueue: DatabaseReader {
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (Database) throws -> T) rethrows -> T {
public func unsafeRead<T>(_ value: (DatabaseBase<API>) throws -> T) rethrows -> T {
try writer.sync(value)
}
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await writer.execute(value)
}
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
writer.async { value(.success($0)) }
}
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) rethrows -> T {
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<API>) throws -> T) rethrows -> T {
try writer.reentrantSync(value)
}
public func spawnConcurrentRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
// Check that we're on the writer queue...
writer.execute { db in
@@ -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()
}
@@ -337,7 +349,7 @@ extension DatabaseQueue: DatabaseReader {
}
}
extension DatabaseQueue: DatabaseWriter {
extension DatabaseQueueBase: DatabaseWriterBase {
// MARK: - Writing in Database
/// Wraps database operations inside a database transaction.
@@ -369,7 +381,7 @@ extension DatabaseQueue: DatabaseWriter {
/// - throws: The error thrown by `updates`, or by the wrapping transaction.
public func inTransaction(
_ kind: Database.TransactionKind? = nil,
_ updates: (Database) throws -> Database.TransactionCompletion)
_ updates: (DatabaseBase<API>) throws -> Database.TransactionCompletion)
throws
{
try writer.sync { db in
@@ -380,29 +392,29 @@ extension DatabaseQueue: DatabaseWriter {
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
public func writeWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
try writer.sync(updates)
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
public func barrierWriteWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) throws -> T {
try writer.sync(updates)
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await writer.execute(updates)
}
public func asyncBarrierWriteWithoutTransaction(
_ updates: @escaping @Sendable (Result<Database, Error>) -> Void
_ updates: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
writer.async { updates(.success($0)) }
}
@@ -441,16 +453,16 @@ extension DatabaseQueue: DatabaseWriter {
///
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`.
public func inDatabase<T>(_ updates: (Database) throws -> T) rethrows -> T {
public func inDatabase<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
try writer.sync(updates)
}
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
public func unsafeReentrantWrite<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
try writer.reentrantSync(updates)
}
public func asyncWriteWithoutTransaction(
_ updates: @escaping @Sendable (Database) -> Void
_ updates: @escaping @Sendable (DatabaseBase<API>) -> Void
) {
writer.async(updates)
}
@@ -458,7 +470,7 @@ extension DatabaseQueue: DatabaseWriter {
// MARK: - Temp Copy
extension DatabaseQueue {
extension DatabaseQueueBase {
/// Returns a connection to an in-memory copy of the database at `path`.
///
/// Changes performed on the returned connection do not impact the
+29 -28
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(_:)``
///
@@ -52,7 +52,8 @@ import Dispatch
/// ### Supporting Types
///
/// - ``AnyDatabaseReader``
public protocol DatabaseReader: AnyObject, Sendable {
public protocol DatabaseReaderBase<API>: AnyObject, Sendable {
associatedtype API: SQLiteAPI
/// The database configuration.
var configuration: Configuration { get }
@@ -186,7 +187,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
/// would happen while establishing the database access.
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func read<T>(_ value: (Database) throws -> T) throws -> T
func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T
/// Executes read-only database operations, and returns their result after
/// they have finished executing.
@@ -215,7 +216,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// database access, or the error thrown by `value`, or
/// `CancellationError` if the task is cancelled.
func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T
/// Schedules read-only database operations for execution, and
@@ -245,7 +246,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func asyncRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
)
/// Executes database operations, and returns their result after they have
@@ -284,7 +285,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
/// would happen while establishing the database access.
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T
func unsafeRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -319,7 +320,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// database access, or the error thrown by `value`, or
/// `CancellationError` if the task is cancelled.
func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T
/// Schedules database operations for execution, and returns immediately.
@@ -354,7 +355,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
)
/// Executes database operations, and returns their result after they have
@@ -398,7 +399,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// - parameter value: A closure which accesses the database.
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
/// would happen while establishing the database access.
func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T
func unsafeReentrantRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T
// MARK: - Value Observation
@@ -417,7 +418,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
) -> AnyDatabaseCancellable
}
extension DatabaseReader {
extension DatabaseReaderBase {
// MARK: - Backup
@@ -499,7 +500,7 @@ extension DatabaseReader {
}
#if canImport(Combine)
extension DatabaseReader {
extension DatabaseReaderBase {
// MARK: - Publishing Database Values
/// Returns a publisher that publishes one value and completes.
@@ -531,7 +532,7 @@ extension DatabaseReader {
/// - parameter value: A closure which accesses the database.
public func readPublisher<Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
value: @escaping @Sendable (Database) throws -> Output
value: @escaping @Sendable (DatabaseBase<API>) throws -> Output
) -> DatabasePublishers.Read<Output> {
OnDemandFuture { fulfill in
self.asyncRead { dbResult in
@@ -568,7 +569,7 @@ extension Publisher where Failure == Error {
}
#endif
extension DatabaseReader {
extension DatabaseReaderBase {
// MARK: - Value Observation Support
/// Adding an observation in a read-only database emits only the
@@ -619,17 +620,17 @@ extension DatabaseReader {
///
/// An instance of `AnyDatabaseReader` forwards its operations to an underlying
/// base database reader.
public final class AnyDatabaseReader {
private let base: any DatabaseReader
public final class AnyDatabaseReaderBase<API: SQLiteAPI> {
private let base: any DatabaseReader<API>
/// Creates a new database reader that wraps and forwards operations
/// to `base`.
public init(_ base: any DatabaseReader) {
public init(_ base: any DatabaseReader<API>) {
self.base = base
}
}
extension AnyDatabaseReader: DatabaseReader {
extension AnyDatabaseReaderBase: DatabaseReaderBase {
public var configuration: Configuration {
base.configuration
}
@@ -647,40 +648,40 @@ extension AnyDatabaseReader: DatabaseReader {
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ value: (Database) throws -> T) throws -> T {
public func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
try base.read(value)
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await base.read(value)
}
public func asyncRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
base.asyncRead(value)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
public func unsafeRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
try base.unsafeRead(value)
}
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await base.unsafeRead(value)
}
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
base.asyncUnsafeRead(value)
}
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
try base.unsafeReentrantRead(value)
}
@@ -735,20 +736,20 @@ extension DatabaseSnapshotReader {
/// - parameter value: A closure which accesses the database.
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
/// would happen while establishing the database access.
public func reentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
public func reentrantRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
// Reentrant reads are safe in a snapshot
try unsafeReentrantRead(value)
}
// There is no such thing as an unsafe access to a snapshot.
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
public func unsafeRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
try read(value)
}
// There is no such thing as an unsafe access to a snapshot.
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
asyncRead(value)
}
+11 -11
View File
@@ -163,7 +163,7 @@ public struct DatabaseRegion: Sendable {
}
/// Returns a region suitable for database observation
func observableRegion(_ db: Database) throws -> DatabaseRegion {
func observableRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion {
// SQLite does not expose schema changes to the
// TransactionObserver protocol. By removing internal SQLite tables from
// the observed region, we optimize database observation.
@@ -178,7 +178,7 @@ public struct DatabaseRegion: Sendable {
/// Returns a region only made of actual tables with their canonical names.
///
/// This method removes views.
func canonicalTables(_ db: Database) throws -> DatabaseRegion {
func canonicalTables(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion {
guard let tableRegions else { return .fullDatabase }
var region = DatabaseRegion()
for (table, tableRegion) in tableRegions {
@@ -237,7 +237,7 @@ extension DatabaseRegion {
/// Returns an array of all event kinds that can impact this region.
///
/// - precondition: the region is canonical.
func impactfulEventKinds(_ db: Database) throws -> [DatabaseEventKind] {
func impactfulEventKinds(_ db: DatabaseBase<some SQLiteAPI>) throws -> [DatabaseEventKind] {
if let tableRegions {
return try tableRegions.flatMap { (table, tableRegion) -> [DatabaseEventKind] in
let tableName = table.rawValue // canonical table name
@@ -256,8 +256,8 @@ extension DatabaseRegion {
}
} else {
// full database
return try db.schemaIdentifiers().flatMap { schemaIdentifier in
let schema = try db.schema(schemaIdentifier)
return try db.fetchSchemaIdentifiers().flatMap { schemaID in
let schema = try db.schema(schemaID)
return try schema.objects
.filter { $0.type == .table }
.flatMap { table in
@@ -420,7 +420,7 @@ public protocol DatabaseRegionConvertible: Sendable {
/// Returns a database region.
///
/// - parameter db: A database connection.
func databaseRegion(_ db: Database) throws -> DatabaseRegion
func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
}
extension DatabaseRegionConvertible where Self == DatabaseRegion {
@@ -430,16 +430,16 @@ extension DatabaseRegionConvertible where Self == DatabaseRegion {
}
extension DatabaseRegion: DatabaseRegionConvertible {
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
public func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion {
self
}
}
/// A type-erased DatabaseRegionConvertible
public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
let _region: @Sendable (Database) throws -> DatabaseRegion
let _region: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
public init(_ region: @escaping @Sendable (Database) throws -> DatabaseRegion) {
public init(_ region: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion) {
_region = region
}
@@ -447,7 +447,7 @@ public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
_region = { try region.databaseRegion($0) }
}
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
public func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion {
try _region(db)
}
}
@@ -461,7 +461,7 @@ extension DatabaseRegion {
}
}
static func union(_ regions: [any DatabaseRegionConvertible]) -> @Sendable (Database) throws -> DatabaseRegion {
static func union<API: SQLiteAPI>(_ regions: [any DatabaseRegionConvertible]) -> @Sendable (DatabaseBase<API>) throws -> DatabaseRegion {
return { db in
try regions.reduce(into: DatabaseRegion()) { union, region in
try union.formUnion(region.databaseRegion(db))
+14 -9
View File
@@ -6,7 +6,7 @@ import Foundation
public struct DatabaseRegionObservation: Sendable {
/// A closure that is evaluated when the observation starts, and returns
/// the observed database region.
var observedRegion: @Sendable (Database) throws -> DatabaseRegion
var observedRegion: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
}
extension DatabaseRegionObservation {
@@ -83,10 +83,11 @@ 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,
onChange: @escaping @Sendable (Database) -> Void)
onChange: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) -> Void)
-> AnyDatabaseCancellable
{
let stateMutex = Mutex(ObservationState.pending)
@@ -145,12 +146,12 @@ extension DatabaseRegionObservation {
}
#endif
private class DatabaseRegionObserver: TransactionObserver {
private class DatabaseRegionObserver: TransactionObserverBase {
let region: DatabaseRegion
let onChange: @Sendable (Database) -> Void
let onChange: @Sendable (DatabaseBase<some SQLiteAPI>) -> Void
var isChanged = false
init(region: DatabaseRegion, onChange: @escaping @Sendable (Database) -> Void) {
init(region: DatabaseRegion, onChange: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) -> Void) {
self.region = region
self.onChange = onChange
}
@@ -171,14 +172,14 @@ private class DatabaseRegionObserver: TransactionObserver {
}
}
func databaseDidCommit(_ db: Database) {
func databaseDidCommit(_ db: DatabaseBase<some SQLiteAPI>) {
guard isChanged else { return }
isChanged = false
onChange(db)
}
func databaseDidRollback(_ db: Database) {
func databaseDidRollback(_ db: DatabaseBase<some SQLiteAPI>) {
isChanged = false
}
}
@@ -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: DatabaseBase<some SQLiteAPI>, inView view: DatabaseObjectID) {
/// ["id"]
/// }
/// }
///
/// // A database connection configured with the schema source.
/// var config = Configuration()
/// config.schemaSource = MySchemaSource()
/// let dbQueue = try DatabaseQueue(path: "/path/to/db.sqlite", configuration: config)
///
/// // A record type that feeds from a view.
/// struct Player: Decodable, Identifiable, FetchableRecord {
/// static let databaseTableName = "playerView"
/// var id: String
/// var name: String
/// }
///
/// // Thanks to the schema source, we can fetch players by id:
/// let player = try dbQueue.read { db in
/// try Player.find(db, id: "alice")
/// }
/// ```
///
/// ### Schema Sources in Libraries
///
/// When you are developing a schema source for a library, some extra
/// care is necessary whenever the database file is owned by the users
/// of your library. Your users may define views for their own purposes,
/// and your library knows nothing about the eventual primary key of
/// those views.
///
/// In this case, make your schema source `public`, and have this method
/// return `nil` for those unknown views. If needed, use the `db`
/// argument and query the database schema with
/// <doc:DatabaseSchemaIntrospection> methods.
///
/// For example:
///
/// ```swift
/// // A well-behaved schema source defined by a library is public
/// // and returns nil for unknown views.
/// public struct MyLibrarySchemaSource: DatabaseSchemaSource {
/// public func columnsForPrimaryKey(_ db: DatabaseBase<some SQLiteAPI>, inView view: DatabaseObjectID) {
/// if view.name == "playerView" {
/// // This is a view managed by my library:
/// return ["id"]
/// } else if try db.tableExists(view.name + "MyLibrary") {
/// // This is a view managed by my library:
/// return ["uuid"]
/// } else {
/// // Not a view managed by my library:
/// // don't mess with user's schema
/// return nil
/// }
/// }
/// }
/// ```
///
/// With such a setup, your user will be able to deal with their
/// own views, by chaining your schema source with other ones
/// (see ``DatabaseSchemaSource/then(_:)``):
///
/// ```swift
/// // Application code
/// import MyLibrary
/// import GRDB
///
/// let myLibrarySchemaSource = MyLibrarySchemaSource()
/// let customSchemaSource = TheirCustomSchemaSource()
/// let schemaSource = myLibrarySchemaSource.then(customSchemaSource)
///
/// var config = Configuration()
/// config.schemaSource = schemaSource
/// let dbQueue = try DatabaseQueue(path: "...", configuration: config)
/// ```
///
/// - Parameters:
/// - db: A database connection.
/// - view: The identifier of a database view.
func columnsForPrimaryKey(
_ db: DatabaseBase<some SQLiteAPI>,
inView view: DatabaseObjectID
) throws -> [String]?
}
extension DatabaseSchemaSource {
public func columnsForPrimaryKey(
_ db: DatabaseBase<some SQLiteAPI>,
inView view: DatabaseObjectID
) throws -> [String]? {
nil
}
}
// MARK: - Combined2SchemaSource
extension DatabaseSchemaSource {
/// Returns a schema source that queries `other` when this source does
/// not perform a customization.
///
/// For example:
///
/// ```swift
/// let schemaSource1 = SomeSchemaSource()
/// let schemaSource2 = AnotherSchemaSource()
/// let schemaSource = schemaSource1.then(schemaSource2)
///
/// var config = Configuration()
/// config.schemaSource = schemaSource
/// let dbQueue = try DatabaseQueue(path: "...", configuration: config)
/// ```
public func then(_ other: some DatabaseSchemaSource) -> some DatabaseSchemaSource {
Chained2SchemaSource(first: self, second: other)
}
}
// TODO: move to parameter packs eventually. Parameter packs in generic types
// are only available in macOS 14.0.0 or newer.
// This schema source is designed to tame bad citizens that customize tables
// and views they do not own (such as insufficienly robust schema sources
// exposed by external libraries). We should NEVER MERGE the results of the
// schema sources.
struct Chained2SchemaSource<Source1, Source2>: DatabaseSchemaSource
where Source1: DatabaseSchemaSource,
Source2: DatabaseSchemaSource
{
var first: Source1
var second: Source2
func columnsForPrimaryKey(_ db: DatabaseBase<some SQLiteAPI>, inView view: DatabaseObjectID) throws -> [String]? {
if let result = try first.columnsForPrimaryKey(db, inView: view) { return result }
if let result = try second.columnsForPrimaryKey(db, inView: view) { return result }
return nil
}
}
+15 -8
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)
}
}
@@ -147,24 +154,24 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
// MARK: - Reading from Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
public func read<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T {
try reader.sync(block)
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> T
) async throws -> T {
try await reader.execute(value)
}
public func asyncRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<some SQLiteAPI>, Error>) -> Void
) {
reader.async { value(.success($0)) }
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (Database) throws -> T) rethrows -> T {
public func unsafeRead<T>(_ value: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T {
try reader.sync(value)
}
@@ -173,18 +180,18 @@ 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 (DatabaseBase<some SQLiteAPI>) throws -> T
) async throws -> T {
try await read(value)
}
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<some SQLiteAPI>, Error>) -> Void
) {
reader.async { value(.success($0)) }
}
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T {
try reader.reentrantSync(value)
}
+32 -40
View File
@@ -1,12 +1,15 @@
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
/// A database connection that allows concurrent accesses to an unchanging
/// database content, as it existed at the moment the snapshot was created.
@@ -129,7 +132,7 @@ public final class DatabaseSnapshotPool {
/// - parameter configuration: A configuration. If nil, the configuration of
/// `db` is used.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public init(_ db: Database, configuration: Configuration? = nil) throws {
public init(_ db: DatabaseBase<some SQLiteAPI>, configuration: Configuration? = nil) throws {
let path = db.path
var configuration = Self.configure(configuration ?? db.configuration)
@@ -270,7 +273,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ value: (Database) throws -> T) throws -> T {
public func read<T>(_ value: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T {
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
@@ -294,40 +297,29 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<some SQLiteAPI>) 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(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<some SQLiteAPI>, Error>) -> Void
) {
guard let readerPool else {
value(.failure(DatabaseError.connectionIsClosed()))
@@ -353,12 +345,12 @@ 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 (DatabaseBase<some SQLiteAPI>) throws -> T
) async throws -> T {
try await read(value)
}
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T {
if let reader = currentReader {
return try reader.reentrantSync { db in
let result = try value(db)
@@ -407,11 +399,11 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
return readers.first { $0.onValidQueue }
}
private func poolCompletion(_ db: Database) -> PoolCompletion {
private func poolCompletion(_ db: DatabaseBase<some SQLiteAPI>) -> PoolCompletion {
snapshotIsLost(db) ? .discard : .reuse
}
private func snapshotIsLost(_ db: Database) -> Bool {
private func snapshotIsLost(_ db: DatabaseBase<some SQLiteAPI>) -> Bool {
do {
let currentSnapshot = try WALSnapshot(db)
if currentSnapshot.compare(walSnapshot) == 0 {
+13 -10
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -159,7 +162,7 @@ public struct DatabaseValue: Hashable {
}
/// Creates a `DatabaseValue` initialized from a raw SQLite statement pointer.
public init(sqliteStatement: SQLiteStatement, index: CInt) {
public init(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_NULL:
storage = .null
@@ -184,7 +187,7 @@ public struct DatabaseValue: Hashable {
}
extension DatabaseValue: StatementBinding {
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
switch storage {
case .null:
return sqlite3_bind_null(sqliteStatement, index)
+82 -33
View File
@@ -80,7 +80,7 @@ extension DatabaseValueConvertible {
.databaseValue(databaseValue)
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
public func bind(to sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, at index: CInt) -> CInt {
databaseValue.bind(to: sqliteStatement, at: index)
}
@@ -276,7 +276,7 @@ extension DatabaseValueConvertible {
/// - returns: A ``DatabaseValueCursor`` over fetched values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> DatabaseValueCursor<Self>
@@ -307,7 +307,7 @@ extension DatabaseValueConvertible {
/// - returns: An array.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> [Self]
@@ -341,7 +341,7 @@ extension DatabaseValueConvertible {
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Self?
@@ -376,7 +376,7 @@ extension DatabaseValueConvertible where Self: Hashable {
/// - returns: A set.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Set<Self>
@@ -421,7 +421,7 @@ extension DatabaseValueConvertible {
/// - returns: A ``DatabaseValueCursor`` over fetched values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -453,7 +453,7 @@ extension DatabaseValueConvertible {
/// - returns: An array.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -488,7 +488,7 @@ extension DatabaseValueConvertible {
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -522,7 +522,7 @@ extension DatabaseValueConvertible where Self: Hashable {
/// - returns: A set.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -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> = """
@@ -574,7 +581,7 @@ extension DatabaseValueConvertible {
/// - request: A fetch request.
/// - returns: A ``DatabaseValueCursor`` over fetched values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: some FetchRequest) throws -> DatabaseValueCursor<Self> {
public static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> DatabaseValueCursor<Self> {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchCursor(request.statement, adapter: request.adapter)
}
@@ -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> = """
@@ -608,7 +622,7 @@ extension DatabaseValueConvertible {
/// - request: A fetch request.
/// - returns: An array.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
public static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> [Self] {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchAll(request.statement, adapter: request.adapter)
}
@@ -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> = """
@@ -645,7 +666,7 @@ extension DatabaseValueConvertible {
/// - request: A fetch request.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
public static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> Self? {
let request = try request.makePreparedRequest(db, forSingleResult: true)
return try fetchOne(request.statement, adapter: request.adapter)
}
@@ -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> = """
@@ -681,7 +709,7 @@ extension DatabaseValueConvertible where Self: Hashable {
/// - request: A fetch request.
/// - returns: A set.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
public static func fetchSet(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> Set<Self> {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchSet(request.statement, adapter: request.adapter)
}
@@ -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> = """
@@ -727,7 +762,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// - parameter db: A database connection.
/// - returns: A ``DatabaseValueCursor`` over fetched values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder> {
public func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseValueCursor<RowDecoder> {
try RowDecoder.fetchCursor(db, self)
}
@@ -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> = """
@@ -758,7 +800,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
public func fetchAll(_ db: DatabaseBase<some SQLiteAPI>) throws -> [RowDecoder] {
try RowDecoder.fetchAll(db, self)
}
@@ -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> = """
@@ -792,7 +841,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
public func fetchOne(_ db: DatabaseBase<some SQLiteAPI>) throws -> RowDecoder? {
try RowDecoder.fetchOne(db, self)
}
}
@@ -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> = """
@@ -825,7 +874,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable {
/// - parameter db: A database connection.
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
public func fetchSet(_ db: DatabaseBase<some SQLiteAPI>) throws -> Set<RowDecoder> {
try RowDecoder.fetchSet(db, self)
}
}
+35 -35
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
@@ -61,7 +61,7 @@ import Dispatch
/// ### Supporting Types
///
/// - ``AnyDatabaseWriter``
public protocol DatabaseWriter: DatabaseReader {
public protocol DatabaseWriterBase: DatabaseReaderBase {
// MARK: - Writing in Database
@@ -98,7 +98,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`.
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
func writeWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -130,7 +130,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// database access, or the error thrown by `updates`, or
/// `CancellationError` if the task is cancelled.
func writeWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T
/// Executes database operations, and returns their result after they have
@@ -171,7 +171,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`.
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T
func barrierWriteWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) throws -> T
/// Executes database operations, and returns their result after they have
/// finished executing.
@@ -213,7 +213,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// database access, or the error thrown by `updates`, or
/// `CancellationError` if the task is cancelled.
func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T
/// Schedules database operations for execution, and returns immediately.
@@ -256,7 +256,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the barrier access to the database.
func asyncBarrierWriteWithoutTransaction(
_ updates: @escaping @Sendable (Result<Database, Error>) -> Void
_ updates: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
)
/// Schedules database operations for execution, and returns immediately.
@@ -290,7 +290,7 @@ public protocol DatabaseWriter: DatabaseReader {
///
/// - parameter updates: A closure which accesses the database.
func asyncWriteWithoutTransaction(
_ updates: @escaping @Sendable (Database) -> Void
_ updates: @escaping @Sendable (DatabaseBase<API>) -> Void
)
/// Executes database operations, and returns their result after they have
@@ -325,7 +325,7 @@ public protocol DatabaseWriter: DatabaseReader {
///
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`.
func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T
func unsafeReentrantWrite<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T
// MARK: - Reading from Database
@@ -374,7 +374,7 @@ public protocol DatabaseWriter: DatabaseReader {
/// is a `Result` that provides the database connection, or the failure
/// that would prevent establishing the read access to the database.
func spawnConcurrentRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
)
}
@@ -413,7 +413,7 @@ extension DatabaseWriter {
/// would happen while establishing the database access or committing
/// the transaction.
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func write<T>(_ updates: (Database) throws -> T) throws -> T {
public func write<T>(_ updates: (DatabaseBase<API>) throws -> T) throws -> T {
try writeWithoutTransaction { db in
var result: T?
try db.inTransaction {
@@ -461,7 +461,7 @@ extension DatabaseWriter {
/// - parameter updates: A closure which accesses the database.
/// - parameter completion: A closure called with the transaction result.
public func asyncWrite<T>(
_ updates: @escaping @Sendable (Database) throws -> T,
_ updates: @escaping @Sendable (DatabaseBase<API>) throws -> T,
completion: @escaping @Sendable (Database, Result<T, Error>) -> Void
) {
asyncWriteWithoutTransaction { db in
@@ -502,7 +502,7 @@ extension DatabaseWriter {
/// is deallocated).
public func add(
transactionObserver: some TransactionObserver,
extent: Database.TransactionObservationExtent = .observerLifetime)
extent: DatabaseTransactionObservationExtent = .observerLifetime)
{
writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) }
}
@@ -552,7 +552,7 @@ extension DatabaseWriter {
// This method is declared on DatabaseWriter instead of DatabaseReader,
// so that it is not available on DatabaseSnaphot. VACUUM INTO is not
// available inside the transaction that is kept open by DatabaseSnaphot.
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Creates a new database file at the specified path with a minimum
/// amount of disk space.
///
@@ -640,7 +640,7 @@ extension DatabaseWriter {
/// database access, or the error thrown by `updates`, or
/// `CancellationError` if the task is cancelled.
public func write<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await writeWithoutTransaction { db in
var result: T?
@@ -665,7 +665,7 @@ extension DatabaseWriter {
try await writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Creates a new database file at the specified path with a minimum
/// amount of disk space.
///
@@ -733,7 +733,7 @@ extension DatabaseWriter {
/// - parameter updates: A closure which accesses the database.
public func writePublisher<Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
updates: @escaping @Sendable (Database) throws -> Output
updates: @escaping @Sendable (DatabaseBase<API>) throws -> Output
) -> DatabasePublishers.Write<Output> {
OnDemandFuture { fulfill in
self.asyncWrite(updates, completion: { _, result in
@@ -796,7 +796,7 @@ extension DatabaseWriter {
/// - parameter value: A closure which reads from the database.
public func writePublisher<T: Sendable, Output>(
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
updates: @escaping @Sendable (Database) throws -> T,
updates: @escaping @Sendable (DatabaseBase<API>) throws -> T,
thenRead value: @escaping @Sendable (Database, T) throws -> Output
) -> DatabasePublishers.Write<Output> {
OnDemandFuture { fulfill in
@@ -880,40 +880,40 @@ extension AnyDatabaseWriter: DatabaseReader {
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ value: (Database) throws -> T) throws -> T {
public func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
try base.read(value)
}
public func read<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await base.read(value)
}
public func asyncRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
base.asyncRead(value)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
public func unsafeRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
try base.unsafeRead(value)
}
public func unsafeRead<T: Sendable>(
_ value: @escaping @Sendable (Database) throws -> T
_ value: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await base.unsafeRead(value)
}
public func asyncUnsafeRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
base.asyncUnsafeRead(value)
}
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
try base.unsafeReentrantRead(value)
}
@@ -931,45 +931,45 @@ extension AnyDatabaseWriter: DatabaseReader {
extension AnyDatabaseWriter: DatabaseWriter {
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
public func writeWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
try base.writeWithoutTransaction(updates)
}
public func writeWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await base.writeWithoutTransaction(updates)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
public func barrierWriteWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) throws -> T {
try base.barrierWriteWithoutTransaction(updates)
}
public func barrierWriteWithoutTransaction<T: Sendable>(
_ updates: @escaping @Sendable (Database) throws -> T
_ updates: @Sendable (DatabaseBase<API>) throws -> T
) async throws -> T {
try await base.barrierWriteWithoutTransaction(updates)
}
public func asyncBarrierWriteWithoutTransaction(
_ updates: @escaping @Sendable (Result<Database, Error>) -> Void
_ updates: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
base.asyncBarrierWriteWithoutTransaction(updates)
}
public func asyncWriteWithoutTransaction(
_ updates: @escaping @Sendable (Database) -> Void
_ updates: @escaping @Sendable (DatabaseBase<API>) -> Void
) {
base.asyncWriteWithoutTransaction(updates)
}
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
public func unsafeReentrantWrite<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
try base.unsafeReentrantWrite(updates)
}
public func spawnConcurrentRead(
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
) {
base.spawnConcurrentRead(value)
}
+49
View File
@@ -0,0 +1,49 @@
import Dispatch
/// 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
+25 -25
View File
@@ -87,20 +87,20 @@ public protocol FetchRequest<RowDecoder>: SQLSubqueryable, DatabaseRegionConvert
/// - parameter db: A database connection.
/// - parameter singleResult: A hint that a single result row will be
/// consumed.
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
func makePreparedRequest<API>(_ db: DatabaseBase<API>, forSingleResult singleResult: Bool) throws -> PreparedRequestBase<API>
/// Returns the number of rows fetched by the request.
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
func fetchCount(_ db: Database) throws -> Int
func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int
}
extension FetchRequest {
/// Returns the database region that the request feeds from.
///
/// - parameter db: A database connection.
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
public func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion {
try makePreparedRequest(db, forSingleResult: false).statement.databaseRegion
}
}
@@ -123,28 +123,28 @@ typealias WillExecuteSupplementaryRequest = (_ request: AnyFetchRequest<Row>, _
/// - parameter rows: The rows that are modified by the supplementary fetch.
/// - parameter willExecuteSupplementaryRequest: A closure to execute before
/// performing supplementary fetches.
typealias SupplementaryFetch = (
_ db: Database,
typealias SupplementaryFetch<API: SQLiteAPI> = (
_ db: DatabaseBase<API>,
_ rows: [Row],
_ willExecuteSupplementaryRequest: WillExecuteSupplementaryRequest?)
throws -> Void
/// A `PreparedRequest` is a request that is ready to be executed.
public struct PreparedRequest {
public struct PreparedRequestBase<API: SQLiteAPI> {
/// A prepared statement with bound parameters.
public var statement: Statement
public var statement: StatementBase<API>
/// An eventual adapter for rows fetched by the select statement.
public var adapter: (any RowAdapter)?
/// A closure that performs supplementary fetches.
/// Support for eager loading of hasMany associations.
var supplementaryFetch: SupplementaryFetch?
var supplementaryFetch: SupplementaryFetch<API>?
init(
statement: Statement,
statement: StatementBase<API>,
adapter: (any RowAdapter)?,
supplementaryFetch: SupplementaryFetch? = nil)
supplementaryFetch: SupplementaryFetch<API>? = nil)
{
self.statement = statement
self.adapter = adapter
@@ -172,7 +172,7 @@ extension FetchRequest {
/// - parameter adapter: A closure that accepts a database connection and
/// returns a row adapter.
public func adapted(
_ adapter: @escaping @Sendable (Database) throws -> any RowAdapter
_ adapter: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> any RowAdapter
) -> AdaptedFetchRequest<Self> {
AdaptedFetchRequest(self, adapter)
}
@@ -183,11 +183,11 @@ extension FetchRequest {
/// See ``FetchRequest/adapted(_:)``.
public struct AdaptedFetchRequest<Base: FetchRequest> {
let base: Base
let adapter: @Sendable (Database) throws -> any RowAdapter
let adapter: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> any RowAdapter
/// Creates an adapted request from a base request and a closure that builds
/// a row adapter from a database connection.
init(_ base: Base, _ adapter: @escaping @Sendable (Database) throws -> any RowAdapter) {
init(_ base: Base, _ adapter: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> any RowAdapter) {
self.base = base
self.adapter = adapter
}
@@ -202,14 +202,14 @@ extension AdaptedFetchRequest: SQLSubqueryable {
extension AdaptedFetchRequest: FetchRequest {
public typealias RowDecoder = Base.RowDecoder
public func fetchCount(_ db: Database) throws -> Int {
public func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
try base.fetchCount(db)
}
public func makePreparedRequest(
_ db: Database,
public func makePreparedRequest<API>(
_ db: DatabaseBase<API>,
forSingleResult singleResult: Bool = false)
throws -> PreparedRequest
throws -> PreparedRequestBase<API>
{
var preparedRequest = try base.makePreparedRequest(db, forSingleResult: singleResult)
@@ -262,14 +262,14 @@ extension AnyFetchRequest: SQLSubqueryable {
}
extension AnyFetchRequest: FetchRequest {
public func fetchCount(_ db: Database) throws -> Int {
public func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
try request.fetchCount(db)
}
public func makePreparedRequest(
_ db: Database,
public func makePreparedRequest<API>(
_ db: DatabaseBase<API>,
forSingleResult singleResult: Bool = false)
throws -> PreparedRequest
throws -> PreparedRequestBase<API>
{
try request.makePreparedRequest(db, forSingleResult: singleResult)
}
@@ -283,11 +283,11 @@ private class FetchRequestEraser: FetchRequest, @unchecked Sendable {
fatalError("subclass must override")
}
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
func makePreparedRequest<API>(_ db: DatabaseBase<API>, forSingleResult singleResult: Bool) throws -> PreparedRequestBase<API> {
fatalError("subclass must override")
}
func fetchCount(_ db: Database) throws -> Int {
func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
fatalError("subclass must override")
}
}
@@ -303,11 +303,11 @@ private final class ConcreteFetchRequestEraser<Request: FetchRequest>: FetchRequ
request.sqlSubquery
}
override func fetchCount(_ db: Database) throws -> Int {
override func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
try request.fetchCount(db)
}
override func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
override func makePreparedRequest<API>(_ db: DatabaseBase<API>, forSingleResult singleResult: Bool) throws -> PreparedRequestBase<API> {
try request.makePreparedRequest(db, forSingleResult: singleResult)
}
}
+417 -145
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -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``
@@ -217,7 +234,7 @@ public final class Row {
/// The row is implemented on top of StatementRowImpl, which grants *direct*
/// access to the SQLite statement. Iteration of the statement does modify
/// the row.
init(statement: Statement) {
init(statement: StatementBase<some SQLiteAPI>) {
self.statement = statement
self.sqliteStatement = statement.sqliteStatement
self.impl = StatementRowImpl(sqliteStatement: statement.sqliteStatement, statement: statement)
@@ -226,7 +243,7 @@ public final class Row {
/// Creates a row that maps an SQLite statement. Further calls to
/// sqlite3_step() modify the row.
init(sqliteStatement: SQLiteStatement) {
init(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>) {
self.statement = nil
self.sqliteStatement = sqliteStatement
self.impl = SQLiteStatementRowImpl(sqliteStatement: sqliteStatement)
@@ -240,8 +257,8 @@ public final class Row {
/// the values from the SQLite statement so that further iteration of the
/// statement does not modify the row.
convenience init(
copiedFromSQLiteStatement sqliteStatement: SQLiteStatement,
statement: Statement)
copiedFromSQLiteStatement sqliteStatement: SQLiteStatementBase<some SQLiteAPI>,
statement: StatementBase<some SQLiteAPI>)
{
self.init(impl: StatementCopyRowImpl(
sqliteStatement: sqliteStatement,
@@ -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 {
@@ -1488,7 +1736,7 @@ extension Row {
/// - returns: A ``RowCursor`` over fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> RowCursor
@@ -1516,7 +1764,7 @@ extension Row {
/// - returns: An array of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> [Row]
@@ -1545,7 +1793,7 @@ extension Row {
/// - returns: A set of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Set<Row>
@@ -1574,7 +1822,7 @@ extension Row {
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Row?
@@ -1629,7 +1877,7 @@ extension Row {
/// - returns: A ``RowCursor`` over fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -1658,7 +1906,7 @@ extension Row {
/// - returns: An array of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -1687,7 +1935,7 @@ extension Row {
/// - returns: A set of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -1716,7 +1964,7 @@ extension Row {
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -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> = """
@@ -1773,7 +2027,7 @@ extension Row {
/// - request: A fetch request.
/// - returns: A ``RowCursor`` over fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: some FetchRequest) throws -> RowCursor {
public static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> RowCursor {
let request = try request.makePreparedRequest(db, forSingleResult: false)
precondition(request.supplementaryFetch == nil, "Not implemented: fetchCursor with supplementary fetch")
return try fetchCursor(request.statement, adapter: request.adapter)
@@ -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> = """
@@ -1804,7 +2064,7 @@ extension Row {
/// - request: A fetch request.
/// - returns: An array of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Row] {
public static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> [Row] {
let request = try request.makePreparedRequest(db, forSingleResult: false)
let rows = try fetchAll(request.statement, adapter: request.adapter)
try request.supplementaryFetch?(db, rows, nil)
@@ -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> = """
@@ -1836,7 +2102,7 @@ extension Row {
/// - request: A fetch request.
/// - returns: A set of rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Row> {
public static func fetchSet(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> Set<Row> {
let request = try request.makePreparedRequest(db, forSingleResult: false)
if let supplementaryFetch = request.supplementaryFetch {
let rows = try fetchAll(request.statement, adapter: request.adapter)
@@ -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> = """
@@ -1872,7 +2144,7 @@ extension Row {
/// - request: A fetch request.
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Row? {
public static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> Row? {
let request = try request.makePreparedRequest(db, forSingleResult: true)
guard let row = try fetchOne(request.statement, adapter: request.adapter) else {
return nil
@@ -1921,7 +2193,7 @@ extension FetchRequest<Row> {
/// - parameter db: A database connection.
/// - returns: A ``RowCursor`` over fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> RowCursor {
public func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> RowCursor {
try Row.fetchCursor(db, self)
}
@@ -1942,7 +2214,7 @@ extension FetchRequest<Row> {
/// - parameter db: A database connection.
/// - returns: An array of fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [Row] {
public func fetchAll(_ db: DatabaseBase<some SQLiteAPI>) throws -> [Row] {
try Row.fetchAll(db, self)
}
@@ -1963,7 +2235,7 @@ extension FetchRequest<Row> {
/// - parameter db: A database connection.
/// - returns: A set of fetched rows.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<Row> {
public func fetchSet(_ db: DatabaseBase<some SQLiteAPI>) throws -> Set<Row> {
try Row.fetchSet(db, self)
}
@@ -1984,7 +2256,7 @@ extension FetchRequest<Row> {
/// - parameter db: A database connection.
/// - returns: An optional row.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> Row? {
public func fetchOne(_ db: DatabaseBase<some SQLiteAPI>) throws -> Row? {
try Row.fetchOne(db, self)
}
}
+43 -24
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
/// A key that is used to decode a value in a row
@usableFromInline
@@ -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] = []
+3 -3
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,
@@ -181,7 +181,7 @@ public struct SQL: Sendable {
///
/// - parameter db: A database connection.
/// - returns: A tuple made of a raw SQL string, and statement arguments.
public func build(_ db: Database) throws -> (sql: String, arguments: StatementArguments) {
public func build(_ db: DatabaseBase<some SQLiteAPI>) throws -> (sql: String, arguments: StatementArguments) {
let context = SQLGenerationContext(db)
let sql = try self.sql(context)
return (sql: sql, arguments: context.arguments)
@@ -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) })
}
}
+4 -4
View File
@@ -191,14 +191,14 @@ extension SQLRequest: FetchRequest {
.literal(sqlLiteral)
}
public func fetchCount(_ db: Database) throws -> Int {
public func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
try SQLRequest<Int>("SELECT COUNT(*) FROM (\(self))").fetchOne(db)!
}
public func makePreparedRequest(
_ db: Database,
public func makePreparedRequest<API>(
_ db: DatabaseBase<API>,
forSingleResult singleResult: Bool = false)
throws -> PreparedRequest
throws -> PreparedRequestBase<API>
{
let context = SQLGenerationContext(db)
let sql = try sqlLiteral.sql(context)
+20
View File
@@ -0,0 +1,20 @@
public protocol SQLiteAPI {
static var SQLITE_NULL: CInt { get }
static var SQLITE_OK: CInt { get }
static func sqlite3_bind_double(_: OpaquePointer?, _: CInt, _: CDouble) -> CInt
static func sqlite3_bind_int64(_: OpaquePointer?, _: CInt, _: Int64) -> CInt
static func sqlite3_bind_null(_: OpaquePointer?, _: CInt) -> CInt
static func sqlite3_bind_text(_: OpaquePointer?, _: CInt, _: UnsafePointer<CChar>?, _: CInt, _: (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt
static func sqlite3_column_double(_: OpaquePointer?, _ iCol: CInt) -> Double
static func sqlite3_column_int64(_: OpaquePointer?, _ iCol: CInt) -> Int64
static func sqlite3_column_text(_: OpaquePointer?, _ iCol: CInt) -> UnsafePointer<CChar>?
static func sqlite3_column_type(_: OpaquePointer?, _ iCol: CInt) -> CInt
@discardableResult static func sqlite3_commit_hook(_: OpaquePointer?, _: (@convention(c) (UnsafeMutableRawPointer?) -> Int32)?, _: UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer?
@discardableResult static func sqlite3_rollback_hook(_: OpaquePointer?, _: (@convention(c) (UnsafeMutableRawPointer?) -> Void)?, _: UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer?
@discardableResult static func sqlite3_update_hook(_: OpaquePointer?, _: (@convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer<CChar>?, UnsafePointer<CChar>?, Int64) -> Void)?, _: UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer?
}
public typealias sqlite3_destructor_type = @convention(c) (UnsafeMutableRawPointer?) -> Void
+3 -3
View File
@@ -59,7 +59,7 @@ final class SchedulingWatchdog: @unchecked Sendable {
}
static func preconditionValidQueue(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
_ message: @autoclosure() -> String = "Database was not used on the correct thread.",
file: StaticString = #file,
line: UInt = #line)
@@ -69,11 +69,11 @@ final class SchedulingWatchdog: @unchecked Sendable {
/// Returns whether the database argument can be used in the current
/// dispatch queue.
static func allows(_ db: Database) -> Bool {
static func allows(_ db: DatabaseBase<some SQLiteAPI>) -> Bool {
current?.allows(db) ?? false
}
func allows(_ db: Database) -> Bool {
func allows(_ db: DatabaseBase<some SQLiteAPI>) -> Bool {
allowedDatabases.contains { $0 === db }
}
+27 -125
View File
@@ -1,9 +1,12 @@
import Foundation
/// A class that serializes accesses to an SQLite connection.
final class SerializedDatabase {
final class SerializedDatabaseBase<API: SQLiteAPI> {
/// The database connection
private let db: Database
private let db: DatabaseBase<API>
/// The actor that performs asynchronous accesses
private let actor: DispatchQueueActor
/// 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 {
@@ -87,7 +92,7 @@ final class SerializedDatabase {
/// - parameter allowingLongLivedTransaction: When true, the
/// ``Configuration/allowsUnsafeTransactions`` configuration flag is
/// ignored until this method is called again with false.
func sync<T>(allowingLongLivedTransaction: Bool, _ body: (Database) throws -> T) rethrows -> T {
func sync<T>(allowingLongLivedTransaction: Bool, _ body: (DatabaseBase<API>) throws -> T) rethrows -> T {
try sync { db in
self.allowsUnsafeTransactions = allowingLongLivedTransaction
return try body(db)
@@ -98,7 +103,7 @@ final class SerializedDatabase {
/// have finished executing.
///
/// This method is not reentrant.
func sync<T>(_ block: (Database) throws -> T) rethrows -> T {
func sync<T>(_ block: (DatabaseBase<API>) throws -> T) rethrows -> T {
// Three different cases:
//
// 1. A database is invoked from some queue like the main queue:
@@ -148,7 +153,7 @@ final class SerializedDatabase {
/// - parameter allowingLongLivedTransaction: When true, the
/// ``Configuration/allowsUnsafeTransactions`` configuration flag is
/// ignored until this method is called again with false.
func reentrantSync<T>(allowingLongLivedTransaction: Bool, _ body: (Database) throws -> T) rethrows -> T {
func reentrantSync<T>(allowingLongLivedTransaction: Bool, _ body: (DatabaseBase<API>) throws -> T) rethrows -> T {
try reentrantSync { db in
self.allowsUnsafeTransactions = allowingLongLivedTransaction
return try body(db)
@@ -159,7 +164,7 @@ final class SerializedDatabase {
/// have finished executing.
///
/// This method is reentrant.
func reentrantSync<T>(_ block: (Database) throws -> T) rethrows -> T {
func reentrantSync<T>(_ block: (DatabaseBase<API>) throws -> T) rethrows -> T {
// Three different cases:
//
// 1. A database is invoked from some queue like the main queue:
@@ -223,7 +228,7 @@ final class SerializedDatabase {
}
/// Schedules database operations for execution, and returns immediately.
func async(_ block: @escaping @Sendable (Database) -> Void) {
func async(_ block: @escaping @Sendable (DatabaseBase<API>) -> Void) {
queue.async {
block(self.db)
self.preconditionNoUnsafeTransactionLeft(self.db)
@@ -238,27 +243,29 @@ final class SerializedDatabase {
/// Executes the block in the current queue.
///
/// - precondition: the current dispatch queue is valid.
func execute<T>(_ block: (Database) throws -> T) rethrows -> T {
func execute<T>(_ block: (DatabaseBase<API>) throws -> T) rethrows -> T {
preconditionValidQueue()
return try block(db)
}
/// Asynchrously executes the block.
func execute<T: Sendable>(
_ block: @escaping @Sendable (Database) throws -> T
_ block: @Sendable (DatabaseBase<API>) 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?() }
}
}
@@ -288,7 +295,7 @@ final class SerializedDatabase {
/// Fatal error if a transaction has been left opened.
private func preconditionNoUnsafeTransactionLeft(
_ db: Database,
_ db: DatabaseBase<API>,
_ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access",
file: StaticString = #file,
line: UInt = #line)
@@ -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()
}
}
}
}
+24 -14
View File
@@ -1,16 +1,22 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
/// A raw SQLite statement, suitable for the SQLite C API.
public typealias SQLiteStatement = OpaquePointer
//public typealias SQLiteStatement = OpaquePointer
public struct SQLiteStatementBase<API: SQLiteAPI> {
public let rawValue: OpaquePointer
}
extension String {
/// SQL statements are separated by semicolons and white spaces.
@@ -34,7 +40,7 @@ extension String {
}
}
public final class Statement {
public final class StatementBase<API: SQLiteAPI> {
enum TransactionEffect: Equatable {
case beginTransaction
case commitTransaction
@@ -45,7 +51,7 @@ public final class Statement {
}
/// The raw SQLite statement, suitable for the SQLite C API.
public let sqliteStatement: SQLiteStatement
public let sqliteStatement: SQLiteStatementBase<API>
/// The SQL query.
public var sql: String {
@@ -92,6 +98,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 +147,7 @@ public final class Statement {
let authorizer = database.authorizer
authorizer.reset()
var sqliteStatement: SQLiteStatement? = nil
var sqliteStatement: SQLiteStatement?
let code = sqlite3_prepare_v3(
database.sqliteConnection, statementStart, -1, prepFlags,
&sqliteStatement, statementEnd)
@@ -160,6 +169,7 @@ public final class Statement {
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
self.transactionEffect = authorizer.transactionEffect
self.authorizerEventKinds = authorizer.databaseEventKinds
self.isQueryOnlyPragma = authorizer.isQueryOnlyPragma
}
deinit {
@@ -832,11 +842,11 @@ public protocol StatementBinding {
/// - parameter sqliteStatement: An SQLite statement.
/// - parameter index: 1-based index to statement arguments.
/// - returns: the code returned by the `sqlite3_bind_xxx` function.
func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt
func bind(to sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, at index: CInt) -> CInt
}
/// Helper function for `withBinding(to:at:do:)` methods.
func checkBindingSuccess(code: CInt, sqliteStatement: SQLiteStatement) throws {
func checkBindingSuccess(code: CInt, sqliteStatement: SQLiteStatementBase<some SQLiteAPI>) throws {
if code == SQLITE_OK { return }
let message = String(cString: sqlite3_errmsg(sqlite3_db_handle(sqliteStatement)))
let sql = String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
+20 -8
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
#if canImport(string_h)
import string_h
@@ -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
}
+109 -47
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
/// A type that can decode itself from the low-level C interface to
/// SQLite results.
@@ -89,10 +92,10 @@ public protocol StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
/// - returns: A decoded value, or, if decoding is impossible, nil.
static func fromStatement(
_ sqliteStatement: SQLiteStatement,
atUncheckedIndex index: CInt)
-> Self?
static func fromStatement<API>(
_ sqliteStatement: SQLiteStatementBase<API>,
atUncheckedIndex index: CInt
) -> Self?
/// Creates an instance from a raw SQLite statement pointer, if possible.
///
@@ -104,7 +107,7 @@ public protocol StatementColumnConvertible {
///
/// ```swift
/// extension Int64: StatementColumnConvertible {
/// public init(sqliteStatement: SQLiteStatement, index: CInt) {
/// public init(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
/// self = sqlite3_column_int64(sqliteStatement, index)
/// }
/// }
@@ -117,7 +120,7 @@ public protocol StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
init?(sqliteStatement: SQLiteStatement, index: CInt)
init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt)
}
extension StatementColumnConvertible {
@@ -125,7 +128,10 @@ extension StatementColumnConvertible {
/// Default implementation fails on decoding NULL.
@inline(__always)
@inlinable
public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt) -> Self? {
public static func fromStatement<API>(
_ sqliteStatement: SQLiteStatementBase<API>,
atUncheckedIndex index: CInt
) -> Self? {
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
return nil
}
@@ -295,7 +301,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: A ``FastDatabaseValueCursor`` over fetched values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> FastDatabaseValueCursor<Self>
@@ -326,7 +332,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> [Self]
@@ -360,7 +366,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Self?
@@ -398,7 +404,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
_ statement: Statement,
_ statement: StatementBase<some SQLiteAPI>,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Set<Self>
@@ -443,7 +449,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: A ``FastDatabaseValueCursor`` over fetched values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -475,7 +481,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -510,7 +516,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -544,7 +550,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
@@ -563,13 +569,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> = """
@@ -596,7 +609,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - request: A fetch request.
/// - returns: A ``FastDatabaseValueCursor`` over fetched values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: some FetchRequest)
public static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest)
throws -> FastDatabaseValueCursor<Self>
{
let request = try request.makePreparedRequest(db, forSingleResult: false)
@@ -608,13 +621,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> = """
@@ -632,7 +652,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - request: A fetch request.
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
public static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> [Self] {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchAll(request.statement, adapter: request.adapter)
}
@@ -647,13 +667,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> = """
@@ -669,7 +696,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - request: A fetch request.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
public static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> Self? {
let request = try request.makePreparedRequest(db, forSingleResult: true)
return try fetchOne(request.statement, adapter: request.adapter)
}
@@ -681,13 +708,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> = """
@@ -705,7 +739,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
/// - request: A fetch request.
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
public static func fetchSet(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> Set<Self> {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchSet(request.statement, adapter: request.adapter)
}
@@ -720,13 +754,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> = """
@@ -751,7 +792,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// - parameter db: A database connection.
/// - returns: A ``FastDatabaseValueCursor`` over fetched values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> FastDatabaseValueCursor<RowDecoder> {
public func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> FastDatabaseValueCursor<RowDecoder> {
try RowDecoder.fetchCursor(db, self)
}
@@ -760,13 +801,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> = """
@@ -782,7 +830,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
public func fetchAll(_ db: DatabaseBase<some SQLiteAPI>) throws -> [RowDecoder] {
try RowDecoder.fetchAll(db, self)
}
@@ -796,13 +844,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> = """
@@ -816,7 +871,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
public func fetchOne(_ db: DatabaseBase<some SQLiteAPI>) throws -> RowDecoder? {
try RowDecoder.fetchOne(db, self)
}
}
@@ -827,13 +882,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> = """
@@ -849,7 +911,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// - parameter db: A database connection.
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
public func fetchSet(_ db: DatabaseBase<some SQLiteAPI>) throws -> Set<RowDecoder> {
try RowDecoder.fetchSet(db, self)
}
}
+13 -10
View File
@@ -1,17 +1,20 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
/// Data is convertible to and from DatabaseValue.
extension Data: DatabaseValueConvertible, StatementColumnConvertible {
public init(sqliteStatement: SQLiteStatement, index: CInt) {
public init(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
let count = Int(sqlite3_column_bytes(sqliteStatement, index))
self.init(bytes: bytes, count: count) // copy bytes
@@ -46,7 +49,7 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
}
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
withUnsafeBytes {
sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
}
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -78,7 +81,7 @@ extension DatabaseDateComponents: StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
guard let cString = sqlite3_column_text(sqliteStatement, index) else {
return nil
}
+12 -9
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -133,7 +136,7 @@ extension Date: StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_INTEGER, SQLITE_FLOAT:
self.init(timeIntervalSince1970: sqlite3_column_double(sqliteStatement, index))
+12 -9
View File
@@ -1,12 +1,15 @@
#if !os(Linux)
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -47,7 +50,7 @@ extension Decimal: DatabaseValueConvertible {
extension Decimal: StatementColumnConvertible {
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_INTEGER:
self.init(sqlite3_column_int64(sqliteStatement, index))
+12 -9
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -78,7 +81,7 @@ extension UUID: DatabaseValueConvertible {
extension UUID: StatementColumnConvertible {
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_TEXT:
let string = String(cString: sqlite3_column_text(sqliteStatement, index)!)
@@ -20,7 +20,7 @@ extension SQLExpressible where Self: RawRepresentable, Self.RawValue: SQLExpress
}
extension StatementBinding where Self: RawRepresentable, Self.RawValue: StatementBinding {
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
public func bind(to sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, at index: CInt) -> CInt {
rawValue.bind(to: sqliteStatement, at: index)
}
}
@@ -41,7 +41,7 @@ extension StatementBinding where Self: RawRepresentable, Self.RawValue: Statemen
extension StatementColumnConvertible where Self: RawRepresentable, Self.RawValue: StatementColumnConvertible {
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
guard let rawValue = RawValue(sqliteStatement: sqliteStatement, index: index) else {
return nil
}
@@ -1,17 +1,20 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
extension Optional: StatementBinding where Wrapped: StatementBinding {
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
switch self {
case .none:
return sqlite3_bind_null(sqliteStatement, index)
return API.sqlite3_bind_null(sqliteStatement.rawValue, index)
case let .some(value):
return value.bind(to: sqliteStatement, at: index)
}
@@ -84,11 +87,11 @@ extension Optional: DatabaseValueConvertible where Wrapped: DatabaseValueConvert
extension Optional: StatementColumnConvertible where Wrapped: StatementColumnConvertible {
@inline(__always)
@inlinable
public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt) -> Self? {
public static func fromStatement<API>(_ sqliteStatement: SQLiteStatementBase<API>, atUncheckedIndex index: CInt) -> Self? {
if let value = Wrapped.fromStatement(sqliteStatement, atUncheckedIndex: index) {
// Valid value
return value
} else if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
} else if API.sqlite3_column_type(sqliteStatement.rawValue, index) == API.SQLITE_NULL {
// NULL
return .some(.none)
} else {
@@ -97,7 +100,7 @@ extension Optional: StatementColumnConvertible where Wrapped: StatementColumnCon
}
}
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
guard let value = Wrapped(sqliteStatement: sqliteStatement, index: index) else {
return nil
}
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
// MARK: - Value Types
@@ -17,8 +20,8 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: CInt) {
self = sqlite3_column_int64(sqliteStatement, index) != 0
public init<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
self = API.sqlite3_column_int64(sqliteStatement.rawValue, index) != 0
}
/// Returns an INTEGER database value.
@@ -99,8 +102,8 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
}
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, self ? 1 : 0)
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, self ? 1 : 0)
}
}
@@ -114,8 +117,8 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
guard let v = Int(exactly: int64) else { return nil }
self = v
}
@@ -138,8 +141,8 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { Int(exactly: $0) }
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
}
}
@@ -153,8 +156,8 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
guard let v = Int8(exactly: int64) else { return nil }
self = v
}
@@ -177,8 +180,8 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { Int8(exactly: $0) }
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
}
}
@@ -192,8 +195,8 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
guard let v = Int16(exactly: int64) else { return nil }
self = v
}
@@ -216,8 +219,8 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { Int16(exactly: $0) }
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
}
}
@@ -231,8 +234,8 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
guard let v = Int32(exactly: int64) else { return nil }
self = v
}
@@ -255,8 +258,8 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { Int32(exactly: $0) }
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
}
}
@@ -268,8 +271,8 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: CInt) {
self = sqlite3_column_int64(sqliteStatement, index)
public init<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
self = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
}
/// Returns an INTEGER database value.
@@ -298,8 +301,8 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
}
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, self)
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, self)
}
}
@@ -313,8 +316,8 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
guard let v = UInt(exactly: int64) else { return nil }
self = v
}
@@ -337,8 +340,8 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { UInt(exactly: $0) }
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
}
}
@@ -352,8 +355,8 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
guard let v = UInt8(exactly: int64) else { return nil }
self = v
}
@@ -376,8 +379,8 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { UInt8(exactly: $0) }
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
}
}
@@ -391,8 +394,8 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
guard let v = UInt16(exactly: int64) else { return nil }
self = v
}
@@ -415,8 +418,8 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { UInt16(exactly: $0) }
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
}
}
@@ -430,8 +433,8 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
guard let v = UInt32(exactly: int64) else { return nil }
self = v
}
@@ -454,8 +457,8 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { UInt32(exactly: $0) }
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
}
}
@@ -469,8 +472,8 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
/// - index: The column index.
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
guard let v = UInt64(exactly: int64) else { return nil }
self = v
}
@@ -493,8 +496,8 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
Int64.fromDatabaseValue(dbValue).flatMap { UInt64(exactly: $0) }
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
}
}
@@ -506,8 +509,8 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: CInt) {
self = sqlite3_column_double(sqliteStatement, index)
public init<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
self = API.sqlite3_column_double(sqliteStatement.rawValue, index)
}
/// Returns a REAL database value.
@@ -533,8 +536,8 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
}
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_double(sqliteStatement, index, self)
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_double(sqliteStatement.rawValue, index, self)
}
}
@@ -546,8 +549,8 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: CInt) {
self = Float(sqlite3_column_double(sqliteStatement, index))
public init<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
self = Float(API.sqlite3_column_double(sqliteStatement.rawValue, index))
}
/// Returns a REAL database value.
@@ -573,8 +576,8 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
}
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_double(sqliteStatement, index, Double(self))
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_double(sqliteStatement.rawValue, index, Double(self))
}
}
@@ -586,8 +589,8 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init(sqliteStatement: SQLiteStatement, index: CInt) {
self = String(cString: sqlite3_column_text(sqliteStatement, index)!)
public init<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
self = String(cString: API.sqlite3_column_text(sqliteStatement.rawValue, index)!)
}
/// Returns a TEXT database value.
@@ -616,8 +619,8 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
}
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_text(sqliteStatement, index, self, -1, SQLITE_TRANSIENT)
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
API.sqlite3_bind_text(sqliteStatement.rawValue, index, self, -1, SQLITE_TRANSIENT)
}
/// Calls the given closure after binding a statement argument.
@@ -627,9 +630,9 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameter sqliteStatement: An SQLite statement.
/// - parameter index: 1-based index to statement arguments.
/// - parameter body: The closure to execute when argument is bound.
func withBinding<T>(to sqliteStatement: SQLiteStatement, at index: CInt, do body: () throws -> T) throws -> T {
func withBinding<API, T>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt, do body: () throws -> T) throws -> T {
try withCString {
let code = sqlite3_bind_text(sqliteStatement, index, $0, -1, nil /* SQLITE_STATIC */)
let code = API.sqlite3_bind_text(sqliteStatement.rawValue, index, $0, -1, nil /* SQLITE_STATIC */)
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
return try body()
}
@@ -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 =
+28 -24
View File
@@ -10,7 +10,9 @@ import Foundation
///
/// - ``DefaultTransactionClock``
/// - ``CustomTransactionClock``
public protocol TransactionClock: Sendable {
public protocol TransactionClock<API>: Sendable {
associatedtype API: SQLiteAPI
/// Returns the date of the current transaction.
///
/// This function is called whenever a transaction starts - precisely
@@ -20,31 +22,33 @@ public protocol TransactionClock: Sendable {
/// called, and the database connection is not in a transaction.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/get_autocommit.html>
func now(_ db: Database) throws -> Date
func now(_ db: DatabaseBase<API>) throws -> Date
}
extension TransactionClock where Self == DefaultTransactionClock {
/// Returns the default clock.
public static var `default`: Self { DefaultTransactionClock() }
}
#warning("TODO: expose a version with default api")
//extension TransactionClock where Self == DefaultTransactionClock {
// /// Returns the default clock.
// public static var `default`: Self { DefaultTransactionClock() }
//}
extension TransactionClock where Self == CustomTransactionClock {
/// Returns a custom clock.
///
/// The provided closure is called whenever a transaction starts - precisely
/// speaking, whenever the database connection leaves the auto-commit mode.
///
/// It is also called when the ``Database/transactionDate`` property is
/// called, and the database connection is not in a transaction.
public static func custom(_ now: @escaping @Sendable (Database) throws -> Date) -> Self {
CustomTransactionClock(now)
}
}
#warning("TODO: expose a version with default api")
//extension TransactionClock where Self == CustomTransactionClock {
// /// Returns a custom clock.
// ///
// /// The provided closure is called whenever a transaction starts - precisely
// /// speaking, whenever the database connection leaves the auto-commit mode.
// ///
// /// It is also called when the ``Database/transactionDate`` property is
// /// called, and the database connection is not in a transaction.
// public static func custom(_ now: @escaping @Sendable (Database) throws -> Date) -> Self {
// CustomTransactionClock(now)
// }
//}
/// The default transaction clock.
public struct DefaultTransactionClock: TransactionClock {
public struct DefaultTransactionClock<API: SQLiteAPI>: TransactionClock {
/// Returns the start date of the current transaction.
public func now(_ db: Database) throws -> Date {
public func now(_ db: DatabaseBase<API>) throws -> Date {
// An opportunity to fetch transaction time from the database when
// SQLite supports the feature.
Date()
@@ -52,14 +56,14 @@ public struct DefaultTransactionClock: TransactionClock {
}
/// A custom transaction clock.
public struct CustomTransactionClock: TransactionClock {
let _now: @Sendable (Database) throws -> Date
public struct CustomTransactionClock<API: SQLiteAPI>: TransactionClock {
let _now: @Sendable (DatabaseBase<API>) throws -> Date
public init(_ now: @escaping @Sendable (Database) throws -> Date) {
public init(_ now: @escaping @Sendable (DatabaseBase<API>) throws -> Date) {
self._now = now
}
public func now(_ db: Database) throws -> Date {
public func now(_ db: DatabaseBase<API>) throws -> Date {
try _now(db)
}
}
+112 -95
View File
@@ -1,13 +1,16 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
extension Database {
extension DatabaseBase {
// MARK: - Database Observation
@@ -30,8 +33,8 @@ extension Database {
/// the observer lifetime (observation lasts until observer
/// is deallocated).
public func add(
transactionObserver: some TransactionObserver,
extent: TransactionObservationExtent = .observerLifetime)
transactionObserver: some TransactionObserverBase<API>,
extent: DatabaseTransactionObservationExtent = .observerLifetime)
{
SchedulingWatchdog.preconditionValidQueue(self)
guard let observationBroker else { return }
@@ -54,7 +57,7 @@ extension Database {
/// db.remove(transactionObserver: myObserver)
/// }
/// ```
public func remove(transactionObserver: some TransactionObserver) {
public func remove(transactionObserver: some TransactionObserverBase<API>) {
SchedulingWatchdog.preconditionValidQueue(self)
guard let observationBroker else { return }
@@ -79,7 +82,7 @@ extension Database {
/// ```swift
/// /// Inserts a region in the database, and start monitoring upon
/// /// successful insertion.
/// func startMonitoring(_ db: Database, region: CLRegion) throws {
/// func startMonitoring(_ db: DatabaseBase<some SQLiteAPI>, region: CLRegion) throws {
/// // Make sure database is inside a transaction
/// try db.inSavepoint {
///
@@ -110,34 +113,9 @@ extension Database {
/// - parameter onCommit: A closure executed on transaction commit.
/// - parameter onRollback: A closure executed on transaction rollback.
public func afterNextTransaction(
onCommit: @escaping @Sendable (Database) -> Void,
onRollback: @escaping @Sendable (Database) -> Void = { _ in })
onCommit: @escaping @Sendable (DatabaseBase<API>) -> Void,
onRollback: @escaping @Sendable (DatabaseBase<API>) -> Void = { _ in })
{
class TransactionHandler: TransactionObserver {
let onCommit: @Sendable (Database) -> Void
let onRollback: @Sendable (Database) -> Void
init(
onCommit: @escaping @Sendable (Database) -> Void,
onRollback: @escaping @Sendable (Database) -> Void
) {
self.onCommit = onCommit
self.onRollback = onRollback
}
// Ignore changes
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false }
func databaseDidChange(with event: DatabaseEvent) { }
func databaseDidCommit(_ db: Database) {
onCommit(db)
}
func databaseDidRollback(_ db: Database) {
onRollback(db)
}
}
// We don't notify read-only transactions to transaction observers
GRDBPrecondition(!isReadOnly, "Read-only transactions are not notified")
@@ -145,16 +123,42 @@ extension Database {
transactionObserver: TransactionHandler(onCommit: onCommit, onRollback: onRollback),
extent: .nextTransaction)
}
/// The extent of the observation performed by a ``TransactionObserver``.
public enum TransactionObservationExtent: Sendable {
/// Observation lasts until observer is deallocated.
case observerLifetime
/// Observation lasts until the next transaction.
case nextTransaction
/// Observation lasts until the database is closed.
case databaseLifetime
}
fileprivate class TransactionHandler<API: SQLiteAPI>: TransactionObserverBase {
let onCommit: @Sendable (DatabaseBase<API>) -> Void
let onRollback: @Sendable (DatabaseBase<API>) -> Void
init(
onCommit: @escaping @Sendable (DatabaseBase<API>) -> Void,
onRollback: @escaping @Sendable (DatabaseBase<API>) -> Void
) {
self.onCommit = onCommit
self.onRollback = onRollback
}
// Ignore changes
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false }
func databaseDidChange(with event: DatabaseEvent) { }
func databaseDidCommit(_ db: DatabaseBase<API>) {
onCommit(db)
}
func databaseDidRollback(_ db: DatabaseBase<API>) {
onRollback(db)
}
}
#warning("TODO: export as Database.TransactionObservationExtent")
/// The extent of the observation performed by a ``TransactionObserver``.
public enum DatabaseTransactionObservationExtent: Sendable {
/// Observation lasts until observer is deallocated.
case observerLifetime
/// Observation lasts until the next transaction.
case nextTransaction
/// Observation lasts until the database is closed.
case databaseLifetime
}
// MARK: - DatabaseObservationBroker
@@ -167,8 +171,8 @@ extension Database {
/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
/// func databaseDidChange(with event: DatabaseEvent)
/// func databaseWillCommit() throws
/// func databaseDidCommit(_ db: Database)
/// func databaseDidRollback(_ db: Database)
/// func databaseDidCommit(_ db: DatabaseBase<some SQLiteAPI>)
/// func databaseDidRollback(_ db: DatabaseBase<some SQLiteAPI>)
/// }
///
/// First observer is added, and a transaction is started. At this point,
@@ -241,8 +245,8 @@ extension Database {
///
/// After the statement *has been executed*, the broker calls
/// observer.databaseDidCommit().
class DatabaseObservationBroker {
private unowned let database: Database
class DatabaseObservationBroker<API: SQLiteAPI> {
private unowned let database: DatabaseBase<API>
/// The savepoint stack allows us to hold database event notifications until
/// all savepoints are released. The goal is to only tell transaction
@@ -255,10 +259,10 @@ class DatabaseObservationBroker {
private var transactionCompletion = TransactionCompletion.none
/// The registered transaction observers.
private var transactionObservations: [TransactionObservation] = []
private var transactionObservations: [TransactionObservation<API>] = []
/// The observers for an individual statement execution.
private var statementObservations: [StatementObservation] = [] {
private var statementObservations: [StatementObservation<API>] = [] {
didSet {
let isEmpty = statementObservations.isEmpty
if isEmpty != oldValue.isEmpty {
@@ -272,22 +276,22 @@ class DatabaseObservationBroker {
}
}
init(_ database: Database) {
init(_ database: DatabaseBase<API>) {
self.database = database
}
// MARK: - Transaction observers
func add(transactionObserver: some TransactionObserver, extent: Database.TransactionObservationExtent) {
func add(transactionObserver: some TransactionObserverBase<API>, extent: DatabaseTransactionObservationExtent) {
transactionObservations.append(TransactionObservation(observer: transactionObserver, extent: extent))
}
func remove(transactionObserver: some TransactionObserver) {
func remove(transactionObserver: some TransactionObserverBase<API>) {
transactionObservations.removeFirst { $0.isWrapping(transactionObserver) }
}
/// Called from ``TransactionObserver/stopObservingDatabaseChangesUntilNextTransaction()``.
func disableUntilNextTransaction(transactionObserver: some TransactionObserver) {
func disableUntilNextTransaction(transactionObserver: some TransactionObserverBase<API>) {
if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver) }) {
observation.isEnabled = false
statementObservations.removeFirst { $0.transactionObservation === observation }
@@ -319,7 +323,7 @@ class DatabaseObservationBroker {
}
/// Prepares observation of changes that are about to be performed by the statement.
func statementWillExecute(_ statement: Statement) {
func statementWillExecute(_ statement: StatementBase<API>) {
if !database.isReadOnly && !transactionObservations.isEmpty {
// As statement executes, it may trigger database changes that will
// be notified to transaction observers. As a consequence, observers
@@ -395,7 +399,7 @@ class DatabaseObservationBroker {
/// May throw the user-provided cancelled commit error, if a transaction
/// observer has cancelled a transaction.
func statementDidFail(_ statement: Statement) throws {
func statementDidFail(_ statement: StatementBase<API>) throws {
// Undo statementWillExecute
statementObservations = []
SchedulingWatchdog.current!.databaseObservationBroker = nil
@@ -422,7 +426,7 @@ class DatabaseObservationBroker {
/// May throw the user-provided cancelled commit error, if the statement
/// commits an empty transaction, and a transaction observer cancels this
/// empty transaction.
func statementDidExecute(_ statement: Statement) throws {
func statementDidExecute(_ statement: StatementBase<API>) throws {
// Undo statementWillExecute
if transactionObservations.isEmpty == false {
statementObservations = []
@@ -549,8 +553,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 +621,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()
@@ -699,7 +712,7 @@ class DatabaseObservationBroker {
func installCommitAndRollbackHooks() {
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_commit_hook(database.sqliteConnection, { brokerPointer in
API.sqlite3_commit_hook(database.sqliteConnection, { brokerPointer in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
do {
try broker.databaseWillCommit()
@@ -713,7 +726,7 @@ class DatabaseObservationBroker {
}
}, brokerPointer)
sqlite3_rollback_hook(database.sqliteConnection, { brokerPointer in
API.sqlite3_rollback_hook(database.sqliteConnection, { brokerPointer in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
switch broker.transactionCompletion {
case .cancelledCommit:
@@ -729,7 +742,7 @@ class DatabaseObservationBroker {
private func installUpdateHook() {
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_update_hook(
API.sqlite3_update_hook(
database.sqliteConnection,
{ (brokerPointer, updateKind, databaseNameCString, tableNameCString, rowID) in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
@@ -762,7 +775,7 @@ class DatabaseObservationBroker {
}
private func uninstallUpdateHook() {
sqlite3_update_hook(database.sqliteConnection, nil, nil)
API.sqlite3_update_hook(database.sqliteConnection, nil, nil)
#if SQLITE_ENABLE_PREUPDATE_HOOK
sqlite3_preupdate_hook(database.sqliteConnection, nil, nil)
#endif
@@ -788,7 +801,8 @@ class DatabaseObservationBroker {
// MARK: - TransactionObserver
public protocol TransactionObserver: AnyObject {
public protocol TransactionObserverBase<API>: AnyObject {
associatedtype API: SQLiteAPI
/// Returns whether specific kinds of database changes should be notified
/// to the observer.
@@ -852,10 +866,10 @@ public protocol TransactionObserver: AnyObject {
func databaseWillCommit() throws
/// Called when a transaction has been committed on disk.
func databaseDidCommit(_ db: Database)
func databaseDidCommit(_ db: DatabaseBase<API>)
/// Called when a transaction has been rollbacked.
func databaseDidRollback(_ db: Database)
func databaseDidRollback(_ db: DatabaseBase<API>)
#if SQLITE_ENABLE_PREUPDATE_HOOK
/// Called when the database is changed by an insert, update, or
@@ -889,7 +903,7 @@ public protocol TransactionObserver: AnyObject {
#endif
}
extension TransactionObserver {
extension TransactionObserverBase {
/// The default implementation does nothing.
public func databaseWillCommit() throws { }
@@ -951,22 +965,25 @@ extension TransactionObserver {
// MARK: - TransactionObservation
/// This class manages the observation extent of a transaction observer
final class TransactionObservation {
let extent: Database.TransactionObservationExtent
final class TransactionObservation<API: SQLiteAPI> {
let extent: DatabaseTransactionObservationExtent
/// A disabled observation is not interested in individual database changes.
/// It is still interested in transactions commits & rollbacks.
var isEnabled = true
private weak var weakObserver: (any TransactionObserver)?
private var strongObserver: (any TransactionObserver)?
private var observer: (any TransactionObserver)? { strongObserver ?? weakObserver }
private weak var weakObserver: (any TransactionObserverBase<API>)?
private var strongObserver: (any TransactionObserverBase<API>)?
private var observer: (any TransactionObserverBase<API>)? {
if let strongObserver { return strongObserver }
return weakObserver
}
fileprivate var isObserving: Bool {
observer != nil
}
init(observer: some TransactionObserver, extent: Database.TransactionObservationExtent) {
init(observer: some TransactionObserverBase<API>, extent: DatabaseTransactionObservationExtent) {
self.extent = extent
switch extent {
case .observerLifetime:
@@ -979,7 +996,7 @@ final class TransactionObservation {
}
}
func isWrapping(_ observer: some TransactionObserver) -> Bool {
func isWrapping(_ observer: some TransactionObserverBase<API>) -> Bool {
self.observer === observer
}
@@ -1008,7 +1025,7 @@ final class TransactionObservation {
try observer?.databaseWillCommit()
}
func databaseDidCommit(_ db: Database) {
func databaseDidCommit(_ db: DatabaseBase<API>) {
switch extent {
case .observerLifetime, .databaseLifetime:
observer?.databaseDidCommit(db)
@@ -1024,7 +1041,7 @@ final class TransactionObservation {
}
}
func databaseDidRollback(_ db: Database) {
func databaseDidRollback(_ db: DatabaseBase<API>) {
switch extent {
case .observerLifetime, .databaseLifetime:
observer?.databaseDidRollback(db)
@@ -1043,8 +1060,8 @@ final class TransactionObservation {
/// The observation of one particular statement, by a particular
/// transaction observer.
struct StatementObservation {
var transactionObservation: TransactionObservation
struct StatementObservation<API: SQLiteAPI> {
var transactionObservation: TransactionObservation<API>
/// A predicate that filters database events that should be notified.
///
@@ -1055,7 +1072,7 @@ struct StatementObservation {
/// ```
var tracksEvent: DatabaseEventPredicate
init(transactionObservation: TransactionObservation, trackingEvents predicate: DatabaseEventPredicate) {
init(transactionObservation: TransactionObservation<API>, trackingEvents predicate: DatabaseEventPredicate) {
self.transactionObservation = transactionObservation
self.tracksEvent = predicate
}
@@ -1243,16 +1260,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 +1502,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt)
-> DatabaseValue?
{
var value: SQLiteValue? = nil
var value: SQLiteValue?
guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil }
if let value {
return DatabaseValue(sqliteValue: value)
+14 -23
View File
@@ -1,12 +1,15 @@
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
/// An instance of WALSnapshot records the state of a WAL mode database for some
/// specific point in history.
@@ -16,30 +19,18 @@ import SQLite3
/// actual observation. This class has no other purpose, and is not intended to
/// become public.
///
/// It does not work with SQLCipher, because SQLCipher does not support
/// `SQLITE_ENABLE_SNAPSHOT` correctly: we have linker errors.
/// See <https://github.com/ericsink/SQLitePCL.raw/issues/452>.
///
/// With custom SQLite builds, it only works if `SQLITE_ENABLE_SNAPSHOT`
/// is defined.
///
/// With system SQLite, it works because the SDK exposes the C apis and
/// since XCode 14.
///
/// Yes, this is an awfully complex logic.
///
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
final class WALSnapshot: @unchecked Sendable {
// @unchecked because sqlite3_snapshot has no threading requirements.
// <https://www.sqlite.org/c3ref/snapshot.html>
let sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>
init(_ db: Database) throws {
init(_ db: DatabaseBase<some SQLiteAPI>) throws {
var sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>?
let code = withUnsafeMutablePointer(to: &sqliteSnapshot) {
return sqlite3_snapshot_get(db.sqliteConnection, "main", $0)
}
guard code == SQLITE_OK else {
guard code == API.SQLITE_OK else {
// <https://www.sqlite.org/c3ref/snapshot_get.html>
//
// > The following must be true for sqlite3_snapshot_get() to succeed. [...]
+13 -7
View File
@@ -1,13 +1,13 @@
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
/// A long-live read-only WAL transaction.
///
/// `WALSnapshotTransaction` **takes ownership** of its reader
/// `SerializedDatabase` (TODO: make it a move-only type eventually).
final class WALSnapshotTransaction: @unchecked Sendable {
final class WALSnapshotTransactionBase<API: SQLiteAPI>: @unchecked Sendable {
// @unchecked because `databaseAccess` is protected by a mutex.
private struct DatabaseAccess {
let reader: SerializedDatabase
let reader: SerializedDatabaseBase<API>
let release: @Sendable (_ isInsideTransaction: Bool) -> Void
// MUST be called only once
@@ -15,7 +15,13 @@ final class WALSnapshotTransaction: @unchecked Sendable {
// WALSnapshotTransaction may be deinitialized in the dispatch
// queue of its reader: allow reentrancy.
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
try? db.commit()
// Commit or rollback, but try hard to leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
return db.isInsideTransaction
}
release(isInsideTransaction)
@@ -54,7 +60,7 @@ final class WALSnapshotTransaction: @unchecked Sendable {
/// - parameter release: A closure to call when the read-only connection
/// is no longer used.
init(
onReader reader: SerializedDatabase,
onReader reader: SerializedDatabaseBase<API>,
release: @escaping @Sendable (_ isInsideTransaction: Bool) -> Void)
throws
{
@@ -84,7 +90,7 @@ final class WALSnapshotTransaction: @unchecked Sendable {
/// Executes database operations in the snapshot transaction, and
/// returns their result after they have finished executing.
func read<T>(_ value: (Database) throws -> T) throws -> T {
func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
try databaseAccessMutex.withLock { databaseAccess in
guard let databaseAccess else {
throw DatabaseError.snapshotIsLost()
@@ -97,7 +103,7 @@ final class WALSnapshotTransaction: @unchecked Sendable {
/// Schedules database operations for execution, and
/// returns immediately.
func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
func asyncRead(_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void) {
databaseAccessMutex.withLock { databaseAccess in
guard let databaseAccess else {
value(.failure(DatabaseError.snapshotIsLost()))
+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:
@@ -128,7 +128,7 @@ For example:
```swift
extension EvenInteger: StatementColumnConvertible {
init?(sqliteStatement: SQLiteStatement, index: CInt) {
init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
guard let value = Int(exactly: int64) else {
return nil // Does not fit Int (probably a 32-bit architecture)
@@ -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)
```
+9 -9
View File
@@ -69,7 +69,7 @@ On insertion, the `Player` record should get fresh `creationDate` and `modificat
extension Player: Encodable, MutablePersistableRecord {
/// Sets both `creationDate` and `modificationDate` to the
/// transaction date, if they are not set yet.
mutating func willInsert(_ db: Database) throws {
mutating func willInsert(_ db: DatabaseBase<some SQLiteAPI>) throws {
if creationDate == nil {
creationDate = try db.transactionDate
}
@@ -182,7 +182,7 @@ extension Player: Encodable, MutablePersistableRecord {
/// Sets both `creationDate` and `modificationDate` to the
/// transaction date, if they are not set yet.
mutating func willInsert(_ db: Database) throws {
mutating func willInsert(_ db: DatabaseBase<some SQLiteAPI>) throws {
if creationDate == nil {
creationDate = try db.transactionDate
}
@@ -311,7 +311,7 @@ You can copy it in your application, or use it as an inspiration. Not all apps h
extension Player {
/// If the player has a non-nil primary key and a matching row in
/// the database, the player is updated. Otherwise, it is inserted.
mutating func saveWithTimestamp(_ db: Database) throws {
mutating func saveWithTimestamp(_ db: DatabaseBase<some SQLiteAPI>) throws {
// Test the presence of id first, so that we don't perform an
// update that would surely throw RecordError.recordNotFound.
if id == nil {
@@ -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 }
@@ -346,7 +346,7 @@ extension TimestampedRecord {
/// `TimestampedRecord` types that customize the `willInsert`
/// persistence callback should call `initializeTimestamps` from
/// their implementation.
mutating func willInsert(_ db: Database) throws {
mutating func willInsert(_ db: DatabaseBase<some SQLiteAPI>) throws {
try initializeTimestamps(db)
}
@@ -356,7 +356,7 @@ extension TimestampedRecord {
/// It is called automatically before insertion, if your type does not
/// customize the `willInsert` persistence callback. If you customize
/// this callback, call `initializeTimestamps` from your implementation.
mutating func initializeTimestamps(_ db: Database) throws {
mutating func initializeTimestamps(_ db: DatabaseBase<some SQLiteAPI>) throws {
if creationDate == nil {
creationDate = try db.transactionDate
}
@@ -370,7 +370,7 @@ extension TimestampedRecord {
///
/// - parameter modificationDate: The modification date. If nil, the
/// transaction date is used.
mutating func updateWithTimestamp(_ db: Database, modificationDate: Date? = nil) throws {
mutating func updateWithTimestamp(_ db: DatabaseBase<some SQLiteAPI>, modificationDate: Date? = nil) throws {
self.modificationDate = try modificationDate ?? db.transactionDate
try update(db)
}
@@ -403,7 +403,7 @@ extension TimestampedRecord {
/// - returns: Whether the record was changed and updated.
@discardableResult
mutating func updateChangesWithTimestamp(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
modificationDate: Date? = nil,
modify: (inout Self) -> Void)
throws -> Bool
@@ -431,7 +431,7 @@ extension TimestampedRecord {
///
/// - parameter modificationDate: The modification date. If nil, the
/// transaction date is used.
mutating func touch(_ db: Database, modificationDate: Date? = nil) throws {
mutating func touch(_ db: DatabaseBase<some SQLiteAPI>, modificationDate: Date? = nil) throws {
try updateChanges(db) {
$0.modificationDate = try modificationDate ?? db.transactionDate
}
+4 -4
View File
@@ -128,7 +128,7 @@ We have seen in the <doc:SingleRowTables#The-Single-Row-Table> section that by d
```swift
// Customize the default PersistableRecord behavior
func willUpdate(_ db: Database, columns: Set<String>) throws {
func willUpdate(_ db: DatabaseBase<some SQLiteAPI>, columns: Set<String>) throws {
// Insert the default configuration if it does not exist yet.
if try !exists(db) {
try AppConfiguration.default.insert(db)
@@ -141,7 +141,7 @@ The standard GRDB method ``FetchableRecord/fetchOne(_:)`` returns an optional wh
```swift
/// Returns the persisted configuration, or the default one if the
/// database table is empty.
static func find(_ db: Database) throws -> AppConfiguration {
static func find(_ db: DatabaseBase<some SQLiteAPI>) throws -> AppConfiguration {
try fetchOne(db) ?? .default
}
}
@@ -233,7 +233,7 @@ extension AppConfiguration {
// Database Access
extension AppConfiguration: FetchableRecord, PersistableRecord {
// Customize the default PersistableRecord behavior
func willUpdate(_ db: Database, columns: Set<String>) throws {
func willUpdate(_ db: DatabaseBase<some SQLiteAPI>, columns: Set<String>) throws {
// Insert the default configuration if it does not exist yet.
if try !exists(db) {
try AppConfiguration.default.insert(db)
@@ -242,7 +242,7 @@ extension AppConfiguration: FetchableRecord, PersistableRecord {
/// Returns the persisted configuration, or the default one if the
/// database table is empty.
static func find(_ db: Database) throws -> AppConfiguration {
static func find(_ db: DatabaseBase<some SQLiteAPI>) throws -> AppConfiguration {
try fetchOne(db) ?? .default
}
}
+15 -3
View File
@@ -55,7 +55,7 @@ let count = try await writer.read { db in
}
// Shorthand notation:
// ⚠️ Converting non-sendable function value to '@Sendable (Database)
// ⚠️ Converting non-sendable function value to '@Sendable (DatabaseBase<some SQLiteAPI>)
// throws -> Int' may introduce data races.
let count = try await writer.read(Player.fetchCount)
```
@@ -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/
+2 -2
View File
@@ -160,7 +160,7 @@ This restriction can be left with the ``Configuration/allowsUnsafeTransactions``
It is possible to ask if a transaction is currently opened:
```swift
func myCriticalMethod(_ db: Database) throws {
func myCriticalMethod(_ db: DatabaseBase<some SQLiteAPI>) throws {
precondition(db.isInsideTransaction, "This method requires a transaction")
try ...
}
@@ -169,7 +169,7 @@ func myCriticalMethod(_ db: Database) throws {
Yet, there is a better option than checking for transactions. Critical database sections should use savepoints, described below:
```swift
func myCriticalMethod(_ db: Database) throws {
func myCriticalMethod(_ db: DatabaseBase<some SQLiteAPI>) throws {
try db.inSavepoint {
// Here the database is guaranteed to be inside a transaction.
try ...
+383
View File
@@ -0,0 +1,383 @@
# View Records
Define record types that target database views.
## Overview
A record type targets a [database view] as soon as its ``TableRecord/databaseTableName-3tcw2`` is the name of a view.
With such a record, some GRDB features will work out of the box, and some will throw errors without extra configuration:
```swift
// OK: Works out of the box
let captains = try Captain.fetchAll(db)
let captainCount = try Captain.fetchCount(db)
// KO: Requires extra configuration
// SQLite error 1: database view captain has no primary key
var bob = try Captain.find(db, id: "bob")
bob.name = "Bobby"
// SQLite error 1: cannot modify captain because it is a view
try bob.update(db)
```
This article explains how to solve those errors:
- How to provide a primary key to a view.
- How to define INSTEAD OF triggers that insert, update, and delete through a database view.
> important: GRDB is impacted by some SQLite limitations regarding INSTEAD OF triggers:
>
> - **Auto-incremented primary keys are not supported.** To be precise, SQLite won't expose the rowid of rows inserted via an INSTEAD OF trigger, so GRDB won't know the id of newly inserted rows. This has various nefarious consequences—see for example the important notice in the ``MutablePersistableRecord/didInsert(_:)`` callback. For more information, check this [SQLite forum thread](https://sqlite.org/forum/forumpost/707e7ed932).
> - **INSTEAD OF triggers and the RETURNING clause do not play well together.** Those are SQLite bugs. All GRDB record methods with `andFetch` in their name may return unexpected or wrong results, depending on the SQLite version. For example, the SQLite version that ships with iOS 18 has bugs, and even more in iOS 17. If you intend to use the `RETURNING` clause, it is recommended that you write tests and run them in various target operation systems.
## Preliminary Setup
To support this documentation, we need a database that contains a view. The sample code below uses <doc:Migrations> and <doc:DatabaseSchemaModifications> methods.
The database schema contains teams and players. Some players are the captain of their team. We enforce in the database schema that a given team can't have multiple captains:
```swift
var migrator = DatabaseMigrator()
migrator.registerMigration("Teams and players") { db in
try db.create(table: "team") { t in
t.primaryKey("id", .text)
t.column("name", .text).notNull()
}
try db.create(table: "player") { t in
t.primaryKey("id", .text)
t.column("name", .text).notNull()
t.belongsTo("team", onDelete: .setNull)
t.column("isCaptain", .boolean).notNull()
}
// One unique captain per team
try db.create(
indexOn: "player", columns: ["teamId"],
options: .unique,
condition: Column("isCaptain"))
}
```
We define record types for the `team` and `player` tables, as described in <doc:RecordRecommendedPractices>:
```swift
struct Team: Codable, Identifiable, FetchableRecord, PersistableRecord {
var id: String
var name: String
}
struct Player: Codable, Identifiable, FetchableRecord, PersistableRecord {
var id: String
var name: String
var teamId: String?
var isCaptain: Bool
}
```
Let's define a view and a record type for captains. At this point, both the view and the record are read-only:
```swift
migrator.registerMigration("Read-only captains") { db in
try db.execute(sql: """
CREATE VIEW captain AS
SELECT id, name, teamId
FROM player
WHERE isCaptain AND teamId IS NOT NULL;
""")
}
struct Captain: Decodable, Identifiable, FetchableRecord {
var id: String
var name: String
var teamId: String
}
```
✅ From now on, we can use the `Captain` record:
```swift
let dbQueue = try DatabaseQueue()
try migrator.migrate(dbQueue)
try dbQueue.write { db in
try Team(id: "red", name: "Red").insert(db)
try Team(id: "blue", name: "Blue").insert(db)
try Player(id: "alice", name: "Alice", teamId: "red", isCaptain: true).insert(db)
try Player(id: "bob", name: "Bob", teamId: "blue", isCaptain: true).insert(db)
try Player(id: "craig", name: "Craig", teamId: "blue", isCaptain: false).insert(db)
let captains = try Captain.fetchAll(db)
// Prints:
// Captain(id: "alice", name: "Alice", teamId: "red")
// Captain(id: "bob", name: "Bob", teamId: "blue")
print(captains)
}
```
## Specifying the primary key of a view
SQLite views do not have any primary key, so GRDB cannot introspect the database schema and automatically find the eventual primary key.
To instruct GRDB about the primary key, define a **schema source**, a type that conforms to ``DatabaseSchemaSource``. In this sample code, the schema only contains the "captain" view, so our schema source does not need to be very complicated. Check the documentation of the protocol for more detailed instructions:
```swift
struct GameSchemaSource: DatabaseSchemaSource {
/// Returns the names of the columns for the primary key in the
/// provided database view.
func columnsForPrimaryKey(_ db: DatabaseBase<some SQLiteAPI>, inView view: DatabaseObjectID) throws -> [String]? {
["id"]
}
}
```
We configure the database connection with this schema source:
```swift
var config = Configuration()
config.schemaSource = GameSchemaSource()
let dbQueue = try DatabaseQueue(configuration: config)
try migrator.migrate(dbQueue)
```
✅ We can now use the primary key of captains:
```swift
try dbQueue.read { db in
// [Insert some teams and players...]
let captains = try Captain.orderByPrimaryKey().fetchAll(db)
let alice = try Captain.find(db, id: "alice")
}
```
## Associations between views
To define [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) between record types that target database views, the foreign key must be explicitly provided. We define the foreign key from `captain` to `team` with a column declared as recommended in <doc:RecordRecommendedPractices>:
```swift
extension Captain {
// Time to define some columns
enum Columns {
static let teamId = Column(CodingKeys.teamId)
}
// The captain view has a foreign key to teams,
// from the teamId column to the team primary key.
// SQLite does not know about it, so we declare it explicitly:
static let teamForeignKey = ForeignKey([Columns.teamId])
// A captain belongs to a team.
static let team = belongsTo(Team.self, using: teamForeignKey)
}
extension Team {
// A team has a captain.
static let captain = hasOne(Captain.self, using: Captain.teamForeignKey)
}
```
✅ We can now use those associations:
```swift
try dbQueue.read { db in
// All teams with a captain
let teamsWithCaptain: [Team] = try Team
.joining(required: Team.captain)
.fetchAll(db)
// All (captain, team) pairs
struct CaptainWithTeam: Decodable, FetchableRecord {
var captain: Captain
var team: Team
}
let captainsWithTeam: [CaptainWithTeam] = try Captain
.including(required: Captain.team)
.asRequest(of: CaptainWithTeam.self)
.fetchAll(db)
}
```
## Inserting rows into a view
SQLite views are read-only unless we define an [INSTEAD OF trigger] that specifies which statements to run when we insert a row into a view.
INSTEAD OF triggers are very versatile, and applications can define the behavior that best fits their needs. In our sample code, inserting a captain will insert a player with the `isCaptain` flag set, and we'll also remove the `isCaptain` flag of the previous captain, if any:
```swift
migrator.registerMigration("Captain insert") { db in
try db.execute(sql: """
-- Insert trigger
CREATE TRIGGER captain_insert
INSTEAD OF INSERT ON captain
BEGIN
-- Remove previous captain
UPDATE player SET isCaptain = 0
WHERE teamId = NEW.teamId AND isCaptain;
-- Insert new captain
INSERT INTO player(id, name, teamId, isCaptain)
VALUES (NEW.id, NEW.name, NEW.teamId, 1);
END;
""")
}
// Apply the new migration
try migrator.migrate(dbQueue)
```
Let's also give an `insert()` method to the Captain record, with the ``PersistableRecord`` protocol:
```swift
extension Captain: Encodable, PersistableRecord { }
```
- note: Remember that auto-incremented primary keys are not supported, as described at the beginning of this article. Our captain view is backed by the player table which has a string primary key, so we're fine.
✅ We can directly insert captains:
```swift
try dbQueue.write {
try Team(id: "green", name: "Green").insert(db)
// Diane is the captain
try Captain(id: "diane", name: "Diane", teamId: "green").insert(db)
// Well, no: Eugene is the captain
try Captain(id: "eugene", name: "Eugene", teamId: "green").insert(db)
// Prints:
// team player captain
// green|Green diane|Diane|green|0 eugene|Eugene|green
// eugene|Eugene|green|1
try db.dumpTables(["team", "player", "captain"])
}
```
## Updating rows in a view
Just like for inserts, an INSTEAD OF trigger can specify how to update rows in a view.
In our sample code, updating a captain will update the player with the same id, and remove the `isCaptain` flag from the previous captain of the team, if any:
```swift
migrator.registerMigration("Captain update") { db in
try db.execute(sql: """
-- Update trigger
CREATE TRIGGER captain_update
INSTEAD OF UPDATE ON captain
BEGIN
-- Remove previous captain
UPDATE player SET isCaptain = 0
WHERE teamId = NEW.teamId AND isCaptain AND id <> NEW.id;
-- Update captain
UPDATE player SET name = NEW.name, teamId = NEW.teamId, isCaptain = 1
WHERE id = NEW.id;
END;
""")
}
// Apply the new migration
try migrator.migrate(dbQueue)
```
✅ Let's update captains:
```swift
try dbQueue.write {
try Team(id: "red", name: "Red").insert(db)
try Team(id: "blue", name: "Blue").insert(db)
try Captain(id: "alice", name: "Alice", teamId: "red").insert(db)
// Bob is the Blue captain.
var bob = Captain(id: "bob", name: "Bob", teamId: "blue")
try bob.insert(db)
// Bob is now Bobby, the Red captain.
// Alice is no longer the Red captain.
try bob.updateChanges(db) {
$0.name = "Bobby"
$0.teamId = "red"
}
// Prints:
// team player captain
// blue|Blue alice|Alice|red|0 bob|Bobby|red
// red|Red bob|Bobby|red|1
try db.dumpTables(["team", "player", "captain"])
}
```
## Deleting rows from a view
The last missing INSTEAD OF trigger deals with deletes:
```swift
migrator.registerMigration("Captain delete") { db in
try db.execute(sql: """
-- Delete trigger
CREATE TRIGGER captain_delete
INSTEAD OF DELETE ON captain
BEGIN
DELETE FROM player WHERE id = OLD.id;
END;
""")
}
// Apply the new migration
try migrator.migrate(dbQueue)
```
✅ Let's delete some captains:
```swift
try dbQueue.write {
// Delete Alice
try Captain.deleteOne(db, id: "alice")
// Delete Bob
let bob = try Captain.find(db, id: "bob")
try bob.delete(db)
// Delete all captains
try Captain.deleteAll()
}
```
## Going further
To exercise the techniques described here, try to define record types for these other views:
- The `enrolledPlayer` view that only contains players that belong to a team:
```swift
try db.execute(sql: """
CREATE VIEW enrolledPlayer AS
SELECT id, name, teamId, isCaptain
FROM player
WHERE teamId IS NOT NULL;
""")
```
- The `teamWithCaptainId` view that contains a `captainId` column:
```swift
try db.execute(sql: """
CREATE VIEW teamWithCaptainId AS
SELECT team.id, team.name, player.id AS captainId
FROM team
JOIN player ON player.teamId = team.id AND player.isCaptain;
""")
```
- A refactored `captain` view whose primary key is the team id—this is valid, since the schema enforces that there's a single captain for each team:
```swift
try db.execute(sql: """
CREATE VIEW captain AS
SELECT teamId, name
FROM player
WHERE isCaptain AND teamId IS NOT NULL;
""")
```
[database view]: https://www.sqlite.org/lang_createview.html
[INSTEAD OF trigger]: https://sqlite.org/lang_createtrigger.html#instead_of_triggers
+6 -6
View File
@@ -2,7 +2,7 @@ import Foundation
// MARK: - Dump
extension Database {
extension DatabaseBase {
/// Prints the results of all statements in the provided SQL.
///
/// For example:
@@ -183,7 +183,7 @@ extension Database {
// MARK: -
extension Database {
extension DatabaseBase {
func _dumpStatements(
_ statements: some Cursor<Statement>,
format: some DumpFormat,
@@ -317,16 +317,16 @@ extension Database {
}
private func ignoresObject(named name: String) throws -> Bool {
if Database.isSQLiteInternalTable(name) { return true }
if Database.isGRDBInternalTable(name) { return true }
if Self.isSQLiteInternalTable(name) { return true }
if Self.isGRDBInternalTable(name) { return true }
if try isShadowTable(name) { return true }
return false
}
private func isShadowTable(_ tableName: String) throws -> Bool {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
// Maybe SQLCipher is too old: check actual version
if sqlite3_libversion_number() >= 3037000 {
if Database.sqliteLibVersionNumber >= 3037000 {
guard let table = try table(tableName) else {
// Not a table
return false
+1 -1
View File
@@ -1,4 +1,4 @@
extension DatabaseReader {
extension DatabaseReaderBase {
/// Prints the results of all statements in the provided SQL.
///
/// For example:
+8 -6
View File
@@ -33,26 +33,28 @@
/// - ``writeRow(_:statement:to:)``
/// - ``finalize(_:statement:to:)``
public protocol DumpFormat {
#warning("TODO: incompatible with GRDB 7")
/// Writes a row from the given statement.
///
/// - Parameters:
/// - db: A connection to the database
/// - statement: The iterated statement
/// - stream: A stream for text output.
mutating func writeRow(
_ db: Database,
statement: Statement,
mutating func writeRow<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream) throws
#warning("TODO: incompatible with GRDB 7")
/// All rows from the statement have been printed.
///
/// - Parameters:
/// - db: A connection to the database
/// - statement: The statement that was iterated.
/// - stream: A stream for text output.
mutating func finalize(
_ db: Database,
statement: Statement,
mutating func finalize<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
}
+18 -15
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -58,9 +61,9 @@ public struct DebugDumpFormat: Sendable {
}
extension DebugDumpFormat: DumpFormat {
public mutating func writeRow(
_ db: Database,
statement: Statement,
public mutating func writeRow<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
{
if firstRow {
@@ -88,15 +91,15 @@ extension DebugDumpFormat: DumpFormat {
stream.write("\n")
}
public mutating func finalize(
_ db: Database,
statement: Statement,
public mutating func finalize<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
{
firstRow = true
}
private func formattedValue(_ db: Database, in sqliteStatement: SQLiteStatement, at index: CInt) -> String {
private func formattedValue(_ db: DatabaseBase<some SQLiteAPI>, in sqliteStatement: SQLiteStatement, at index: CInt) -> String {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_NULL:
return nullValue
+18 -15
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -77,9 +80,9 @@ public struct JSONDumpFormat: Sendable {
}
extension JSONDumpFormat: DumpFormat {
public mutating func writeRow(
_ db: Database,
statement: Statement,
public mutating func writeRow<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
throws {
if firstRow {
@@ -124,9 +127,9 @@ extension JSONDumpFormat: DumpFormat {
stream.write("}")
}
public mutating func finalize(
_ db: Database,
statement: Statement,
public mutating func finalize<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
{
if firstRow {
@@ -142,7 +145,7 @@ extension JSONDumpFormat: DumpFormat {
firstRow = true
}
private func formattedValue(_ db: Database, in sqliteStatement: SQLiteStatement, at index: CInt) throws -> String {
private func formattedValue(_ db: DatabaseBase<some SQLiteAPI>, in sqliteStatement: SQLiteStatement, at index: CInt) throws -> String {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_NULL:
return "null"
+18 -15
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -40,9 +43,9 @@ public struct LineDumpFormat: Sendable {
}
extension LineDumpFormat: DumpFormat {
public mutating func writeRow(
_ db: Database,
statement: Statement,
public mutating func writeRow<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
{
var lines: [(column: String, value: String)] = []
@@ -73,9 +76,9 @@ extension LineDumpFormat: DumpFormat {
}
}
public mutating func finalize(
_ db: Database,
statement: Statement,
public mutating func finalize<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
{
if firstRow == false {
@@ -85,7 +88,7 @@ extension LineDumpFormat: DumpFormat {
}
func formattedValue(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
in sqliteStatement: SQLiteStatement,
at index: CInt)
-> String
+18 -15
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
import Foundation
@@ -55,9 +58,9 @@ public struct ListDumpFormat: Sendable {
}
extension ListDumpFormat: DumpFormat {
public mutating func writeRow(
_ db: Database,
statement: Statement,
public mutating func writeRow<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
{
if firstRow {
@@ -85,16 +88,16 @@ extension ListDumpFormat: DumpFormat {
stream.write("\n")
}
public mutating func finalize(
_ db: Database,
statement: Statement,
public mutating func finalize<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
{
firstRow = true
}
func formattedValue(
_ db: Database,
_ db: DatabaseBase<some SQLiteAPI>,
in sqliteStatement: SQLiteStatement,
at index: CInt)
-> String
+17 -14
View File
@@ -1,11 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
//// Import C SQLite functions
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
//import SQLCipher
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
//import SQLite3
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
//// #elseif SomeTrait
//// import ...
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
//import GRDBSQLite
//#endif
/// A format that prints one line per database row, formatting values
/// as SQL literals.
@@ -44,9 +47,9 @@ public struct QuoteDumpFormat: Sendable {
}
extension QuoteDumpFormat: DumpFormat {
public mutating func writeRow(
_ db: Database,
statement: Statement,
public mutating func writeRow<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
{
if firstRow {
@@ -78,9 +81,9 @@ extension QuoteDumpFormat: DumpFormat {
stream.write("\n")
}
public mutating func finalize(
_ db: Database,
statement: Statement,
public mutating func finalize<API>(
_ db: DatabaseBase<API>,
statement: StatementBase<API>,
to stream: inout DumpStream)
{
firstRow = true
Loaded 100 of 311 files, more files were not shown because too many files have changed in this diff. Show more