Compare commits

...
Author SHA1 Message Date
Gwendal Roué 92a554cd0d Merge branch 'development' 2026-11-01 18:24:21 +01:00
Gwendal Roué 47c8497269 v7.12.0 2026-11-01 17:03:56 +01:00
Gwendal Roué d99e639c11 Merge pull request #1894 from groue/dev/issue-1888
Fix SharedValueObservation deadlock, ordering, and cancellation
2026-11-01 16:51:47 +01:00
Gwendal Roué 1d59d1656b Fix SharedValueObservation 2026-11-01 16:23:38 +01:00
Gwendal Roué 5fe300b733 More failing SharedValueObservation tests 2026-11-01 16:00:41 +01:00
Dylan Mace a8a5b431be Failing tests: SharedValueObservation deadlocks when a client is cancelled during a notification 2026-11-01 15:02:39 +01:00
Gwendal Roué b7b747c5bb Merge pull request #1889 from builtbysharath/open-error-message
Keep SQLite's error message when a database fails to open
2026-11-01 14:55:17 +01:00
Gwendal Roué 62f4bfe5f3 Merge pull request #1893 from groue/dev/support-statement-recompilation
Dev/support statement recompilation
2026-11-01 14:54:23 +01:00
Gwendal Roué 9601d6ac9b Row fetched from a statement do not cache statement column in order to support statement recompilation 2026-11-01 14:22:32 +01:00
Gwendal Roué dc101b2847 Failing test for the Row column cache of a recompiled statement 2026-11-01 14:21:42 +01:00
Gwendal Roué a0f184ec26 Invalidate Statement column cache after recompilation 2026-11-01 14:21:42 +01:00
Gwendal Roué b983df96e2 Failing test for SQLRequest on a recompiled statement 2026-11-01 14:21:42 +01:00
Gwendal Roué 94fa864eb7 Failing test for the column cache of a recompiled statement 2026-11-01 13:57:06 +01:00
Sharath Kumar e1a0c1afbe Skip the open error message test when URI filenames are off
sqlite_compileoption_used('USE_URI') reports whether the option is
defined, not its value, and is missing when compile-option diagnostics
are omitted. Check the error from the open instead: without URI
filenames, the path is in a missing "file:" directory and fails with
SQLITE_CANTOPEN.
2026-10-13 15:35:38 +05:30
Sharath Kumar 3f80cfccf4 Keep SQLite's error message when a database fails to open 2026-10-11 22:33:07 +05:30
Gwendal Roué 6f64c72209 Merge pull request #1879 from nesevis/fix/rowid-and-single-integer-primary-key
Fix upsert for WITHOUT ROWID tables with an INTEGER primary key
2026-09-27 09:12:49 +02:00
Gwendal Roué 8e24aec8f2 Merge pull request #1885 from groue/dev/string-with-nul-character
Add support for Strings that contain the NUL character
2026-09-26 22:22:30 +02:00
Gwendal Roué de0ce29d73 Encode strings with a NUL character
Inspired from #1880 by @nesevis
2026-09-26 16:34:14 +02:00
Gwendal Roué 9858de3249 Decode strings with a NUL character
Inspired from #1880 by @nesevis
2026-09-26 16:34:14 +02:00
Gwendal Roué fe774b3537 Performance tests for String as a statement argument 2026-09-26 13:03:16 +02:00
Gwendal Roué 550ef55c90 Fast path for String performance decoding test 2026-09-26 12:43:38 +02:00
Gwendal Roué e37c7cf306 Do not measure database access acquisition and Array building 2026-09-26 12:37:11 +02:00
Gwendal Roué 1ff66c8382 Test independance 2026-09-26 12:36:33 +02:00
Chris Kolbu 8957148d4d Performance tests for string fetching and function results 2026-09-26 12:34:37 +02:00
Gwendal Roué 23083c4668 Failing tests for strings with a NUL character used as statement argument
Inspired from #1880 by @nesevis
2026-09-26 12:06:49 +02:00
Gwendal Roué dfa942e9c0 Failing tests for decoding and encoding strings with a NUL character
Inspired from #1880 by @nesevis
2026-09-26 12:06:43 +02:00
Gwendal Roué 5d31cba4a0 Failing tests for database functions returning or accepting strings with a NUL character
Inspired from #1880 by @nesevis
2026-09-26 12:06:36 +02:00
Gwendal Roué 533286eab0 Merge pull request #1884 from groue/dev/fix-1883
Work around an SQLite bug in WAL snapshot ordering
2026-09-26 10:37:32 +02:00
Gwendal Roué ac1e5e66be Remove assertion about SQLite snapshot ordering
Fix #1883
2026-09-26 10:20:32 +02:00
Gwendal Roué 6bf7ba8f03 Merge pull request #1881 from groue/dev/fix-1873
Fix an accidentally quadratic behavior in SQLite statement compilation
2026-09-23 19:09:50 +02:00
Gwendal Roué 9f2e3b7d6b Optimize statement authorizer region accumulation
This commit is inspired by #1873 from @guidedways, who detected an unexpectedly quadratic behavior in the way we build database regions from the statement authorizer
2026-09-23 14:16:22 +02:00
Gwendal Roué c08767b500 Fix stale test
The test was checking for the presence of an SQLite bug. This bug is gone in macOS 27.0.
2026-09-15 14:36:27 +02:00
Chris Kolbu 8511cfd399 Document INTEGER PRIMARY KEY in WITHOUT ROWID tables 2026-08-18 19:55:41 +10:00
Chris Kolbu 4373b3a49b Fix failing tests for INTEGER PRIMARY KEY in WITHOUT ROWID tables 2026-08-18 19:55:41 +10:00
Chris Kolbu d4713c1fa8 Failing tests for INTEGER PRIMARY KEY in WITHOUT ROWID tables 2026-08-18 19:55:41 +10:00
Gwendal Roué 0d8cf958b4 Merge pull request #1876 from latent-9/docs/fix-doubled-word
Fix doubled word in doc comment
2026-08-08 10:56:30 +02:00
latent-9 0a9a55d15f Fix doubled word in doc comment 2026-08-08 15:07:24 +12:00
Gwendal Roué b83108d10f Merge branch 'development' 2026-06-18 14:07:07 +02:00
Gwendal Roué 468b8e81be v7.11.1 2026-06-18 14:06:56 +02:00
Gwendal Roué a3a29aa921 Merge pull request #1869 from MarkusSintonen/optimize-register-migration
Optimize migration registration to be O(n) instead of O(n^2)
2026-06-18 08:19:57 +02:00
Markus Sintonen f1d321139f Combine unappliedExecutions into a single loop 2026-06-17 21:06:52 +03:00
Markus Sintonen 7d489358e2 Compare migration identifier from OrderedDictionary key 2026-06-17 20:41:46 +03:00
Markus Sintonen 67530472a5 Use OrderedDictionary for O(1) migration registration 2026-06-17 20:35:58 +03:00
Gwendal Roué fe3b957e5f Add missing Foundation imports 2026-06-10 12:55:39 +02:00
Gwendal Roué f1eb48b0cf Fix a warning in Version 27.0 beta 2026-06-10 12:53:47 +02:00
Gwendal Roué 9ed8c8457e Merge branch 'development' 2026-06-01 08:06:44 +02:00
Gwendal Roué 656d1f4539 v7.11.0 2026-06-01 08:06:35 +02:00
Gwendal Roué cc85b3d82d Disable GRDBCustom on GitHub CI
The tests pass on my machine, but not on CI: https://github.com/groue/GRDB.swift/actions/runs/26725623508/job/78792729917
2026-06-01 07:51:40 +02:00
Gwendal Roué 97f517a660 Use Xcode folders
... except in projects that use CocoaPods, because well the new Xcode project format is not supporteed
2026-05-31 23:57:01 +02:00
Gwendal Roué b49e990bdd Merge pull request #1864 from simolus3/development
Add `observe(statement:)` to `TransactionObserver`
2026-05-31 14:38:10 +02:00
Gwendal Roué 27c7bda0e9 Refactor with DatabaseEventObservationStrategy
The issue with `observesAllDatabaseChanges` is that this was a misleading name: transaction observers are not notified of changes that are performed in a save point that is eventually rollbacked.

By exposing the DatabaseEventObservationStrategy type, we allow for a future extra flag that ignores save points, trading observation precision for a reduced memory footprint.
2026-05-31 14:04:10 +02:00
Simon Binder 253cdfec8c Review feedback 2026-05-11 20:47:20 +02:00
Simon Binder e934c428b4 Add observe(statement:) to TransactionObserver 2026-05-05 22:06:06 +02:00
Gwendal Roué cdc2fb4200 Merge pull request #1858 from groue/dev/issue-1855
Fix upsert for WITHOUT ROWID tables
2026-03-19 08:07:22 +01:00
Gwendal Roué 47cb0b877b Fix failing test for upsert in a table WITHOUT ROWID
Fixes #1855
2026-03-16 12:10:57 +01:00
Gwendal Roué c637e04133 Failing test for upsert in a table WITHOUT ROWID
Failing test for #1855
2026-03-16 12:10:57 +01:00
Gwendal Roué 36e30a6f1e Merge branch 'development' 2026-02-15 15:10:35 +01:00
Gwendal Roué 368514c33b v7.10.0 2026-02-15 15:09:40 +01:00
Gwendal Roué 21b1322e05 Fix Swiftlint warnings 2026-02-15 15:09:40 +01:00
Gwendal Roué 819f4572df Merge pull request #1852 from groue/dev/upsert-strategy
Configure whether UPSERT should update all columns, or no column.
2026-02-15 14:10:32 +01:00
Gwendal Roué 7b01c9b72b Let the user choose between the two possible update strategies for upsert 2026-02-15 13:40:05 +01:00
Gwendal Roué 7f9d1503a0 Merge pull request #1850 from swift-everywhere/platform-fixes
Android and Windows platform import/conditional accommodation
2026-02-04 08:38:48 +01:00
Marc Prud'hommeaux 14567635e4 Android and Windows platform import/conditional accommodation 2026-02-03 17:56:04 -05:00
Gwendal Roué 205387d2d2 Merge pull request #1849 from marcprux/patch-1
Add Sendable conformance to DispatchQueueExecutor for Android and Windows
2026-02-03 11:32:13 +01:00
Marc Prud'hommeaux c8f0328413 Add Sendable conformance to DispatchQueueExecutor for Android and Windows 2026-02-03 10:44:33 +01:00
Gwendal Roué e784b10314 Merge pull request #1845 from R4N/sqlcipher-spm-upstream
SQLCipher organizational/import adjustments
2026-02-03 08:19:11 +01:00
Gwendal Roué 34fa177a47 Merge pull request #1848 from groue/bellebethcooper-typo-fix
Minor typo in doc comments
2026-02-03 08:13:35 +01:00
bellebethcooper 67ebcb325c Minor typo in doc comments 2026-02-03 16:32:37 +11:00
Gwendal Roué a3036feb48 Merge branch 'development' into sqlcipher-spm-upstream 2026-02-01 15:11:22 +01:00
Gwendal Roué 14d4c842e4 Document how to enable SQLCipher with SPM 2026-02-01 14:48:50 +01:00
Gwendal Roué 79276d7f68 Prepare support for SPM+SQLCipher 2026-02-01 14:43:24 +01:00
Gwendal Roué 14fdba1ef3 Rename CipherXxx APIs to SQLCipherXxx when possible 2026-02-01 14:43:24 +01:00
Gwendal Roué 8b5017714f Support more SQLCipher log destinations 2026-02-01 14:43:24 +01:00
Gwendal Roué a1a9c3aefe Make links appear as links in DocC 2026-02-01 12:37:49 +01:00
Gwendal Roué d664db9610 Enhance documentation formatting 2026-02-01 12:37:49 +01:00
Gwendal Roué 2c4492a098 Do not define CipherLogLevel as a frozen enum 2026-02-01 12:37:49 +01:00
Gwendal Roué c0ef0e0f99 Use the same logic for importing SQLCipher as in other files 2026-02-01 11:19:30 +01:00
Gwendal Roué 81a699cae9 Merge branch 'grdb_linux_changes' into development 2026-02-01 11:00:35 +01:00
Micah Moore bd954c6791 Removes GRDBSQLCipher import from SQLCipher conditional import in Database.swift to allow SQLCipher forkers versatility for defining pass-throughs to GRDB required sqlite variadic functions. 2026-01-19 13:37:41 -05:00
Micah Moore 2f94eb307a Adds Foundation import to Database+SQLCipher 2026-01-16 14:59:25 -05:00
Gwendal Roué 51083da42d Merge pull request #1846 from leejungyeob/fix-usage-example-typo
Fix typo in usage examples
2026-01-16 13:18:54 +01:00
leejungyeob c229891b6d Fix typo in usage examples 2026-01-16 18:20:56 +09:00
Micah Moore c24bf5d118 SQLCipher adjustments to support forks which want to enable SQLCipher using traits/swiftSettings
- Adds Database+SQLCipher extension with SQLCipher operations, enabled by #if SQLITE_HAS_CODEC
- Adjusts Import Statements to import SQLCipher when SQLCipher trait is enabled (or SQLCipher swiftSetting is set)
2026-01-14 11:32:48 -05:00
Gwendal Roué ccfe3149d7 Merge pull request #1842 from Cykelero/fix-usage-example-typos
Fix typos in usage examples
2026-01-09 16:30:58 +01:00
Nathan Manceaux-Panot ce71d6c19f Fix typos in usage examples 2026-01-09 15:44:42 +01:00
Gwendal Roué 129e53d54e Remove obsolete TODOs 2025-12-30 13:00:56 +01:00
Gwendal Roué bc5dd31366 Fix Swiftlint warnings 2025-12-30 10:31:13 +01:00
Gwendal Roué aa0079aeb8 Merge branch 'development' 2025-12-13 12:11:32 +01:00
Gwendal Roué 74ef238376 v7.9.0 2025-12-13 12:05:31 +01:00
Gwendal Roué 9d7a487971 Merge pull request #1839 from groue/dev/issue-1838
Fix cancellation of async tasks that use the FTS5 full-text engine.
2025-12-10 16:11:32 +01:00
Gwendal Roué ac2f2e8643 Test that we recover from the FTS5 bug 2025-12-10 13:38:25 +01:00
Gwendal Roué e281149a2d Simplify Issue1838Tests
... and add it to test targets
2025-12-10 13:28:04 +01:00
Gwendal Roué 3ee256e7e8 Common API for statements that must ignore interruption errors 2025-12-09 21:39:20 +01:00
Gwendal Roué 361599aacd Task cancellation should turn all SQLITE_INTERRUPT errors into CancellationError, including errors thrown by statement compilation
I did not know statement compilation could fail when database is interrupted until #1838. A ROLLBACK statement would not even compile due to the FTS5 statement leak reported in https://sqlite.org/forum/forumpost/137c7662b389fa18
2025-12-09 21:38:15 +01:00
Gwendal Roué 64a024097d Fix failing test for #1838 by reseting all prepared statements before retrying 2025-12-08 21:40:48 +01:00
Gwendal Roué 60ea10948b Protect PRAGMA query_only = 0 against SQLITE_INTERRUPT
This should fix a race condition about cancellation that happens during a read-only access.
2025-12-08 21:22:43 +01:00
Gwendal Roué 5dba64d545 Retry a rollback in case of SQLITE_INTERRUPT error
This should fix a race condition about cancellation that happens during a rollback
2025-12-08 21:11:26 +01:00
Gwendal Roué 2212a17950 Failing test for #1838 2025-12-08 15:13:28 +01:00
Gwendal Roué 24fa06d646 Merge branch 'master' into development 2025-12-08 09:51:07 +01:00
Gwendal Roué fd788900b6 Revert "Add link to our beloved sponsor Base"
This reverts commit 827ab62bb6.
2025-12-08 09:50:02 +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
Tim De Jong 3dd3bbf0c5 vscode config 2025-10-12 18:03:57 +02:00
Tim De Jong d7cf0f9e59 NSError bridging is not available, or doesn't work the same on non-Darwin platforms. Skip testNSErrorBridging on these platforms. 2025-10-12 18:03:57 +02:00
Tim De Jong 389c3e0d4a Use #if !canImport(Combine) per test case (as done by @marcprux) and throw an XCTSkip for these test cases. This gives a better impression how many tests are skipped on Linux/non-Darwin platforms. 2025-10-12 18:03:57 +02:00
Tim De Jong a212bf9e89 It should be canImport(Darwin) not os(Darwin) 2025-10-12 18:03:57 +02:00
Tim De Jong 65186104cc Integrated upstream changes.
Some tests depend on Combine which is not available on non-Darwin platforms. Fix this.
2025-10-12 18:03:57 +02:00
Tim De Jong 2f108508fa Fixed DatabaseSnapshotTests on non-darwin platforms 2025-10-12 18:03:57 +02:00
Tim De Jong 5513eab099 Fixed the tests in DatabaseQueueTests.swift 2025-10-12 18:03:57 +02:00
Tim De Jong 2ad2d20a89 Fixed the unit tests in DatabasePoolConcurrencyTests. 2025-10-12 18:03:57 +02:00
Tim De Jong dd90fe6e62 Ignore ValueObservationRecorderTests.swift on non-Darwin platforms. 2025-10-12 18:03:57 +02:00
Tim De Jong 691207567a Ignore FailureTestCase.swift entirely on non-Darwin platforms for now. 2025-10-12 18:03:57 +02:00
Tim De Jong c7f1dd7470 Fixed import in CGFloatTests.swift to work under non-Darwin platforms. 2025-10-12 18:03:57 +02:00
Tim De Jong 8e5b9ca9bd Fixed UUID fromDatabaseValue for non-Darwin platforms 2025-10-12 18:03:56 +02:00
Tim De Jong dc7d47c066 Fixed databaseValue build for non-Darwin platforms. 2025-10-12 18:03:56 +02:00
Tim De Jong 14f60ad48f Fixed fromDatabaseValue build under non-Darwin platforms 2025-10-12 18:03:56 +02:00
Tim De Jong e758fde941 Removed #if !os(Linux) in NSString.swift, NSData.swift and Date.swift. 2025-10-12 17:43:25 +02:00
Tim De Jong 7477e1cff8 Removed the #if !os(Linux) compiler directive in the Decimal extension, as it compiles fine under swift 6 2025-10-12 17:43:15 +02:00
Tim De Jong 2d6fe172c3 Import Foundation for CGFloat on non-Darwin platforms 2025-10-12 17:43:02 +02:00
Tim De Jong 0526853dde Fixed some linker errors caused by WAL absence on Linux. 2025-10-12 17:42:49 +02:00
Gwendal Roué a60810f28e Merge pull request #1819 from groue/dev/SQLCipher-cleanup
Accept multiple SQLCipher libraries
2025-10-12 15:46:52 +02:00
Gwendal Roué c35095c6da Enable more tests 2025-10-12 14:58:06 +02:00
Gwendal Roué f878d99733 Use SQLITE_HAS_CODEC instead of GRDBCIPHER when testing for SQLCipher availability
GRDBCIPHER is now just a marker for importing SQLCipher with CocoaPods.

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

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

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

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

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

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

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

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

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

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

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

Signed-off-by: dependabot[bot] <support@github.com>
2025-08-18 09:08:53 +00:00
378 changed files with 8643 additions and 6275 deletions

No files matched your search

+43 -43
View File
@@ -1,4 +1,4 @@
# https://github.com/actions/runner-images/blob/main/images/macos/macos-14-Readme.md
# https://github.com/actions/runner-images/blob/main/images/macos/macos-15-Readme.md
name: "GRDB CI"
@@ -40,20 +40,20 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
destination: "platform=macOS"
name: "macOS"
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
destination: "OS=18.1,name=iPhone 16 Pro"
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
destination: "OS=18.5,name=iPhone 16 Pro"
name: "iOS"
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
destination: "OS=18.1,name=Apple TV"
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
destination: "OS=18.5,name=Apple TV"
name: "tvOS"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: ${{ matrix.name }}
run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project GRDB.xcodeproj -scheme GRDB -destination "${{ matrix.destination }}" OTHER_SWIFT_FLAGS='$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' GCC_PREPROCESSOR_DEFINITIONS='$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' clean test
SPM:
@@ -66,11 +66,11 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
name: "Xcode 16.1"
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
name: "Xcode 16.4"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: ${{ matrix.name }}
run: make test_SPM test_install_SPM
SQLCipher3:
@@ -83,11 +83,11 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
name: "Xcode 16.1"
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
name: "Xcode 16.4"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher3Encrypted
SQLCipher4:
@@ -100,30 +100,30 @@ 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:
name: CustomSQLite
runs-on: ${{ matrix.runsOn }}
env:
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
include:
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
name: "Xcode 16.1"
steps:
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: make test_framework_GRDBCustomSQLiteOSX
# CustomSQLite:
# name: CustomSQLite
# runs-on: ${{ matrix.runsOn }}
# env:
# DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
# timeout-minutes: 60
# strategy:
# fail-fast: false
# matrix:
# include:
# - xcode: "Xcode_16.4.app"
# runsOn: macOS-15
# name: "Xcode 16.4"
# steps:
# - uses: actions/checkout@v5
# - name: ${{ matrix.name }}
# run: make test_framework_GRDBCustomSQLiteOSX
XCFramework:
name: XCFramework
runs-on: ${{ matrix.runsOn }}
@@ -134,11 +134,11 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
name: "Xcode 16.1"
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
name: "Xcode 16.4"
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: ${{ matrix.name }}
run: make test_universal_xcframework
+1 -1
View File
@@ -2,4 +2,4 @@ version: 1
builder:
configs:
- documentation_targets: [GRDB]
swift_version: 6.0
swift_version: 6.1
+7
View File
@@ -0,0 +1,7 @@
{
"editor.formatOnSave": false,
"editor.insertSpaces": true,
"editor.tabSize": 4,
"editor.detectIndentation": false,
"editor.trimAutoWhitespace": false
}
+95 -1
View File
@@ -7,6 +7,12 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 7.x Releases
- `7.12.x` Releases - [7.12.0](#7120)
- `7.11.x` Releases - [7.11.0](#7110) - [7.11.1](#7111)
- `7.10.x` Releases - [7.10.0](#7100)
- `7.9.x` Releases - [7.9.0](#790)
- `7.8.x` Releases - [7.8.0](#780)
- `7.7.x` Releases - [7.7.0](#770) - [7.7.1](#771)
- `7.6.x` Releases - [7.6.0](#760) - [7.6.1](#761)
- `7.5.x` Releases - [7.5.0](#750)
- `7.4.x` Releases - [7.4.0](#740) - [7.4.1](#741)
@@ -138,6 +144,94 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 7.12.0
Released November 1, 2026
- **New**: Add support for Strings that contain the NUL character by [@groue](https://github.com/groue) and [@nesevis](https://github.com/nesevis) in [#1885](https://github.com/groue/GRDB.swift/pull/1885)
- **New**: Keep SQLite's error message when a database fails to open by [@builtbysharath](https://github.com/builtbysharath) in [#1889](https://github.com/groue/GRDB.swift/pull/1889)
- **Fixed**: Fix doubled word in doc comment by [@latent-9](https://github.com/latent-9) in [#1876](https://github.com/groue/GRDB.swift/pull/1876)
- **Fixed**: Fix an accidentally quadratic behavior in SQLite statement compilation by [@groue](https://github.com/groue) and [@guidedways](https://github.com/guidedways) in [#1881](https://github.com/groue/GRDB.swift/pull/1881)
- **Fixed**: Work around an SQLite bug in WAL snapshot ordering by [@groue](https://github.com/groue) and [@vburojevic](https://github.com/vburojevic) in [#1884](https://github.com/groue/GRDB.swift/pull/1884)
- **Fixed**: Fix upsert for WITHOUT ROWID tables with an INTEGER primary key by [@nesevis](https://github.com/nesevis) in [#1879](https://github.com/groue/GRDB.swift/pull/1879)
- **Fixed**: Support for statement recompilation after the columns are modified in the database schema by [@groue](https://github.com/groue) in [#1893](https://github.com/groue/GRDB.swift/pull/1893)
- **Fixed**: Fix SharedValueObservation deadlock, ordering, and cancellation by [@groue](https://github.com/groue) in [#1894](https://github.com/groue/GRDB.swift/pull/1894)
## 7.11.1
Released June 18, 2026
- **New**: Make migration registration an O(1) operation [@MarkusSintonen](https://github.com/MarkusSintonen) in [#1869](https://github.com/groue/GRDB.swift/pull/1869)
## 7.11.0
Released June 1, 2026
- **New**: Add option to disable database change filtering in `TransactionObserver` by [@simolus3](https://github.com/simolus3) in [#1864](https://github.com/groue/GRDB.swift/pull/1864)
- **Fixed**: Fix upsert for WITHOUT ROWID tables by [@groue](https://github.com/groue) in [#1858](https://github.com/groue/GRDB.swift/pull/1858)
## 7.10.0
Released February 15, 2026
- **Documentation fixes** by [@bellebethcooper](https://github.com/bellebethcooper), [@Cykelero](https://github.com/Cykelero), and [@leejungyeob](https://github.com/leejungyeob) in [#1842](https://github.com/groue/GRDB.swift/pull/1842), [#1846](https://github.com/groue/GRDB.swift/pull/1846), [#1848](https://github.com/groue/GRDB.swift/pull/1848)
- **New**: Linux adjustments by [@thinkpractice](https://github.com/thinkpractice) in [#1825](https://github.com/groue/GRDB.swift/pull/1825)
- **New**: SQLCipher adjustments by [@R4N](https://github.com/R4N) in [#1845](https://github.com/groue/GRDB.swift/pull/1845)
- **New**: Android and Windows adjustments by [@marcprux](https://github.com/marcprux) in [#1849](https://github.com/groue/GRDB.swift/pull/1849), [#1850](https://github.com/groue/GRDB.swift/pull/1850)
- **New**: Configure whether UPSERT should update all columns, or no column by [@groue](https://github.com/groue) in [#1852](https://github.com/groue/GRDB.swift/pull/1852)
## 7.9.0
Released December 13, 2025
- **Breaking Change**: Simplify the compiler checks for the availability of SQLite snapshots by [@groue](https://github.com/groue) in [#1826](https://github.com/groue/GRDB.swift/pull/1826)
This change aims at easing Linux and Android compatibility.
**The library requirements are raised to Swift 6.1+, Xcode 16.3+.**
- **Breaking Change**: Accept multiple SQLCipher libraries by [@groue](https://github.com/groue) in [#1819](https://github.com/groue/GRDB.swift/pull/1819)
This change aims at easing building GRDB against various SQLCipher flavors.
**The compiler flag that enables new GRDB APIs for SQLCipher is now `SQLITE_HAS_CODEC`.**
- **Fixed**: Fix cancellation of async tasks that use the FTS5 full-text engine by [@groue](https://github.com/groue) in [#1839](https://github.com/groue/GRDB.swift/pull/1839)
This workarounds an [SQLite bug](https://sqlite.org/forum/forumpost/95413eb410) that would trigger a GRDB crash, and improves the robustness of the library regarding database accesses cancellation and database interruption.
- **New**: Improve the ergonomics of `DatabaseMigrator.registerMigration(_:foreignKeyChecks:merging:migrate)`, introduced in [#1818](https://github.com/groue/GRDB.swift/pull/1818), by accepting that the name of the merged migration is included in the set of merged migrations:
```swift
// Used to fail, now OK:
migrator.registerMigration("v3", merging: ["v1", "v2", "v3"]) { ... }
// ~~~~ ~~~~
// The above code is equivalent to:
migrator.registerMigration("v3", merging: ["v1", "v2"]) { ... }
```
## 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
@@ -4347,7 +4441,7 @@ Released April 3, 2017
**Breaking Changes**
- SQLite C API is now available right from the GRBD module: you don't need any longer to import `SQLiteiPhoneOS` module et al (see documentation for [Raw SQLite Pointers](https://github.com/groue/GRDB.swift#raw-sqlite-pointers)).
- SQLite C API is now available right from the GRDB module: you don't need any longer to import `SQLiteiPhoneOS` module et al (see documentation for [Raw SQLite Pointers](https://github.com/groue/GRDB.swift#raw-sqlite-pointers)).
- The [manual installation procedure for WatchOS extensions](https://github.com/groue/GRDB.swift#installation) has changed.
- [Carthage](https://github.com/Carthage/Carthage) is no longer supported. At the present time it is unable to support the various frameworks built by GRDB (system SQLite, SQLCipher, custom SQLite builds, etc.)
@@ -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"
@@ -56,7 +56,7 @@ import GRDB
// Start observing the database.
// Previous observation, if any, is cancelled.
cancellable = observation.start(in: appDatabase.reader) { error in
cancellable = observation.start(in: appDatabase.reader, scheduling: .immediate) { error in
// Handle error
} onChange: { [unowned self] players in
self.players = players
+3 -3
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '7.6.1'
s.version = '7.12.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
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1400"
LastUpgradeVersion = "2600"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
+27 -8
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
#if !canImport(Darwin)
@@ -87,7 +90,7 @@ public struct Configuration: Sendable {
/// with the number of snapshots.
///
/// The default configuration label is nil.
public var label: String? = nil
public var label: String?
/// A boolean value indicating whether SQLite 3.29+ interprets
/// double-quoted strings as string literals when they does not match any
@@ -329,7 +332,7 @@ public struct Configuration: Sendable {
/// The behavior in case of SQLITE_BUSY error, for read-only connections.
/// If nil, GRDB picks a default one.
var readonlyBusyMode: Database.BusyMode? = nil
var readonlyBusyMode: Database.BusyMode?
/// The maximum number of concurrent reader connections.
///
@@ -387,7 +390,7 @@ public struct Configuration: Sendable {
/// ``qos`` property.
///
/// The default is nil.
public var targetQueue: DispatchQueue? = nil
public var targetQueue: DispatchQueue?
/// The target dispatch queue for write database accesses.
///
@@ -395,7 +398,7 @@ public struct Configuration: Sendable {
/// by ``targetQueue``.
///
/// The default is nil.
public var writeTargetQueue: DispatchQueue? = nil
public var writeTargetQueue: DispatchQueue?
#if os(iOS)
/// A boolean value indicating whether the database connection releases
@@ -421,6 +424,22 @@ public struct Configuration: Sendable {
/// reveals that a lot of time is spent opening new SQLite connections.
public var persistentReadOnlyConnections = false
// MARK: - Database Schema
/// A custom schema source.
///
/// The use case for a custom schema source is enabling GRDB features that
/// would not work with the built-in schema introspection that is provided
/// by SQLite. For example, a custom schema source can help record types
/// that read or write in a database view.
///
/// The schema source is automatically disabled during database
/// migrations performed by ``DatabaseMigrator``: those access the raw
/// SQLite schema, unaltered. If a migration needs a schema source,
/// you may call ``Database/withSchemaSource(_:execute:)`` from within
/// the body of a migration.
public var schemaSource: (any DatabaseSchemaSource)?
// MARK: - Factory Configuration
/// Creates a factory configuration.
+257
View File
@@ -0,0 +1,257 @@
#if SQLITE_HAS_CODEC
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif SQLCipher
import SQLCipher
#else
#error("No SQLCipher library configured")
#endif
import Foundation
extension Database {
/// Destination of SQLCipher logs.
///
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_log>
public struct SQLCipherLogTarget: Sendable {
public var rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public static let stdout = Self(rawValue: "stdout")
public static let stderr = Self(rawValue: "stderr")
public static let device = Self(rawValue: "device")
public static func file(_ path: String) -> Self { Self(rawValue: path) }
}
/// Granularitly of SQLCipher log outputs.
///
/// Each log level is more verbose than the last. With ``debug`` and
/// ``trace`` the logging system will generate a significant log volume.
///
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_log_level>
///
/// ## Topics
///
/// ### Log Levels
///
/// - ``none``
/// - ``error``
/// - ``warn``
/// - ``info``
/// - ``debug``
/// - ``trace``
public struct SQLCipherLogLevel: RawRepresentable, Sendable {
public var rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public static let none = Self(rawValue: "NONE")
public static let error = Self(rawValue: "ERROR")
public static let warn = Self(rawValue: "WARN")
public static let info = Self(rawValue: "INFO")
public static let debug = Self(rawValue: "DEBUG")
public static let trace = Self(rawValue: "TRACE")
}
/// - Returns: the SQLCipher version
///
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_version>
public var cipherVersion: String {
get throws { try String.fetchOne(self, sql: "PRAGMA cipher_version")! }
}
/// - Returns: the SQLCipher fips status: 1 for fips mode, 0 for non-fips mode
/// The FIPS status will not be initialized until the database connection has been keyed
///
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_fips_status>
public var cipherFipsStatus: String? {
get throws { try String.fetchOne(self, sql: "PRAGMA cipher_fips_status") }
}
/// - Returns: The compiled crypto provider.
/// The database must be keyed before requesting the name of the crypto provider.
///
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_provider>
public var cipherProvider: String? {
get throws { try String.fetchOne(self, sql: "PRAGMA cipher_provider") }
}
/// - Returns: the version number provided from the compiled crypto provider.
/// This value, if known, is available only after the database has been keyed.
///
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_provider_version>
public var cipherProviderVersion: String? {
get throws { try String.fetchOne(self, sql: "PRAGMA cipher_provider_version") }
}
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
///
/// Call this method from `Configuration.prepareDatabase`,
/// as in the example below:
///
/// var config = Configuration()
/// config.prepareDatabase { db in
/// try db.usePassphrase("secret")
/// }
public func usePassphrase(_ passphrase: String) throws {
guard var data = passphrase.data(using: .utf8) else {
throw DatabaseError(message: "invalid passphrase")
}
defer {
data.resetBytes(in: 0..<data.count)
}
try usePassphrase(data)
}
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
///
/// Call this method from `Configuration.prepareDatabase`,
/// as in the example below:
///
/// var config = Configuration()
/// config.prepareDatabase { db in
/// try db.usePassphrase(passphraseData)
/// }
public func usePassphrase(_ passphrase: Data) throws {
let code = passphrase.withUnsafeBytes {
sqlite3_key(sqliteConnection, $0.baseAddress, CInt($0.count))
}
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
}
}
/// Changes the passphrase used by an SQLCipher encrypted database.
public func changePassphrase(_ passphrase: String) throws {
guard var data = passphrase.data(using: .utf8) else {
throw DatabaseError(message: "invalid passphrase")
}
defer {
data.resetBytes(in: 0..<data.count)
}
try changePassphrase(data)
}
/// Changes the passphrase used by an SQLCipher encrypted database.
public func changePassphrase(_ passphrase: Data) throws {
// FIXME: sqlite3_rekey is discouraged.
//
// https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320
//
// > We (Zetetic) have been discouraging the use of sqlite3_rekey in
// > favor of attaching a new database with the desired encryption
// > options and using sqlcipher_export() to migrate the contents and
// > schema of the original db into the new one:
// > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/
let code = passphrase.withUnsafeBytes {
sqlite3_rekey(sqliteConnection, $0.baseAddress, CInt($0.count))
}
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: lastErrorMessage)
}
}
/// When using Commercial or Enterprise SQLCipher packages you must call
/// `PRAGMA cipher_license` with a valid license code prior to executing
/// cryptographic operations on an encrypted database.
/// Failure to provide a license code, or use of an expired trial code,
/// will result in an `SQLITE_AUTH (23)` error code reported from the SQLite API
/// License Codes will activate SQLCipher Commercial or Enterprise packages
/// from Zetetic: <https://www.zetetic.net/sqlcipher/buy/>
/// 15-day free trials are available by request: <https://www.zetetic.net/sqlcipher/trial/>
///
/// Call this method from ``Configuration/prepareDatabase(_:)``,
/// as in the example below:
///
/// ```swift
/// var config = Configuration()
/// config.prepareDatabase { db in
/// try db.applySQLCipherLicense(license)
/// }
/// ```
///
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_license>
/// - Parameter license: base64 SQLCipher license code to activate SQLCipher commercial
public func applySQLCipherLicense(_ license: String) throws {
try execute(sql: "PRAGMA cipher_license = '\(license)'")
}
/// Instructs SQLCipher to log internal debugging and operational information.
///
/// The supplied ``logLevel`` determines the granularity of the logs output.
///
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_log>
/// - Parameter logLevel: The granularity to use for the logging system - defaults to `DEBUG`.
/// - Parameter target: The destination of SQLCipher logs - defaults to `.device`.
public func enableCipherLogging(
logLevel: SQLCipherLogLevel = .debug,
target: SQLCipherLogTarget = .device
) throws {
// Pragma do not support SQL arguments. We need to generate SQL that contains literal values:
// PRAGMA cipher_log = '/path/to/file'
// PRAGMA cipher_log_level = 'xxx'
let context = SQLGenerationContext(self, argumentsSink: .literalValues)
try execute(sql: SQL("PRAGMA cipher_log = \(target.rawValue)").sql(context))
try execute(sql: SQL("PRAGMA cipher_log_level = \(logLevel.rawValue.uppercased())").sql(context))
}
/// Instructs SQLCipher to disable logging internal debugging and operational information.
///
/// See <https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_log>
public func disableCipherLogging() throws {
try execute(sql: "PRAGMA cipher_log_level = NONE")
}
internal func validateSQLCipher() throws {
// https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688
//
// > In order to avoid situations where SQLite might be used
// > improperly at runtime, we strongly recommend that
// > applications institute a runtime test to ensure that the
// > application is actually using SQLCipher on the active
// > connection.
if try String.fetchOne(self, sql: "PRAGMA cipher_version") == nil {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: """
GRDB is not linked against SQLCipher. \
Check https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688
""")
}
}
internal func dropAllDatabaseObjects() throws {
// SQLCipher does not support the backup API:
// https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631
// So we'll drop all database objects one after the other.
// Prevent foreign keys from messing with drop table statements
let foreignKeysEnabled = try Bool.fetchOne(self, sql: "PRAGMA foreign_keys")!
if foreignKeysEnabled {
try execute(sql: "PRAGMA foreign_keys = OFF")
}
try throwingFirstError(
execute: {
// Remove all database objects, one after the other
try inTransaction {
let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'"
while let row = try Row.fetchOne(self, sql: sql) {
let type: String = row["type"]
let name: String = row["name"]
try execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)")
}
return .commit
}
},
finally: {
// Restore foreign keys if needed
if foreignKeysEnabled {
try execute(sql: "PRAGMA foreign_keys = ON")
}
})
}
}
#endif
File diff suppressed because it is too large. Load diff
+29 -5
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
@@ -387,7 +390,7 @@ extension SQLStatementCursor: Cursor {
let baseAddress = buffer.baseAddress! // never nil because the buffer contains the trailing \0.
// Compile next statement
var statementEnd: UnsafePointer<CChar>? = nil
var statementEnd: UnsafePointer<CChar>?
let statement = try Statement(
database: database,
statementStart: baseAddress + offset,
@@ -510,6 +513,27 @@ extension Database {
publicStatementArguments: configuration.publicStatementArguments)
}
/// Always throws an error
func statementCompilationDidFail(
at statementStart: UnsafePointer<CChar>,
withResultCode resultCode: CInt
) throws -> Never {
switch ResultCode(rawValue: resultCode) {
case .SQLITE_INTERRUPT, .SQLITE_ABORT:
// The only error that a user sees when a Task is cancelled
// is CancellationError.
try suspensionMutex.load().checkCancellation()
default:
break
}
// Throw compilation failure
throw DatabaseError(
resultCode: resultCode,
message: lastErrorMessage,
sql: String(cString: statementStart))
}
private func checkForAutocommitTransition() {
if sqlite3_get_autocommit(sqliteConnection) == 0 {
if autocommitState == .on {
+118 -128
View File
@@ -1,10 +1,14 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
import GRDBSQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
@@ -113,6 +117,11 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``resumeNotification``
/// - ``suspendNotification``
///
/// ### The Schema Source
///
/// - ``schemaSource``
/// - ``withSchemaSource(_:execute:)``
///
/// ### Other Database Operations
///
/// - ``add(tokenizer:)``
@@ -169,7 +178,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// connection has been opened is an SQLite misuse, and has no effect.
///
/// Related SQLite documentation: <https://www.sqlite.org/errlog.html>
nonisolated(unsafe) public static var logError: LogErrorFunction? = nil {
nonisolated(unsafe) public static var logError: LogErrorFunction? {
didSet {
if logError != nil {
_registerErrorLogCallback { (_, code, message) in
@@ -187,6 +196,19 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// The database configuration.
public let configuration: Configuration
/// The current schema source.
///
/// By default, it is the ``Configuration/schemaSource``
/// of ``configuration``. To modify the schema source,
/// use ``withSchemaSource(_:execute:)``.
///
/// The schema source is automatically disabled (nil) during database
/// migrations performed by ``DatabaseMigrator``: those access the raw
/// SQLite schema, unaltered. If a migration needs a schema source,
/// you may call ``Database/withSchemaSource(_:execute:)`` from within
/// the body of a migration.
public internal(set) var schemaSource: (any DatabaseSchemaSource)?
/// A description of this database connection.
///
/// The returned string is based on the ``Configuration/label``
@@ -442,6 +464,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
self.description = description
self.configuration = configuration
self.schemaSource = configuration.schemaSource
self.path = path
// We do not report read-only transactions to transaction observers, so
@@ -459,7 +482,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
@@ -471,8 +494,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// https://www.sqlite.org/c3ref/close.html
// > Calling sqlite3_close() or sqlite3_close_v2() with a NULL
// > pointer argument is a harmless no-op.
//
// Read the error message before the connection is closed.
let message = sqliteConnection.map { String(cString: sqlite3_errmsg($0)) }
_ = sqlite3_close(sqliteConnection) // ignore result code
throw DatabaseError(resultCode: code)
throw DatabaseError(resultCode: code, message: message)
}
guard let sqliteConnection else {
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
@@ -619,24 +645,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
#if SQLITE_HAS_CODEC
private func validateSQLCipher() throws {
// https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688
//
// > In order to avoid situations where SQLite might be used
// > improperly at runtime, we strongly recommend that
// > applications institute a runtime test to ensure that the
// > application is actually using SQLCipher on the active
// > connection.
if try String.fetchOne(self, sql: "PRAGMA cipher_version") == nil {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: """
GRDB is not linked against SQLCipher. \
Check https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688
""")
}
}
#endif
private func validateFormat() throws {
// Users are surprised when they open a picture as a database and
// see no error (https://github.com/groue/GRDB.swift/issues/54).
@@ -806,7 +814,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.
@@ -841,7 +849,16 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
readOnlyDepth -= 1
assert(readOnlyDepth >= 0, "unbalanced endReadOnly()")
if readOnlyDepth == 0 {
try internalCachedStatement(sql: "PRAGMA query_only = 0").execute()
// We MUST ignore interruptions when we leave the read-only mode,
// otherwise user could not write with this database
// connection again.
//
// It's OK to ignore interruption, since interruption is
// concurrent and we can pretend it occurred before or after
// the PRAGMA.
try ignoringInterruption {
try internalCachedStatement(sql: "PRAGMA query_only = 0").execute()
}
}
}
@@ -1278,6 +1295,31 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
return try value()
}
/// Returns the result of `value`. If `value` throws an interruption
/// error, it is retried a second time.
func ignoringInterruption<T>(_ value: () throws -> T) rethrows -> T {
do {
return try value() // swiftlint:disable:next statement_position
}
catch is CancellationError,
DatabaseError.SQLITE_INTERRUPT,
DatabaseError.SQLITE_ABORT
{
// Maybe we were unlucky, and user has interrupted the database
// during `value` execution.
//
// Another possible cause for this error is the FTS5 bug
// described at <https://sqlite.org/forum/forumpost/137c7662b3>,
// which leaves the database in a sticky interrupted state.
// To workaround this bug, we must leave the interrupted state
// before retrying:
resetAllPreparedStatements()
// Retry
return try value()
}
}
/// Support for `checkForSuspensionViolation(from:)`
private func journalMode() throws -> String {
if let journalMode = journalModeCache {
@@ -1286,7 +1328,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) }
@@ -1483,7 +1525,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// Now that transaction has begun, we'll rollback in case of error.
// But we'll throw the first caught error, so that user knows
// what happened.
var firstError: Error? = nil
var firstError: Error?
let needsRollback: Bool
do {
let completion = try operations()
@@ -1626,7 +1668,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()
@@ -1742,9 +1784,18 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// which rollback errors should be ignored, and which rollback errors
// should be exposed to the library user.
if isInsideTransaction {
try execute(sql: "ROLLBACK TRANSACTION")
// We MUST ignore interruptions during the rollback, otherwise
// we could leave a transaction open, and trigger a fatal error in
// `SerializedDatabase.preconditionNoUnsafeTransactionLeft`.
//
// It's OK to ignore interruption, since interruption is
// concurrent and we can pretend it occurred before or after
// the rollback.
try ignoringInterruption {
try execute(sql: "ROLLBACK TRANSACTION")
}
}
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
assert(!isInsideTransaction)
}
/// Commits a database transaction.
@@ -1757,6 +1808,19 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
}
/// Resets all prepared statements.
///
/// This method helps clearing the interrupted state, as a workaround
/// for https://sqlite.org/forum/forumpost/137c7662b3, discovered
/// in https://github.com/groue/GRDB.swift/issues/1838.
func resetAllPreparedStatements() {
var stmt: SQLiteStatement? = sqlite3_next_stmt(sqliteConnection, nil)
while stmt != nil {
sqlite3_reset(stmt)
stmt = sqlite3_next_stmt(sqliteConnection, stmt)
}
}
// MARK: - Memory Management
/// Frees as much memory as possible.
@@ -1774,35 +1838,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
func erase() throws {
#if SQLITE_HAS_CODEC
// SQLCipher does not support the backup API:
// https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631
// So we'll drop all database objects one after the other.
// Prevent foreign keys from messing with drop table statements
let foreignKeysEnabled = try Bool.fetchOne(self, sql: "PRAGMA foreign_keys")!
if foreignKeysEnabled {
try execute(sql: "PRAGMA foreign_keys = OFF")
}
try throwingFirstError(
execute: {
// Remove all database objects, one after the other
try inTransaction {
let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'"
while let row = try Row.fetchOne(self, sql: sql) {
let type: String = row["type"]
let name: String = row["name"]
try execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)")
}
return .commit
}
},
finally: {
// Restore foreign keys if needed
if foreignKeysEnabled {
try execute(sql: "PRAGMA foreign_keys = ON")
}
})
try dropAllDatabaseObjects()
#else
try DatabaseQueue().backup(to: self)
#endif
@@ -1925,79 +1961,33 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
@available(*, unavailable)
extension Database: Sendable { }
#if SQLITE_HAS_CODEC
extension Database {
// MARK: - Encryption
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
///
/// Call this method from `Configuration.prepareDatabase`,
/// as in the example below:
///
/// var config = Configuration()
/// config.prepareDatabase { db in
/// try db.usePassphrase("secret")
/// }
public func usePassphrase(_ passphrase: String) throws {
guard var data = passphrase.data(using: .utf8) else {
throw DatabaseError(message: "invalid passphrase")
}
defer {
data.resetBytes(in: 0..<data.count)
}
try usePassphrase(data)
}
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
///
/// Call this method from `Configuration.prepareDatabase`,
/// as in the example below:
///
/// var config = Configuration()
/// config.prepareDatabase { db in
/// try db.usePassphrase(passphraseData)
/// }
public func usePassphrase(_ passphrase: Data) throws {
let code = passphrase.withUnsafeBytes {
sqlite3_key(sqliteConnection, $0.baseAddress, CInt($0.count))
}
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
}
}
/// Changes the passphrase used by an SQLCipher encrypted database.
public func changePassphrase(_ passphrase: String) throws {
guard var data = passphrase.data(using: .utf8) else {
throw DatabaseError(message: "invalid passphrase")
}
defer {
data.resetBytes(in: 0..<data.count)
}
try changePassphrase(data)
}
/// Changes the passphrase used by an SQLCipher encrypted database.
public func changePassphrase(_ passphrase: Data) throws {
// FIXME: sqlite3_rekey is discouraged.
/// 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://github.com/ccgus/fmdb/issues/547#issuecomment-259219320
// > https://sqlite.org/c3ref/changes.html
// > Changes to a view that are intercepted by INSTEAD OF triggers are not counted.
//
// > We (Zetetic) have been discouraging the use of sqlite3_rekey in
// > favor of attaching a new database with the desired encryption
// > options and using sqlcipher_export() to migrate the contents and
// > schema of the original db into the new one:
// > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/
let code = passphrase.withUnsafeBytes {
sqlite3_rekey(sqliteConnection, $0.baseAddress, CInt($0.count))
}
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: lastErrorMessage)
// 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
}
}
}
#endif
extension Database {
+1 -1
View File
@@ -12,7 +12,7 @@ public struct DatabaseBackupProgress: Sendable {
/// It is the result of the `sqlite3_backup_pagecount` function.
public let totalPageCount: Int
/// The number of of backed up pages.
/// The number of backed up pages.
///
/// It is equal to `totalPageCount - remainingPageCount`.
public var completedPageCount: Int {
+27 -20
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
@@ -53,12 +56,21 @@ public final class DatabaseCollation: Identifiable, Sendable {
}
}
/// Feeds the `xCompare` parameter of sqlite3_create_collation_v2
/// <https://www.sqlite.org/c3ref/create_collation.html>
typealias XCompare = @Sendable (
_ length1: CInt,
_ buffer1: UnsafeRawPointer,
_ length2: CInt,
_ buffer2: UnsafeRawPointer
) -> CInt
/// The identifier of the collation.
public var id: ID { ID(name: name) }
/// The name of the collation.
public let name: String
let function: @Sendable (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
let xCompare: XCompare
/// Creates a collation.
///
@@ -75,21 +87,16 @@ public final class DatabaseCollation: Identifiable, Sendable {
/// - parameters:
/// - name: The collation name.
/// - function: A function that compares two strings.
public init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
public convenience init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
self.init(name, xCompare: { (length1, buffer1, length2, buffer2) in
let string1 = String(decoding: UnsafeRawBufferPointer(start: buffer1, count: Int(length1)), as: UTF8.self)
let string2 = String(decoding: UnsafeRawBufferPointer(start: buffer2, count: Int(length2)), as: UTF8.self)
return CInt(function(string1, string2).rawValue)
})
}
init(_ name: String, xCompare: @escaping XCompare) {
self.name = name
self.function = { (length1, buffer1, length2, buffer2) in
// Buffers are not C strings: they do not end with \0.
let string1 = String(
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped),
length: Int(length1),
encoding: .utf8,
freeWhenDone: false)!
let string2 = String(
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped),
length: Int(length2),
encoding: .utf8,
freeWhenDone: false)!
return function(string1, string2)
}
self.xCompare = xCompare
}
}
+7 -4
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
+61 -24
View File
@@ -1,12 +1,17 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
/// A custom SQL function or aggregate.
///
/// ## Topics
@@ -82,20 +87,45 @@ 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(var string):
string.withSQLiteText {
sqlite3_result_text(context, $0, $1, SQLITE_TRANSIENT)
}
case .blob(let data):
data.withUnsafeBytes {
sqlite3_result_blob(context, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
}
}
}
}
init(
_ name: String,
argumentCount: Int? = nil,
pure: Bool = false,
xFunc: @escaping XFunc)
{
self.id = ID(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
self.isPure = pure
self.kind = .function { (argc, argv) in
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
}
return try function(arguments)
}
self.kind = .function(xFunc)
}
/// Creates an SQL aggregate function.
@@ -256,11 +286,10 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
private class FunctionDefinition {
let compute: (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?
init(compute: @escaping (CInt, UnsafeMutablePointer<OpaquePointer?>?)
throws -> (any DatabaseValueConvertible)?)
let xFunc: XFunc
init(xFunc: @escaping XFunc)
{
self.compute = compute
self.xFunc = xFunc
}
}
@@ -283,11 +312,19 @@ public final class DatabaseFunction: Identifiable, Sendable {
}
}
/// Feeds the `xFunc` parameter of sqlite3_create_function_v2
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
typealias XFunc = @Sendable (
_ argc: CInt,
_ argv: UnsafeMutablePointer<OpaquePointer?>,
_ context: OpaquePointer?
) throws -> Void
/// A function kind: an "SQL function" or an "aggregate".
/// See <http://sqlite.org/capi3ref.html#sqlite3_create_function>
private enum Kind: Sendable {
/// A regular function: SELECT f(1)
case function(@Sendable (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
case function(XFunc)
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
case aggregate(@Sendable () -> any DatabaseAggregate)
@@ -296,8 +333,8 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
var definition: AnyObject {
switch self {
case .function(let compute):
return FunctionDefinition(compute: compute)
case .function(let xFunc):
return FunctionDefinition(xFunc: xFunc)
case .aggregate(let makeAggregate):
return AggregateDefinition(makeAggregate: makeAggregate)
}
@@ -312,9 +349,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)
}
@@ -414,8 +449,10 @@ public final class DatabaseFunction: Identifiable, Sendable {
sqlite3_result_int64(sqliteContext, int64)
case .double(let double):
sqlite3_result_double(sqliteContext, double)
case .string(let string):
sqlite3_result_text(sqliteContext, string, -1, SQLITE_TRANSIENT)
case .string(var string):
string.withSQLiteText {
sqlite3_result_text(sqliteContext, $0, $1, SQLITE_TRANSIENT)
}
case .blob(let data):
data.withUnsafeBytes {
sqlite3_result_blob(sqliteContext, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
@@ -464,7 +501,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.
+23 -8
View File
@@ -361,8 +361,13 @@ extension DatabasePool: DatabaseReader {
return try await readerPool.get { reader in
try await reader.execute { db in
defer {
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
// Commit or rollback, but make sure we leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
assert(!db.isInsideTransaction)
}
// The block isolation comes from the DEFERRED transaction.
@@ -387,8 +392,13 @@ extension DatabasePool: DatabaseReader {
// Second async jump because that's how `Pool.async` has to be used.
reader.async { db in
defer {
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
// Commit or rollback, but make sure we leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
assert(!db.isInsideTransaction)
releaseReader(.reuse)
}
@@ -551,8 +561,13 @@ extension DatabasePool: DatabaseReader {
let (reader, releaseReader) = try readerPool.get()
reader.async { db in
defer {
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
// Commit or rollback, but make sure we leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
assert(!db.isInsideTransaction)
releaseReader(.reuse)
}
@@ -669,7 +684,7 @@ extension DatabasePool: DatabaseReader {
// MARK: - WAL Snapshot Transactions
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
/// Returns a long-lived WAL snapshot transaction on a reader connection.
func walSnapshotTransaction() throws -> WALSnapshotTransaction {
guard let readerPool else {
@@ -935,7 +950,7 @@ extension DatabasePool {
purpose: "snapshot.\(databaseSnapshotCountMutex.increment())")
}
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
/// Creates a database snapshot that allows concurrent accesses to an
/// unchanging database content, as it exists at the moment the snapshot
/// is created.
+14 -4
View File
@@ -248,8 +248,13 @@ extension DatabaseQueue: DatabaseReader {
) {
writer.async { db in
defer {
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
// Commit or rollback, but make sure we leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
assert(!db.isInsideTransaction)
try? db.endReadOnly()
}
@@ -297,8 +302,13 @@ extension DatabaseQueue: DatabaseReader {
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
defer {
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
// Commit or rollback, but make sure we leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
assert(!db.isInsideTransaction)
try? db.endReadOnly()
}
+41 -5
View File
@@ -41,7 +41,8 @@
/// - ``isModified(byEventsOfKind:)``
/// - ``isModified(by:)``
public struct DatabaseRegion: Sendable {
private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
/// Nil means that the region is the full database.
private var tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) {
self.tableRegions = tableRegions
@@ -77,19 +78,26 @@ public struct DatabaseRegion: Sendable {
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)])
}
/// Full columns in a table: (some columns in a table) × (all rows)
/// Some columns from all rows in a table.
init(table: String, columns: Set<String>) {
let table = CaseInsensitiveIdentifier(rawValue: table)
let columns = Set(columns.map(CaseInsensitiveIdentifier.init))
self.init(tableRegions: [table: TableRegion(columns: columns, rowIds: nil)])
}
/// Full rows in a table: (all columns in a table) × (some rows)
/// All columns from some rows in a table.
init(table: String, rowIds: Set<Int64>) {
let table = CaseInsensitiveIdentifier(rawValue: table)
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: rowIds)])
}
/// Some columns from some rows in a table.
init(table: String, columns: Set<String>, rowIds: Set<Int64>) {
let table = CaseInsensitiveIdentifier(rawValue: table)
let columns = Set(columns.map(CaseInsensitiveIdentifier.init))
self.init(tableRegions: [table: TableRegion(columns: columns, rowIds: rowIds)])
}
/// Returns the intersection of this region and the given one.
///
/// This method is not public because there is no known public use case for
@@ -162,6 +170,22 @@ public struct DatabaseRegion: Sendable {
self = union(other)
}
/// Inserts all columns and rows from the given table.
mutating func insert(table: String) {
guard tableRegions != nil else { return }
let table = CaseInsensitiveIdentifier(rawValue: table)
tableRegions![table, default: TableRegion()].insertAllRowsAndColumns()
}
/// Inserts the specified column and all rows from the given table.
mutating func insert(table: String, column: String) {
assert(!column.isEmpty)
guard tableRegions != nil else { return }
let table = CaseInsensitiveIdentifier(rawValue: table)
let column = CaseInsensitiveIdentifier(rawValue: column)
tableRegions![table, default: TableRegion(columns: [column])].insertAllRowsAndColumn(column)
}
/// Returns a region suitable for database observation
func observableRegion(_ db: Database) throws -> DatabaseRegion {
// SQLite does not expose schema changes to the
@@ -256,8 +280,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
@@ -370,6 +394,18 @@ private struct TableRegion: Equatable {
return TableRegion(columns: columnsUnion, rowIds: rowIdsUnion)
}
mutating func insertAllRowsAndColumns() {
rowIds = nil
columns = nil
}
mutating func insertAllRowsAndColumn(_ column: CaseInsensitiveIdentifier) {
rowIds = nil
if columns != nil {
columns!.insert(column)
}
}
func contains(rowID: Int64) -> Bool {
guard let rowIds else {
return true
+6 -2
View File
@@ -201,7 +201,11 @@ extension DatabasePublishers {
self.observation = observation
}
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
public func receive<S>(subscriber: S)
where S: Subscriber & GRDBSendableMetatype,
Failure == S.Failure,
Output == S.Input
{
let subscription = DatabaseRegionSubscription(
writer: writer,
observation: observation,
@@ -212,7 +216,7 @@ extension DatabasePublishers {
private class DatabaseRegionSubscription<Downstream>:
Subscription, @unchecked Sendable
where Downstream: Subscriber,
where Downstream: Subscriber & GRDBSendableMetatype,
Downstream.Failure == Error,
Downstream.Input == Database
{
+218
View File
@@ -0,0 +1,218 @@
/// A type that provides information about the database schema.
///
/// ## Overview
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
/// The use case for a custom schema source is to enable GRDB features that
/// would not work with the built-in schema introspection provided
/// by SQLite.
///
/// For example, if your database schema contains a view and you wish to use
/// GRDB features that need a primary key, such as the
/// ``FetchableRecord/find(_:id:)`` record method, or the persistence
/// methods of the ``PersistableRecord`` protocol, then use a schema source
/// that implements the ``columnsForPrimaryKey(_:inView:)`` method. See
/// <doc:ViewRecords> for a detailed guide about such views.
///
/// ## Enabling a Schema Source
///
/// To enable a schema source in a database connection, configure its
/// ``Configuration/schemaSource``:
///
/// ```swift
/// struct MySchemaSource: DatabaseSchemaSource { ... }
///
/// var config = Configuration()
/// config.schemaSource = MySchemaSource()
/// let dbQueue = try DatabaseQueue(path: "/path/to/db.sqlite", configuration: config)
/// ```
///
/// ## Schema Sources and Migrations
///
/// By default, schema sources are disabled during <doc:Migrations>. In
/// migrations that need a schema source, you can use
/// ``Database/withSchemaSource(_:execute:)``:
///
/// ```swift
/// migrator.registerMigration("My migration") { db in
/// // No schema source is enabled at this point.
/// try db.withSchemaSource(MySchemaSource()) {
/// // Here the provided schema source is in effect.
/// }
/// }
/// ```
///
/// Take care that **a good migration is a migration that is never
/// modified once it has shipped**: check
/// <doc:Migrations#Good-Practices-for-Defining-Migrations>.
///
/// ## Topics
///
/// ### Customizing the Database Schema
///
/// - ``columnsForPrimaryKey(_:inView:)``
///
/// ### Chaining Schema Sources
///
/// - ``then(_:)``
public protocol DatabaseSchemaSource: Sendable {
/// Returns the names of the columns for the primary key in the
/// provided database view.
///
/// Return `nil` if no customization should happen. Return an empty
/// array to specify that the view has no primary key. The default
/// implementation returns `nil`.
///
/// In your implementation, make sure that the returned columns define
/// a genuine **primary key**:
///
/// - All columns exist in the provided view.
/// - The set of columns reliably identifies and distinguishes between
/// each individual row in the view.
/// - No column contains NULL values.
///
/// It is a programmer error with undefined consequences to miss
/// those requirements.
///
/// For example:
///
/// ```swift
/// // A schema source that specifies that all views are identified by
/// // their "id" column:
/// struct MySchemaSource: DatabaseSchemaSource {
/// func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) {
/// ["id"]
/// }
/// }
///
/// // A database connection configured with the schema source.
/// var config = Configuration()
/// config.schemaSource = MySchemaSource()
/// let dbQueue = try DatabaseQueue(path: "/path/to/db.sqlite", configuration: config)
///
/// // A record type that feeds from a view.
/// struct Player: Decodable, Identifiable, FetchableRecord {
/// static let databaseTableName = "playerView"
/// var id: String
/// var name: String
/// }
///
/// // Thanks to the schema source, we can fetch players by id:
/// let player = try dbQueue.read { db in
/// try Player.find(db, id: "alice")
/// }
/// ```
///
/// ### Schema Sources in Libraries
///
/// When you are developing a schema source for a library, some extra
/// care is necessary whenever the database file is owned by the users
/// of your library. Your users may define views for their own purposes,
/// and your library knows nothing about the eventual primary key of
/// those views.
///
/// In this case, make your schema source `public`, and have this method
/// return `nil` for those unknown views. If needed, use the `db`
/// argument and query the database schema with
/// <doc:DatabaseSchemaIntrospection> methods.
///
/// For example:
///
/// ```swift
/// // A well-behaved schema source defined by a library is public
/// // and returns nil for unknown views.
/// public struct MyLibrarySchemaSource: DatabaseSchemaSource {
/// public func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) {
/// if view.name == "playerView" {
/// // This is a view managed by my library:
/// return ["id"]
/// } else if try db.tableExists(view.name + "MyLibrary") {
/// // This is a view managed by my library:
/// return ["uuid"]
/// } else {
/// // Not a view managed by my library:
/// // don't mess with user's schema
/// return nil
/// }
/// }
/// }
/// ```
///
/// With such a setup, your user will be able to deal with their
/// own views, by chaining your schema source with other ones
/// (see ``DatabaseSchemaSource/then(_:)``):
///
/// ```swift
/// // Application code
/// import MyLibrary
/// import GRDB
///
/// let myLibrarySchemaSource = MyLibrarySchemaSource()
/// let customSchemaSource = TheirCustomSchemaSource()
/// let schemaSource = myLibrarySchemaSource.then(customSchemaSource)
///
/// var config = Configuration()
/// config.schemaSource = schemaSource
/// let dbQueue = try DatabaseQueue(path: "...", configuration: config)
/// ```
///
/// - Parameters:
/// - db: A database connection.
/// - view: The identifier of a database view.
func columnsForPrimaryKey(
_ db: Database,
inView view: DatabaseObjectID
) throws -> [String]?
}
extension DatabaseSchemaSource {
public func columnsForPrimaryKey(
_ db: Database,
inView view: DatabaseObjectID
) throws -> [String]? {
nil
}
}
// MARK: - Combined2SchemaSource
extension DatabaseSchemaSource {
/// Returns a schema source that queries `other` when this source does
/// not perform a customization.
///
/// For example:
///
/// ```swift
/// let schemaSource1 = SomeSchemaSource()
/// let schemaSource2 = AnotherSchemaSource()
/// let schemaSource = schemaSource1.then(schemaSource2)
///
/// var config = Configuration()
/// config.schemaSource = schemaSource
/// let dbQueue = try DatabaseQueue(path: "...", configuration: config)
/// ```
public func then(_ other: some DatabaseSchemaSource) -> some DatabaseSchemaSource {
Chained2SchemaSource(first: self, second: other)
}
}
// TODO: move to parameter packs eventually. Parameter packs in generic types
// are only available in macOS 14.0.0 or newer.
// This schema source is designed to tame bad citizens that customize tables
// and views they do not own (such as insufficienly robust schema sources
// exposed by external libraries). We should NEVER MERGE the results of the
// schema sources.
struct Chained2SchemaSource<Source1, Source2>: DatabaseSchemaSource
where Source1: DatabaseSchemaSource,
Source2: DatabaseSchemaSource
{
var first: Source1
var second: Source2
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
if let result = try first.columnsForPrimaryKey(db, inView: view) { return result }
if let result = try second.columnsForPrimaryKey(db, inView: view) { return result }
return nil
}
}
+7 -2
View File
@@ -113,8 +113,13 @@ public final class DatabaseSnapshot {
deinit {
// Leave snapshot isolation
reader.reentrantSync { db in
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
// Commit or rollback, but make sure we leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
assert(!db.isInsideTransaction)
}
}
+10 -7
View File
@@ -1,11 +1,14 @@
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#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
@@ -137,7 +140,7 @@ public final class DatabaseSnapshotPool {
let walSnapshot = try db.isolated(readOnly: true) {
try WALSnapshot(db)
}
var holderConfig = Configuration()
var holderConfig = configuration
holderConfig.allowsUnsafeTransactions = true
snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig)
try snapshotHolder.inDatabase { db in
@@ -196,7 +199,7 @@ public final class DatabaseSnapshotPool {
var configuration = Self.configure(configuration)
// Acquire and hold WAL snapshot
var holderConfig = Configuration()
var holderConfig = configuration
holderConfig.allowsUnsafeTransactions = true
snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig)
let walSnapshot = try snapshotHolder.inDatabase { db in
+14 -7
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
@@ -144,7 +147,10 @@ public struct DatabaseValue: Hashable {
case SQLITE_FLOAT:
storage = .double(sqlite3_value_double(sqliteValue))
case SQLITE_TEXT:
storage = .string(String(cString: sqlite3_value_text(sqliteValue)!))
let text = sqlite3_value_text(sqliteValue)
let byteCount = Int(sqlite3_value_bytes(sqliteValue))
let string = String(decoding: UnsafeBufferPointer(start: text, count: byteCount), as: UTF8.self)
storage = .string(string)
case SQLITE_BLOB:
if let bytes = sqlite3_value_blob(sqliteValue) {
let count = Int(sqlite3_value_bytes(sqliteValue))
@@ -168,7 +174,8 @@ public struct DatabaseValue: Hashable {
case SQLITE_FLOAT:
storage = .double(sqlite3_column_double(sqliteStatement, index))
case SQLITE_TEXT:
storage = .string(String(cString: sqlite3_column_text(sqliteStatement, index)))
let string = String(sqliteStatement: sqliteStatement, index: index)
storage = .string(string)
case SQLITE_BLOB:
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
let count = Int(sqlite3_column_bytes(sqliteStatement, index))
@@ -220,7 +227,7 @@ extension DatabaseValue: StatementBinding {
let code = double.bind(to: sqliteStatement, at: index)
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
return try body()
case .string(let string):
case .string(var string):
return try string.withBinding(to: sqliteStatement, at: index, do: body)
case .blob(let data):
return try data.withBinding(to: sqliteStatement, at: index, do: body)
+2 -2
View File
@@ -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.
///
@@ -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.
///
+8
View File
@@ -1,4 +1,8 @@
#if os(Linux)
@preconcurrency import Dispatch
#else
import Dispatch
#endif
/// An actor that runs in a DispatchQueue.
///
@@ -43,3 +47,7 @@ private final class DispatchQueueExecutor: SerialExecutor {
dispatchPrecondition(condition: .onQueue(queue))
}
}
#if os(Linux) || os(Android) || os(Windows)
extension DispatchQueueExecutor: @unchecked Sendable {}
#endif
+25 -17
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
@@ -151,7 +154,20 @@ public final class Row {
let sqliteStatement: SQLiteStatement?
/// The number of columns in the row.
public let count: Int
@inlinable
public var count: Int {
// Rows that map an SQLite statement don't cache the number of
// columns, because SQLite may recompile the statement after a
// schema change, with a different number of columns.
if let sqliteStatement {
return Int(sqlite3_column_count(sqliteStatement))
}
return cachedCount
}
/// The number of columns, when the row does not map an SQLite statement.
@usableFromInline
let cachedCount: Int
/// A view on the prefetched associated rows.
///
@@ -235,7 +251,7 @@ public final class Row {
self.statement = statement
self.sqliteStatement = statement.sqliteStatement
self.impl = StatementRowImpl(sqliteStatement: statement.sqliteStatement, statement: statement)
self.count = Int(sqlite3_column_count(sqliteStatement))
self.cachedCount = 0 // Unused because sqliteStatement is not nil: see `count`
}
/// Creates a row that maps an SQLite statement. Further calls to
@@ -244,7 +260,7 @@ public final class Row {
self.statement = nil
self.sqliteStatement = sqliteStatement
self.impl = SQLiteStatementRowImpl(sqliteStatement: sqliteStatement)
self.count = Int(sqlite3_column_count(sqliteStatement))
self.cachedCount = 0 // Unused because sqliteStatement is not nil: see `count`
}
/// Creates a row that contain a copy of the current state of the
@@ -266,7 +282,7 @@ public final class Row {
self.statement = nil
self.sqliteStatement = nil
self.impl = impl
self.count = impl.count
self.cachedCount = impl.count
}
}
@@ -2782,19 +2798,10 @@ private struct StatementCopyRowImpl: RowImpl {
private struct StatementRowImpl: RowImpl {
let statement: Statement
let sqliteStatement: SQLiteStatement
let lowercaseColumnIndexes: [String: Int]
init(sqliteStatement: SQLiteStatement, statement: Statement) {
self.statement = statement
self.sqliteStatement = sqliteStatement
// Optimize row[columnName]
let lowercaseColumnNames = (0..<sqlite3_column_count(sqliteStatement))
.map { String(cString: sqlite3_column_name(sqliteStatement, CInt($0))).lowercased() }
self.lowercaseColumnIndexes = Dictionary(
lowercaseColumnNames
.enumerated()
.map { ($0.element, $0.offset) },
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
}
var count: Int {
@@ -2841,6 +2848,7 @@ private struct StatementRowImpl: RowImpl {
}
func index(forColumn name: String) -> Int? {
let lowercaseColumnIndexes = statement.columnIndexes
if let index = lowercaseColumnIndexes[name] {
return index
}
+7 -4
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#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
+54 -20
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
@@ -44,6 +47,25 @@ public final class Statement {
case rollbackSavepoint(String)
}
/// The column names and indexes of a statement, for a given compilation
/// of the statement.
private struct ColumnCache {
var reprepareCount: CInt
var columnNames: [String]
/// Indexes of the leftmost columns. Keys are lowercase.
var columnIndexes: [String: Int]
init(sqliteStatement: SQLiteStatement, reprepareCount: CInt) {
self.reprepareCount = reprepareCount
self.columnNames = (0..<sqlite3_column_count(sqliteStatement)).map {
String(cString: sqlite3_column_name(sqliteStatement, $0))
}
self.columnIndexes = Dictionary(
columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
}
}
/// The raw SQLite statement, suitable for the SQLite C API.
public let sqliteStatement: SQLiteStatement
@@ -56,11 +78,9 @@ public final class Statement {
}
/// The column names, ordered from left to right.
public lazy var columnNames: [String] = {
// swiftlint:disable:next redundant_self_in_closure
let sqliteStatement = self.sqliteStatement
return (0..<CInt(columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
}()
public var columnNames: [String] {
columnCache.columnNames
}
// The database region is reported by `sqlite3_set_authorizer`, and maybe
// refined in `SQLQueryGenerator.makeStatement(_:)` when we have enough
@@ -111,12 +131,29 @@ public final class Statement {
@usableFromInline
unowned let database: Database
/// Cache for index(ofColumn:). Keys are lowercase.
private lazy var columnIndexes: [String: Int] = {
Dictionary(
columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
}()
/// Indexes of the leftmost columns. Keys are lowercase.
var columnIndexes: [String: Int] {
columnCache.columnIndexes
}
/// Storage for `columnCache`.
private var _columnCache: ColumnCache?
/// The column names and indexes.
///
/// SQLite recompiles statements after schema changes (see
/// <https://www.sqlite.org/c3ref/prepare.html>), and this can change
/// the result columns (think `SELECT *` after a column was added).
/// So the cache is rebuilt whenever the statement is recompiled.
private var columnCache: ColumnCache {
let reprepareCount = sqlite3_stmt_status(sqliteStatement, SQLITE_STMTSTATUS_REPREPARE, 0)
if let _columnCache, _columnCache.reprepareCount == reprepareCount {
return _columnCache
}
let columnCache = ColumnCache(sqliteStatement: sqliteStatement, reprepareCount: reprepareCount)
_columnCache = columnCache
return columnCache
}
/// Creates a prepared statement. Returns nil if the compiled string is
/// blank or empty.
@@ -141,16 +178,13 @@ 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)
guard code == SQLITE_OK else {
throw DatabaseError(
resultCode: code,
message: database.lastErrorMessage,
sql: String(cString: statementStart))
try database.statementCompilationDidFail(at: statementStart, withResultCode: code)
}
guard let sqliteStatement else {
+11 -6
View File
@@ -1,16 +1,21 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
#if canImport(string_h)
import string_h
#elseif os(Linux)
import Glibc
#elseif os(Android)
import Android
#elseif os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(visionOS)
import Darwin
#elseif os(Windows)
@@ -112,10 +117,10 @@ final class StatementAuthorizer {
guard let columnName = cString2.map(String.init) else { return SQLITE_OK }
if columnName.isEmpty {
// SELECT COUNT(*) FROM table
selectedRegion.formUnion(DatabaseRegion(table: tableName))
selectedRegion.insert(table: tableName)
} else {
// SELECT column FROM table
selectedRegion.formUnion(DatabaseRegion(table: tableName, columns: [columnName]))
selectedRegion.insert(table: tableName, column: columnName)
}
return SQLITE_OK
+7 -4
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
/// A type that can decode itself from the low-level C interface to
+3 -1
View File
@@ -1,5 +1,8 @@
#if canImport(CoreGraphics)
import CoreGraphics
#elseif !canImport(Darwin)
import Foundation
#endif
/// CGFloat adopts DatabaseValueConvertible
extension CGFloat: DatabaseValueConvertible {
@@ -15,4 +18,3 @@ extension CGFloat: DatabaseValueConvertible {
return CGFloat(double)
}
}
#endif
+7 -4
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
+7 -6
View File
@@ -1,15 +1,17 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
#if !os(Linux)
/// NSDate is stored in the database using the format
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
extension NSDate: DatabaseValueConvertible {
@@ -38,7 +40,6 @@ extension NSDate: DatabaseValueConvertible {
return cast(date)
}
}
#endif
/// Date is stored in the database using the format
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
+9 -9
View File
@@ -1,11 +1,13 @@
#if !os(Linux)
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
@@ -54,9 +56,8 @@ extension Decimal: StatementColumnConvertible {
case SQLITE_FLOAT:
self.init(sqlite3_column_double(sqliteStatement, index))
case SQLITE_TEXT:
self.init(
string: String(cString: sqlite3_column_text(sqliteStatement, index)!),
locale: _posixLocale)
let string = String(sqliteStatement: sqliteStatement, index: index)
self.init(string: string, locale: _posixLocale)
default:
return nil
}
@@ -65,4 +66,3 @@ extension Decimal: StatementColumnConvertible {
@usableFromInline
let _posixLocale = Locale(identifier: "en_US_POSIX")
#endif
@@ -1,4 +1,3 @@
#if !os(Linux)
import Foundation
/// NSData is convertible to and from DatabaseValue.
@@ -24,4 +23,3 @@ extension NSData: DatabaseValueConvertible {
return cast(data)
}
}
#endif
+10 -4
View File
@@ -1,4 +1,3 @@
#if !os(Linux) && !os(Windows)
import Foundation
private let integerRoundingBehavior = NSDecimalNumberHandler(
@@ -81,10 +80,18 @@ extension NSNumber: DatabaseValueConvertible {
/// Otherwise, returns nil.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
switch dbValue.storage {
case .int64(let int64) where self is NSDecimalNumber.Type:
let number = NSDecimalNumber(value: int64)
return number as? Self
case .int64(let int64):
return self.init(value: int64)
let number = NSNumber(value: int64)
return number as? Self
case .double(let double) where self is NSDecimalNumber.Type:
let number = NSDecimalNumber(value: double)
return number as? Self
case .double(let double):
return self.init(value: double)
let number = NSNumber(value: double)
return number as? Self
case let .string(string):
// Must match Decimal.fromDatabaseValue(_:)
guard let decimal = Decimal(string: string, locale: posixLocale) else { return nil }
@@ -96,4 +103,3 @@ extension NSNumber: DatabaseValueConvertible {
}
private let posixLocale = Locale(identifier: "en_US_POSIX")
#endif
@@ -1,4 +1,3 @@
#if !os(Linux)
import Foundation
/// NSString adopts DatabaseValueConvertible
@@ -24,4 +23,3 @@ extension NSString: DatabaseValueConvertible {
return self.init(string: string)
}
}
#endif
+5 -3
View File
@@ -1,12 +1,15 @@
import Foundation
#if !os(Linux) && !os(Windows)
/// NSURL stores its absoluteString in the database.
extension NSURL: DatabaseValueConvertible {
/// Returns a TEXT database value containing the absolute URL.
public var databaseValue: DatabaseValue {
absoluteString?.databaseValue ?? .null
#if !canImport(Darwin)
absoluteString.databaseValue
#else
absoluteString?.databaseValue ?? .null
#endif
}
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
@@ -16,7 +19,6 @@ extension NSURL: DatabaseValueConvertible {
return cast(URL(string: string))
}
}
#endif
/// URL stores its absoluteString in the database.
extension URL: DatabaseValueConvertible { }
+19 -11
View File
@@ -1,15 +1,17 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
#if !os(Linux) && !os(Windows)
/// NSUUID adopts DatabaseValueConvertible
extension NSUUID: DatabaseValueConvertible {
/// Returns a BLOB database value containing the uuid bytes.
@@ -33,16 +35,22 @@ extension NSUUID: DatabaseValueConvertible {
switch dbValue.storage {
case .blob(let data) where data.count == 16:
return data.withUnsafeBytes {
self.init(uuidBytes: $0.bindMemory(to: UInt8.self).baseAddress)
#if canImport(Darwin)
self.init(uuidBytes: $0.bindMemory(to: UInt8.self).baseAddress)
#else
guard let uuidBytes = $0.bindMemory(to: UInt8.self).baseAddress else {
return nil as Self?
}
return NSUUID(uuidBytes: uuidBytes) as? Self
#endif
}
case .string(let string):
return self.init(uuidString: string)
return NSUUID(uuidString: string) as? Self
default:
return nil
}
}
}
#endif
/// UUID adopts DatabaseValueConvertible
extension UUID: DatabaseValueConvertible {
@@ -81,15 +89,15 @@ extension UUID: StatementColumnConvertible {
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_TEXT:
let string = String(cString: sqlite3_column_text(sqliteStatement, index)!)
let string = String(sqliteStatement: sqliteStatement, index: index)
guard let uuid = UUID(uuidString: string) else {
return nil
}
self.init(uuid: uuid.uuid)
case SQLITE_BLOB:
guard sqlite3_column_bytes(sqliteStatement, index) == 16,
let blob = sqlite3_column_blob(sqliteStatement, index) else
{
let blob = sqlite3_column_blob(sqliteStatement, index)
else {
return nil
}
self.init(uuid: blob.assumingMemoryBound(to: uuid_t.self).pointee)
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
extension Optional: StatementBinding where Wrapped: StatementBinding {
@@ -1,12 +1,17 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
// MARK: - Value Types
/// Bool adopts DatabaseValueConvertible and StatementColumnConvertible.
@@ -587,7 +592,9 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
/// - 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)!)
let text = sqlite3_column_text(sqliteStatement, index)
let byteCount = Int(sqlite3_column_bytes(sqliteStatement, index))
self = String(decoding: UnsafeBufferPointer(start: text, count: byteCount), as: UTF8.self)
}
/// Returns a TEXT database value.
@@ -617,23 +624,57 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
}
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_text(sqliteStatement, index, self, -1, SQLITE_TRANSIENT)
var string = self
return string.withSQLiteText {
sqlite3_bind_text(sqliteStatement, index, $0, $1, SQLITE_TRANSIENT)
}
}
/// Calls the given closure after binding a statement argument.
///
/// The binding is valid only during the execution of this method.
///
/// This method is mutating because the string is made contiguous
/// if necessary.
///
/// - 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 {
try withCString {
let code = sqlite3_bind_text(sqliteStatement, index, $0, -1, nil /* SQLITE_STATIC */)
mutating func withBinding<T>(
to sqliteStatement: SQLiteStatement,
at index: CInt,
do body: () throws -> T
) throws -> T {
try withSQLiteText {
let code = sqlite3_bind_text(sqliteStatement, index, $0, $1, nil /* SQLITE_STATIC */)
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
return try body()
}
}
/// Runs body over the content of this string as an UTF8 string. This
/// method exists because it deals with the ASCII NUL (\0) characters,
/// unlike C strings.
///
/// This method is mutating because the string is made contiguous
/// if necessary.
mutating func withSQLiteText<T>(
_ body: (UnsafePointer<CChar>, CInt) throws -> T
) rethrows -> T {
try withUTF8 { utf8 in
guard let baseAddress = utf8.baseAddress else {
// Empty string: yield a non-nil pointer to the NUL string
// terminator, so that functions such as sqlite3_bind_text()
// unambiguously interpret it as the empty string.
return try withUnsafePointer(to: 0 as CChar) {
try body($0, 0)
}
}
return try baseAddress.withMemoryRebound(to: CChar.self, capacity: utf8.count) {
try body($0, CInt(utf8.count))
}
}
}
}
+160 -66
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
extension Database {
@@ -294,6 +297,10 @@ class DatabaseObservationBroker {
}
}
/// Notifies that some changes were performed in the provided
/// database region.
///
/// Support for the public ``Database/notifyChanges(in:)`` method.
func notifyChanges(withEventsOfKind eventKinds: [DatabaseEventKind]) throws {
// Support for stopObservingDatabaseChangesUntilNextTransaction()
SchedulingWatchdog.current!.databaseObservationBroker = self
@@ -331,65 +338,14 @@ class DatabaseObservationBroker {
SchedulingWatchdog.current!.databaseObservationBroker = self
// Fill statementObservations with observations that are interested
// in the kind of database events performed by the statement, as
// reported by `sqlite3_set_authorizer`.
//
// in the kind of database events performed by the statement.
// Those statementObservations will be notified of individual changes
// in databaseWillChange() and databaseDidChange().
let authorizerEventKinds = statement.authorizerEventKinds
switch authorizerEventKinds.count {
case 0:
// Statement has no effect on any database table.
//
// For example: PRAGMA foreign_keys = ON
statementObservations = []
case 1:
// We'll execute a simple statement without any side effect.
// Eventual database events will thus all have the same kind. All
// detabase events can be notified to interested observations.
//
// For example, if one observes all deletions in the table T, then
// all individual deletions of DELETE FROM T are notified:
let eventKind = authorizerEventKinds[0]
statementObservations = transactionObservations.compactMap { observation in
guard observation.observes(eventsOfKind: eventKind) else {
// observation is not interested
return nil
}
// Observation will be notified of all individual events
return StatementObservation(
transactionObservation: observation,
trackingEvents: .all)
}
default:
// We'll execute a complex statement with side effects performed by
// an SQL trigger or a foreign key action. Eventual database events
// may not all have the same kind: we need to filter them before
// notifying interested observations.
//
// For example, if DELETE FROM T1 generates deletions in T1 and T2
// by the mean of a foreign key action, then when one only observes
// deletions in T1, one must not be notified of deletions in T2:
statementObservations = transactionObservations.compactMap { observation in
let observedEventKinds = authorizerEventKinds.filter(observation.observes)
if observedEventKinds.isEmpty {
// observation is not interested
return nil
}
// Observation will only be notified of individual events
// it is interested into.
return StatementObservation(
transactionObservation: observation,
trackingEvents: .matching(
observedEventKinds: observedEventKinds,
authorizerEventKinds: authorizerEventKinds))
}
statementObservations = transactionObservations.compactMap { observation in
observation.statementObservation(for: statement)
}
}
transactionCompletion = .none
}
@@ -795,16 +751,78 @@ class DatabaseObservationBroker {
}
}
// MARK: - DatabaseEventObservationStrategy
/// Controls which database changes are notified to a `TransactionObserver`.
public struct DatabaseEventObservationStrategy: Sendable {
/// A boolean value indicating whether a ``TransactionObserver`` focuses
/// on database changes filtered by its
/// ``TransactionObserver/observes(eventsOfKind:)`` method.
///
/// When this flag is true (the default), the only notified changes are
/// those performed by `DELETE`, `INSERT` and `UPDATE` statements that
/// are compiled and executed by GRDB. Other changes are not: changes
/// performed by `SELECT` statements (through a database function),
/// changes performed by statements compiled or executed with the SQLite
/// C API.
///
/// Set this flag to false in order to be notified of all database events.
///
/// When this flag is false, an observer prevents the
/// [truncate optimization](https://www.sqlite.org/lang_delete.html#the_truncate_optimization)
/// from being applied on all database tables.
public var requiresDatabaseEventKind: Bool
/// The default strategy for observing database change events.
///
/// In this default strategy, only the `DELETE`, `INSERT` and `UPDATE`
/// statements that are compiled and executed by GRDB are observed.
public static let `default` = DatabaseEventObservationStrategy(requiresDatabaseEventKind: true)
}
// MARK: - TransactionObserver
public protocol TransactionObserver: AnyObject {
/// Controls which database changes should be notified to the observer.
///
/// The default value is ``DatabaseEventObservationStrategy/default``,
/// which only detects changes performed by `DELETE`, `INSERT` and
/// `UPDATE` statements that are compiled and executed by GRDB.
///
/// You can define a universal observer that observes changes performed
/// by `SELECT` statements (through a database function), changes
/// performed by statements compiled or executed with the SQLite C API,
/// as below:
///
/// ```swift
/// // An observer that observes all database changes.
/// class UniversalObserver: TransactionObserver {
/// var databaseEventObservationStrategy: DatabaseEventObservationStrategy {
/// var strategy = DatabaseEventObservationStrategy.default
/// // Don't filter on database event kind, so that we are
/// // notified of changes performed through the SQLite C API:
/// strategy.requiresDatabaseEventKind = false
/// return strategy
/// }
///
/// // You still have to provide an implementation for this method,
/// // but it will never be called since `requiresDatabaseEventKind`
/// // is false.
/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
/// false // ignored
/// }
///
/// func databaseDidChange(with event: DatabaseEvent) {
/// // Handle the change
/// }
/// }
/// ```
var databaseEventObservationStrategy: DatabaseEventObservationStrategy { get }
/// Returns whether specific kinds of database changes should be notified
/// to the observer.
///
/// When this method returns false, database events of this kind are not
/// notified to the ``databaseDidChange(with:)`` method.
///
/// For example:
///
/// ```swift
@@ -820,6 +838,11 @@ public protocol TransactionObserver: AnyObject {
/// prevents the
/// [truncate optimization](https://www.sqlite.org/lang_delete.html#the_truncate_optimization)
/// from being applied on the observed tables.
///
/// - Note: This method is not called when the result of
/// ``databaseEventObservationStrategy`` has the
/// ``DatabaseEventObservationStrategy/requiresDatabaseEventKind``
/// flag set to false.
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
/// Called when the database was modified in some unspecified way.
@@ -835,8 +858,12 @@ public protocol TransactionObserver: AnyObject {
/// Called when the database is changed by an insert, update, or
/// delete event.
///
/// The change is pending until the current transaction ends. See
/// ``databaseWillCommit()-7mksu``, ``databaseDidCommit(_:)`` and
/// Whether this method is called or not for any given change is
/// controlled by ``databaseEventObservationStrategy`` and
/// ``observes(eventsOfKind:)``.
///
/// The notified change is pending until the current transaction ends.
/// See ``databaseWillCommit()-7mksu``, ``databaseDidCommit(_:)`` and
/// ``databaseDidRollback(_:)``.
///
/// The observer has an opportunity to stop receiving further change events
@@ -899,6 +926,11 @@ public protocol TransactionObserver: AnyObject {
}
extension TransactionObserver {
/// The default implementation does not observe statements.
public var databaseEventObservationStrategy: DatabaseEventObservationStrategy {
.default
}
/// The default implementation does nothing.
public func databaseWillCommit() throws { }
@@ -993,7 +1025,69 @@ final class TransactionObservation {
}
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
observer?.observes(eventsOfKind: eventKind) ?? false
guard let observer else {
return false
}
return !observer.databaseEventObservationStrategy.requiresDatabaseEventKind || observer.observes(eventsOfKind: eventKind)
}
func statementObservation(for statement: Statement) -> StatementObservation? {
guard let observer else {
return nil
}
if !observer.databaseEventObservationStrategy.requiresDatabaseEventKind {
return StatementObservation(
transactionObservation: self,
trackingEvents: .all)
}
let authorizerEventKinds = statement.authorizerEventKinds
switch authorizerEventKinds.count {
case 0:
// Statement has no effect on any database table.
//
// For example: PRAGMA foreign_keys = ON
return nil
case 1:
// We'll execute a simple statement without any side effect.
// Eventual database events will thus all have the same kind. All
// detabase events can be notified to interested observations.
//
// For example, if one observes all deletions in the table T, then
// all individual deletions of DELETE FROM T are notified:
guard observer.observes(eventsOfKind: authorizerEventKinds[0]) else {
// observation is not interested
return nil
}
// Observation will be notified of all individual events
return StatementObservation(
transactionObservation: self,
trackingEvents: .all)
default:
// We'll execute a complex statement with side effects performed by
// an SQL trigger or a foreign key action. Eventual database events
// may not all have the same kind: we need to filter them before
// notifying interested observations.
//
// For example, if DELETE FROM T1 generates deletions in T1 and T2
// by the mean of a foreign key action, then when one only observes
// deletions in T1, one must not be notified of deletions in T2:
let observedEventKinds = authorizerEventKinds.filter(observer.observes)
if observedEventKinds.isEmpty {
// observation is not interested
return nil
}
// Observation will only be notified of individual events
// it is interested into.
return StatementObservation(
transactionObservation: self,
trackingEvents: .matching(
observedEventKinds: observedEventKinds,
authorizerEventKinds: authorizerEventKinds))
}
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
@@ -1494,7 +1588,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt)
-> DatabaseValue?
{
var value: SQLiteValue? = nil
var value: SQLiteValue?
guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil }
if let value {
return DatabaseValue(sqliteValue: value)
+8 -17
View File
@@ -1,11 +1,14 @@
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
/// An instance of WALSnapshot records the state of a WAL mode database for some
@@ -16,18 +19,6 @@ import SQLite3
/// actual observation. This class has no other purpose, and is not intended to
/// become public.
///
/// It does not work with SQLCipher, because SQLCipher does not support
/// `SQLITE_ENABLE_SNAPSHOT` correctly: we have linker errors.
/// See <https://github.com/ericsink/SQLitePCL.raw/issues/452>.
///
/// With custom SQLite builds, it only works if `SQLITE_ENABLE_SNAPSHOT`
/// is defined.
///
/// With system SQLite, it works because the SDK exposes the C apis and
/// since XCode 14.
///
/// Yes, this is an awfully complex logic.
///
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
final class WALSnapshot: @unchecked Sendable {
// @unchecked because sqlite3_snapshot has no threading requirements.
+8 -2
View File
@@ -1,4 +1,4 @@
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
/// A long-live read-only WAL transaction.
///
/// `WALSnapshotTransaction` **takes ownership** of its reader
@@ -15,7 +15,13 @@ final class WALSnapshotTransaction: @unchecked Sendable {
// WALSnapshotTransaction may be deinitialized in the dispatch
// queue of its reader: allow reentrancy.
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
try? db.commit()
// Commit or rollback, but try hard to leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
return db.isInsideTransaction
}
release(isInsideTransaction)
@@ -29,6 +29,8 @@ Get information about schema objects such as tables, columns, indexes, foreign k
### Supporting Types
- ``DatabaseSchemaID``
- ``DatabaseObjectID``
- ``ColumnInfo``
- ``ForeignKeyInfo``
- ``IndexInfo``
@@ -96,6 +96,7 @@ do {
- ``persistentReadOnlyConnections``
- ``prepareDatabase(_:)``
- ``publicStatementArguments``
- ``schemaSource``
- ``transactionClock``
- ``TransactionClock``
@@ -106,3 +107,7 @@ do {
- ``writeQoS``
- ``targetQueue``
- ``writeTargetQueue``
### Supporting Types
- ``DatabaseSchemaSource``
@@ -79,7 +79,7 @@ let observation = DatabaseRegionObservation(
`DatabaseRegionObservation` will not notify impactful transactions whenever the database is modified in an undetectable way:
- Changes performed by external database connections.
- Changes performed by SQLite statements that are not compiled and executed by GRDB.
- Changes performed by SQLite statements that are not a `DELETE`, `INSERT` or `UPDATE` statement compiled and executed by GRDB.
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
@@ -97,7 +97,7 @@ do {
**Transaction observers can choose the database changes they are interested in.**
The ``observes(eventsOfKind:)`` method filters events that are notified to ``databaseDidChange(with:)``. It is the most efficient and recommended change filtering technique, because it is only called once before a database query is executed, and can completely disable change tracking:
By default, the ``observes(eventsOfKind:)`` method filters events that are notified to ``databaseDidChange(with:)``. It is the most efficient and recommended change filtering technique, because it is only called once before a database query is executed, and can completely disable change tracking:
```swift
// Calls `observes(eventsOfKind:)` once.
@@ -125,6 +125,8 @@ class PlayerObserver: TransactionObserver {
When the `observes(eventsOfKind:)` method returns false for all event kinds, the observer is still notified of transactions.
The filtering performed by ``observes(eventsOfKind:)`` makes a transaction observer unaware of changes performed by SQLite statements that are not a `DELETE`, `INSERT` or `UPDATE` statement compiled and executed by GRDB. You can lift this limitation with the ``TransactionObserver/databaseEventObservationStrategy``.
## Observation Extent
**You can specify how long an observer is notified of database changes and transactions.**
@@ -232,7 +234,7 @@ The changes and transactions that are not automatically notified to transaction
- Read-only transactions.
- Changes and transactions performed by external database connections.
- Changes performed by SQLite statements that are not both compiled and executed through GRDB APIs.
- Changes performed by SQLite statements that are not a `DELETE`, `INSERT` or `UPDATE` statement compiled and executed by GRDB (this limitation can be lifted, in your custom `TransactionObserver` type, with ``TransactionObserver/databaseEventObservationStrategy``).
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
- The deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite).
@@ -265,8 +267,10 @@ try dbQueue.write { db in
### Filtering Database Changes
- ``databaseEventObservationStrategy``
- ``observes(eventsOfKind:)``
- ``DatabaseEventKind``
- ``DatabaseEventObservationStrategy``
### Handling Database Changes
@@ -228,7 +228,7 @@ This ``tracking(region:_:fetch:)`` method lets you entirely separate the **obser
`ValueObservation` will not fetch and notify a fresh value whenever the database is modified in an undetectable way:
- Changes performed by external database connections.
- Changes performed by SQLite statements that are not compiled and executed by GRDB.
- Changes performed by SQLite statements that are not a `DELETE`, `INSERT` or `UPDATE` statement compiled and executed by GRDB.
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
+1
View File
@@ -94,6 +94,7 @@ let players: [Player] = try dbQueue.read { db in
- <doc:RecordRecommendedPractices>
- <doc:RecordTimestamps>
- <doc:SingleRowTables>
- <doc:ViewRecords>
### Application Tools
@@ -229,5 +229,11 @@ Task {
}
```
## Topics
### Supporting Types
- ``GRDBSendableMetatype``
[demo apps]: https://github.com/groue/GRDB.swift/tree/master/Documentation/DemoApps
[Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide/
+383
View File
@@ -0,0 +1,383 @@
# View Records
Define record types that target database views.
## Overview
A record type targets a [database view] as soon as its ``TableRecord/databaseTableName-3tcw2`` is the name of a view.
With such a record, some GRDB features will work out of the box, and some will throw errors without extra configuration:
```swift
// OK: Works out of the box
let captains = try Captain.fetchAll(db)
let captainCount = try Captain.fetchCount(db)
// KO: Requires extra configuration
// SQLite error 1: database view captain has no primary key
var bob = try Captain.find(db, id: "bob")
bob.name = "Bobby"
// SQLite error 1: cannot modify captain because it is a view
try bob.update(db)
```
This article explains how to solve those errors:
- How to provide a primary key to a view.
- How to define INSTEAD OF triggers that insert, update, and delete through a database view.
> important: GRDB is impacted by some SQLite limitations regarding INSTEAD OF triggers:
>
> - **Auto-incremented primary keys are not supported.** To be precise, SQLite won't expose the rowid of rows inserted via an INSTEAD OF trigger, so GRDB won't know the id of newly inserted rows. This has various nefarious consequences—see for example the important notice in the ``MutablePersistableRecord/didInsert(_:)`` callback. For more information, check this [SQLite forum thread](https://sqlite.org/forum/forumpost/707e7ed932).
> - **INSTEAD OF triggers and the RETURNING clause do not play well together.** Those are SQLite bugs. All GRDB record methods with `andFetch` in their name may return unexpected or wrong results, depending on the SQLite version. For example, the SQLite version that ships with iOS 18 has bugs, and even more in iOS 17. If you intend to use the `RETURNING` clause, it is recommended that you write tests and run them in various target operation systems.
## Preliminary Setup
To support this documentation, we need a database that contains a view. The sample code below uses <doc:Migrations> and <doc:DatabaseSchemaModifications> methods.
The database schema contains teams and players. Some players are the captain of their team. We enforce in the database schema that a given team can't have multiple captains:
```swift
var migrator = DatabaseMigrator()
migrator.registerMigration("Teams and players") { db in
try db.create(table: "team") { t in
t.primaryKey("id", .text)
t.column("name", .text).notNull()
}
try db.create(table: "player") { t in
t.primaryKey("id", .text)
t.column("name", .text).notNull()
t.belongsTo("team", onDelete: .setNull)
t.column("isCaptain", .boolean).notNull()
}
// One unique captain per team
try db.create(
indexOn: "player", columns: ["teamId"],
options: .unique,
condition: Column("isCaptain"))
}
```
We define record types for the `team` and `player` tables, as described in <doc:RecordRecommendedPractices>:
```swift
struct Team: Codable, Identifiable, FetchableRecord, PersistableRecord {
var id: String
var name: String
}
struct Player: Codable, Identifiable, FetchableRecord, PersistableRecord {
var id: String
var name: String
var teamId: String?
var isCaptain: Bool
}
```
Let's define a view and a record type for captains. At this point, both the view and the record are read-only:
```swift
migrator.registerMigration("Read-only captains") { db in
try db.execute(sql: """
CREATE VIEW captain AS
SELECT id, name, teamId
FROM player
WHERE isCaptain AND teamId IS NOT NULL;
""")
}
struct Captain: Decodable, Identifiable, FetchableRecord {
var id: String
var name: String
var teamId: String
}
```
✅ From now on, we can use the `Captain` record:
```swift
let dbQueue = try DatabaseQueue()
try migrator.migrate(dbQueue)
try dbQueue.write { db in
try Team(id: "red", name: "Red").insert(db)
try Team(id: "blue", name: "Blue").insert(db)
try Player(id: "alice", name: "Alice", teamId: "red", isCaptain: true).insert(db)
try Player(id: "bob", name: "Bob", teamId: "blue", isCaptain: true).insert(db)
try Player(id: "craig", name: "Craig", teamId: "blue", isCaptain: false).insert(db)
let captains = try Captain.fetchAll(db)
// Prints:
// Captain(id: "alice", name: "Alice", teamId: "red")
// Captain(id: "bob", name: "Bob", teamId: "blue")
print(captains)
}
```
## Specifying the primary key of a view
SQLite views do not have any primary key, so GRDB cannot introspect the database schema and automatically find the eventual primary key.
To instruct GRDB about the primary key, define a **schema source**, a type that conforms to ``DatabaseSchemaSource``. In this sample code, the schema only contains the "captain" view, so our schema source does not need to be very complicated. Check the documentation of the protocol for more detailed instructions:
```swift
struct GameSchemaSource: DatabaseSchemaSource {
/// Returns the names of the columns for the primary key in the
/// provided database view.
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
["id"]
}
}
```
We configure the database connection with this schema source:
```swift
var config = Configuration()
config.schemaSource = GameSchemaSource()
let dbQueue = try DatabaseQueue(configuration: config)
try migrator.migrate(dbQueue)
```
✅ We can now use the primary key of captains:
```swift
try dbQueue.read { db in
// [Insert some teams and players...]
let captains = try Captain.orderByPrimaryKey().fetchAll(db)
let alice = try Captain.find(db, id: "alice")
}
```
## Associations between views
To define [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) between record types that target database views, the foreign key must be explicitly provided. We define the foreign key from `captain` to `team` with a column declared as recommended in <doc:RecordRecommendedPractices>:
```swift
extension Captain {
// Time to define some columns
enum Columns {
static let teamId = Column(CodingKeys.teamId)
}
// The captain view has a foreign key to teams,
// from the teamId column to the team primary key.
// SQLite does not know about it, so we declare it explicitly:
static let teamForeignKey = ForeignKey([Columns.teamId])
// A captain belongs to a team.
static let team = belongsTo(Team.self, using: teamForeignKey)
}
extension Team {
// A team has a captain.
static let captain = hasOne(Captain.self, using: Captain.teamForeignKey)
}
```
✅ We can now use those associations:
```swift
try dbQueue.read { db in
// All teams with a captain
let teamsWithCaptain: [Team] = try Team
.joining(required: Team.captain)
.fetchAll(db)
// All (captain, team) pairs
struct CaptainWithTeam: Decodable, FetchableRecord {
var captain: Captain
var team: Team
}
let captainsWithTeam: [CaptainWithTeam] = try Captain
.including(required: Captain.team)
.asRequest(of: CaptainWithTeam.self)
.fetchAll(db)
}
```
## Inserting rows into a view
SQLite views are read-only unless we define an [INSTEAD OF trigger] that specifies which statements to run when we insert a row into a view.
INSTEAD OF triggers are very versatile, and applications can define the behavior that best fits their needs. In our sample code, inserting a captain will insert a player with the `isCaptain` flag set, and we'll also remove the `isCaptain` flag of the previous captain, if any:
```swift
migrator.registerMigration("Captain insert") { db in
try db.execute(sql: """
-- Insert trigger
CREATE TRIGGER captain_insert
INSTEAD OF INSERT ON captain
BEGIN
-- Remove previous captain
UPDATE player SET isCaptain = 0
WHERE teamId = NEW.teamId AND isCaptain;
-- Insert new captain
INSERT INTO player(id, name, teamId, isCaptain)
VALUES (NEW.id, NEW.name, NEW.teamId, 1);
END;
""")
}
// Apply the new migration
try migrator.migrate(dbQueue)
```
Let's also give an `insert()` method to the Captain record, with the ``PersistableRecord`` protocol:
```swift
extension Captain: Encodable, PersistableRecord { }
```
- note: Remember that auto-incremented primary keys are not supported, as described at the beginning of this article. Our captain view is backed by the player table which has a string primary key, so we're fine.
✅ We can directly insert captains:
```swift
try dbQueue.write {
try Team(id: "green", name: "Green").insert(db)
// Diane is the captain
try Captain(id: "diane", name: "Diane", teamId: "green").insert(db)
// Well, no: Eugene is the captain
try Captain(id: "eugene", name: "Eugene", teamId: "green").insert(db)
// Prints:
// team player captain
// green|Green diane|Diane|green|0 eugene|Eugene|green
// eugene|Eugene|green|1
try db.dumpTables(["team", "player", "captain"])
}
```
## Updating rows in a view
Just like for inserts, an INSTEAD OF trigger can specify how to update rows in a view.
In our sample code, updating a captain will update the player with the same id, and remove the `isCaptain` flag from the previous captain of the team, if any:
```swift
migrator.registerMigration("Captain update") { db in
try db.execute(sql: """
-- Update trigger
CREATE TRIGGER captain_update
INSTEAD OF UPDATE ON captain
BEGIN
-- Remove previous captain
UPDATE player SET isCaptain = 0
WHERE teamId = NEW.teamId AND isCaptain AND id <> NEW.id;
-- Update captain
UPDATE player SET name = NEW.name, teamId = NEW.teamId, isCaptain = 1
WHERE id = NEW.id;
END;
""")
}
// Apply the new migration
try migrator.migrate(dbQueue)
```
✅ Let's update captains:
```swift
try dbQueue.write {
try Team(id: "red", name: "Red").insert(db)
try Team(id: "blue", name: "Blue").insert(db)
try Captain(id: "alice", name: "Alice", teamId: "red").insert(db)
// Bob is the Blue captain.
var bob = Captain(id: "bob", name: "Bob", teamId: "blue")
try bob.insert(db)
// Bob is now Bobby, the Red captain.
// Alice is no longer the Red captain.
try bob.updateChanges(db) {
$0.name = "Bobby"
$0.teamId = "red"
}
// Prints:
// team player captain
// blue|Blue alice|Alice|red|0 bob|Bobby|red
// red|Red bob|Bobby|red|1
try db.dumpTables(["team", "player", "captain"])
}
```
## Deleting rows from a view
The last missing INSTEAD OF trigger deals with deletes:
```swift
migrator.registerMigration("Captain delete") { db in
try db.execute(sql: """
-- Delete trigger
CREATE TRIGGER captain_delete
INSTEAD OF DELETE ON captain
BEGIN
DELETE FROM player WHERE id = OLD.id;
END;
""")
}
// Apply the new migration
try migrator.migrate(dbQueue)
```
✅ Let's delete some captains:
```swift
try dbQueue.write {
// Delete Alice
try Captain.deleteOne(db, id: "alice")
// Delete Bob
let bob = try Captain.find(db, id: "bob")
try bob.delete(db)
// Delete all captains
try Captain.deleteAll()
}
```
## Going further
To exercise the techniques described here, try to define record types for these other views:
- The `enrolledPlayer` view that only contains players that belong to a team:
```swift
try db.execute(sql: """
CREATE VIEW enrolledPlayer AS
SELECT id, name, teamId, isCaptain
FROM player
WHERE teamId IS NOT NULL;
""")
```
- The `teamWithCaptainId` view that contains a `captainId` column:
```swift
try db.execute(sql: """
CREATE VIEW teamWithCaptainId AS
SELECT team.id, team.name, player.id AS captainId
FROM team
JOIN player ON player.teamId = team.id AND player.isCaptain;
""")
```
- A refactored `captain` view whose primary key is the team id—this is valid, since the schema enforces that there's a single captain for each team:
```swift
try db.execute(sql: """
CREATE VIEW captain AS
SELECT teamId, name
FROM player
WHERE isCaptain AND teamId IS NOT NULL;
""")
```
[database view]: https://www.sqlite.org/lang_createview.html
[INSTEAD OF trigger]: https://sqlite.org/lang_createtrigger.html#instead_of_triggers
+1 -1
View File
@@ -324,7 +324,7 @@ extension Database {
}
private func isShadowTable(_ tableName: String) throws -> Bool {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
// Maybe SQLCipher is too old: check actual version
if Database.sqliteLibVersionNumber >= 3037000 {
guard let table = try table(tableName) else {
+7 -4
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
+7 -4
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
+7 -4
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
+7 -4
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
+7 -4
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
/// A format that prints one line per database row, formatting values
+2 -2
View File
@@ -40,11 +40,11 @@ public struct FTS3 {
/// the `remove_diacritics=1` tokenizer argument.
case removeLegacy
#if GRDBCUSTOMSQLITE
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Remove diacritics from Latin script characters. This option matches
/// the `remove_diacritics=2` tokenizer argument.
case remove
#elseif !GRDBCIPHER
#else
/// Remove diacritics from Latin script characters. This option matches
/// the `remove_diacritics=2` tokenizer argument.
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.27+
+2 -2
View File
@@ -95,10 +95,10 @@ public struct FTS3TokenizerDescriptor: Sendable {
break
case .keep:
arguments.append("remove_diacritics=0")
#if GRDBCUSTOMSQLITE
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
case .remove:
arguments.append("remove_diacritics=2")
#elseif !GRDBCIPHER
#else
case .remove:
arguments.append("remove_diacritics=2")
#endif
+11 -8
View File
@@ -1,11 +1,14 @@
#if SQLITE_ENABLE_FTS5
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
@@ -60,12 +63,12 @@ public struct FTS5 {
/// Remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=1" tokenizer argument.
case removeLegacy
#if GRDBCUSTOMSQLITE
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=2" tokenizer argument,
/// available from SQLite 3.27.0
case remove
#elseif !GRDBCIPHER
#else
/// Remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=2" tokenizer argument,
/// available from SQLite 3.27.0
@@ -117,8 +120,8 @@ public struct FTS5 {
///
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#extending_fts5>
public static func api(_ db: Database) -> UnsafePointer<fts5_api> {
var statement: SQLiteStatement? = nil
var api: UnsafePointer<fts5_api>? = nil
var statement: SQLiteStatement?
var api: UnsafePointer<fts5_api>?
let type: StaticString = "fts5_api_ptr"
let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil)
+7 -4
View File
@@ -1,11 +1,14 @@
#if SQLITE_ENABLE_FTS5
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
/// A type that implements a custom tokenizer for the ``FTS5`` full-text engine.
+8 -5
View File
@@ -1,11 +1,14 @@
#if SQLITE_ENABLE_FTS5
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
@@ -208,7 +211,7 @@ extension Database {
self.xTokenizer = xTokenizer
var tokenizerPointer: OpaquePointer? = nil
var tokenizerPointer: OpaquePointer?
let code: CInt
if arguments.isEmpty {
code = xCreate(contextPointer, nil, 0, &tokenizerPointer)
+2 -2
View File
@@ -182,10 +182,10 @@ public struct FTS5TokenizerDescriptor: Sendable {
break
case .keep:
components.append(contentsOf: ["remove_diacritics", "0"])
#if GRDBCUSTOMSQLITE
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
case .remove:
components.append(contentsOf: ["remove_diacritics", "2"])
#elseif !GRDBCIPHER
#else
case .remove:
components.append(contentsOf: ["remove_diacritics", "2"])
#endif
+7 -4
View File
@@ -1,11 +1,14 @@
#if SQLITE_ENABLE_FTS5
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
+1 -1
View File
@@ -154,7 +154,7 @@ extension SQLSpecificExpressible {
}
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
extension SQLJSONExpressible {
/// The `->>` SQL operator.
///
+1 -1
View File
@@ -1,4 +1,4 @@
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
// MARK: - JSON
extension Database {
+181 -38
View File
@@ -18,6 +18,7 @@ import Foundation
/// ### Registering Migrations
///
/// - ``registerMigration(_:foreignKeyChecks:migrate:)``
/// - ``registerMigration(_:foreignKeyChecks:merging:migrate:)``
/// - ``ForeignKeyChecks``
///
/// ### Configuring a DatabaseMigrator
@@ -110,7 +111,7 @@ public struct DatabaseMigrator: Sendable {
/// See also ``hasSchemaChanges(_:)``.
public var eraseDatabaseOnSchemaChange = false
private var defersForeignKeyChecks = true
private var _migrations: [Migration] = []
private var _migrations: OrderedDictionary<String, Migration> = [:]
/// A new migrator.
public init() {
@@ -161,9 +162,8 @@ public struct DatabaseMigrator: Sendable {
/// Registers a migration.
///
/// The registered migration is appended to the list of migrations to run:
/// it will execute after previously registered migrations, and before
/// migrations that are registered later.
/// The registered migration is appended to the list of migrations. It
/// will execute after previously registered migrations.
///
/// For example:
///
@@ -214,6 +214,107 @@ public struct DatabaseMigrator: Sendable {
_ identifier: String,
foreignKeyChecks: ForeignKeyChecks = .deferred,
migrate: @escaping @Sendable (Database) throws -> Void)
{
registerMigration(identifier, foreignKeyChecks: foreignKeyChecks, merging: []) { db, ids in
precondition(ids.isEmpty)
try migrate(db)
}
}
/// Registers a merged migration.
///
/// Like migrations registered with ``registerMigration(_:foreignKeyChecks:migrate:)``,
/// the merged migration is appended to the list of migrations. It
/// will execute after previously registered migrations.
///
/// A merged migration merges and replaces a set of migrations defined
/// in a previous version of the application. For example, to merge the
/// migrations "v1", "v2" and "v3", redefine the "v3" migration so that
/// it merges "v1" and "v2", as in the example below.
///
/// The second argument of the `migrate` closure is the subset of merged
/// migrations that have already been applied when the merged
/// migration runs.
///
/// ```swift
/// // Old code
/// migrator.registerMigration("v1") { db in
/// // Apply schema version 1
/// }
/// migrator.registerMigration("v2") { db in
/// // Apply schema version 2
/// }
/// migrator.registerMigration("v3") { db in
/// // Apply schema version 3
/// }
///
/// // New code:
/// // - Migrations v1 and v2 are deleted.
/// // - Migration v3 is redefined and merges v1 and v2:
/// migrator.registerMigration("v3", merging: ["v1", "v2"]) { db, appliedIDs in
/// if !appliedIDs.contains("v1") {
/// // Apply schema version 1
/// }
/// if !appliedIDs.contains("v2") {
/// // Apply schema version 2
/// }
/// // Apply schema version 3
/// }
/// ```
///
/// In the above sample code, the merged migration is named like the
/// last one of the merged set. You can also give it a brand new name,
/// as in the alternative below. Notice the different logic in the
/// migration code.
///
/// **In all cases avoid naming the merged migration like the first
/// elements in the merged set** (`v1` or `v2` in our example).
///
/// ```swift
/// // Alternative new code:
/// // - Migrations v1, v2 and v3 are deleted.
/// // - The new migration v3-new merges v1, v2 and v3:
/// migrator.registerMigration("v3-new", merging: ["v1", "v2", "v3"]) { db, appliedIDs in
/// if !appliedIDs.contains("v1") {
/// // Apply schema version 1
/// }
/// if !appliedIDs.contains("v2") {
/// // Apply schema version 2
/// }
/// if !appliedIDs.contains("v3") {
/// // Apply schema version 3
/// }
/// }
/// ```
///
/// - parameters:
/// - identifier: The migration identifier.
/// - mergedIdentifiers: A set of previous migration identifiers
/// that are merged in this migration.
/// - foreignKeyChecks: This parameter is ignored if the database
/// ``Configuration`` has disabled foreign keys.
///
/// The default `.deferred` checks have the migration run with
/// disabled foreign keys, until foreign keys are checked right before
/// changes are committed on disk. These deferred checks are not
/// executed if the migrator is the result of
/// ``disablingDeferredForeignKeyChecks()``.
///
/// The `.immediate` checks have the migration run with foreign
/// keys enabled. Make sure you only use `.immediate` if the migration
/// does not perform schema changes described in
/// <https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes>
/// - migrate: A closure that performs database operations. The
/// first argument is a database connection. The second argument
/// is the set of previous migrations that has been applied when
/// the merged migration runs.
/// - precondition: No migration with the same identifier as already
/// been registered.
public mutating func registerMigration(
_ identifier: String,
foreignKeyChecks: ForeignKeyChecks = .deferred,
merging mergedIdentifiers: Set<String> = [],
migrate: @escaping @Sendable (_ db: Database, _ appliedIdentifiers: Set<String>) throws -> Void)
{
let migrationChecks: Migration.ForeignKeyChecks
switch foreignKeyChecks {
@@ -226,7 +327,18 @@ public struct DatabaseMigrator: Sendable {
case .immediate:
migrationChecks = .immediate
}
registerMigration(Migration(identifier: identifier, foreignKeyChecks: migrationChecks, migrate: migrate))
// Remove the migration identifier from the list of merged identifiers.
// Arguably, the semantics are ambiguous. And raising a fatal error
// is a high price when we can just fix the input.
var mergedIdentifiers = mergedIdentifiers
mergedIdentifiers.remove(identifier)
registerMigration(Migration(
identifier: identifier,
mergedIdentifiers: mergedIdentifiers,
foreignKeyChecks: migrationChecks,
migrate: migrate))
}
// MARK: - Applying Migrations
@@ -237,10 +349,10 @@ public struct DatabaseMigrator: Sendable {
/// - parameter writer: A DatabaseWriter.
/// - throws: The error thrown by the first failed migration.
public func migrate(_ writer: any DatabaseWriter) throws {
guard let lastMigration = _migrations.last else {
guard let lastMigrationIdentifier = _migrations.keys.last else {
return
}
try migrate(writer, upTo: lastMigration.identifier)
try migrate(writer, upTo: lastMigrationIdentifier)
}
/// Runs all unapplied migrations, in the same order as they
@@ -275,8 +387,8 @@ public struct DatabaseMigrator: Sendable {
writer.asyncBarrierWriteWithoutTransaction { dbResult in
do {
let db = try dbResult.get()
if let lastMigration = _migrations.last {
try migrate(db, upTo: lastMigration.identifier)
if let lastMigrationIdentifier = _migrations.keys.last {
try migrate(db, upTo: lastMigrationIdentifier)
}
completion(.success(db))
} catch {
@@ -314,14 +426,13 @@ public struct DatabaseMigrator: Sendable {
///
public func hasSchemaChanges(_ db: Database) throws -> Bool {
let appliedIdentifiers = try appliedIdentifiers(db)
let knownIdentifiers = Set(_migrations.map { $0.identifier })
let knownIdentifiers = Set(_migrations.keys)
if !appliedIdentifiers.isSubset(of: knownIdentifiers) {
// Database contains an unknown migration
return true
}
if let lastAppliedIdentifier = _migrations
.map(\.identifier)
if let lastAppliedIdentifier = _migrations.keys
.last(where: { appliedIdentifiers.contains($0) })
{
// Some migrations were already applied.
@@ -380,7 +491,7 @@ public struct DatabaseMigrator: Sendable {
/// The list of registered migration identifiers, in the same order as they
/// have been registered.
public var migrations: [String] {
_migrations.map(\.identifier)
_migrations.keys
}
/// Returns the identifiers of registered and applied migrations, in the
@@ -390,7 +501,7 @@ public struct DatabaseMigrator: Sendable {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func appliedMigrations(_ db: Database) throws -> [String] {
let appliedIdentifiers = try self.appliedIdentifiers(db)
return _migrations.map { $0.identifier }.filter { appliedIdentifiers.contains($0) }
return _migrations.keys.filter { appliedIdentifiers.contains($0) }
}
/// Returns the applied migration identifiers, even unregistered ones.
@@ -419,7 +530,7 @@ public struct DatabaseMigrator: Sendable {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func completedMigrations(_ db: Database) throws -> [String] {
let appliedIdentifiers = try appliedMigrations(db)
let knownIdentifiers = _migrations.map(\.identifier)
let knownIdentifiers = _migrations.keys
return zip(appliedIdentifiers, knownIdentifiers)
.prefix(while: { (applied: String, known: String) in applied == known })
.map { $0.0 }
@@ -431,7 +542,7 @@ public struct DatabaseMigrator: Sendable {
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func hasCompletedMigrations(_ db: Database) throws -> Bool {
try completedMigrations(db).last == _migrations.last?.identifier
try completedMigrations(db).last == _migrations.keys.last
}
/// A boolean value indicating whether the database refers to
@@ -444,60 +555,92 @@ public struct DatabaseMigrator: Sendable {
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func hasBeenSuperseded(_ db: Database) throws -> Bool {
let appliedIdentifiers = try self.appliedIdentifiers(db)
let knownIdentifiers = _migrations.map(\.identifier)
let knownIdentifiers = _migrations.keys
return appliedIdentifiers.contains { !knownIdentifiers.contains($0) }
}
// MARK: - Non public
private mutating func registerMigration(_ migration: Migration) {
GRDBPrecondition(
!_migrations.map({ $0.identifier }).contains(migration.identifier),
"already registered migration: \(String(reflecting: migration.identifier))")
_migrations.append(migration)
private struct Execution {
enum Mode {
case run(mergedIdentifiers: Set<String>)
case deleteMergedIdentifiers
}
var migration: Migration
var mode: Mode
}
/// Returns unapplied migration identifier,
private func unappliedMigrations(upTo targetIdentifier: String, appliedIdentifiers: [String]) -> [Migration] {
var expectedMigrations: [Migration] = []
for migration in _migrations {
expectedMigrations.append(migration)
if migration.identifier == targetIdentifier {
private mutating func registerMigration(_ migration: Migration) {
GRDBPrecondition(
_migrations[migration.identifier] == nil,
"already registered migration: \(String(reflecting: migration.identifier))")
_migrations.appendValue(migration, forKey: migration.identifier)
}
/// Returns unapplied migration executions
private func unappliedExecutions(upTo targetIdentifier: String, appliedIdentifiers: Set<String>) -> [Execution] {
var executions: [Execution] = []
var foundTarget = false
for (identifier, migration) in _migrations {
if appliedIdentifiers.contains(identifier) {
if !migration.mergedIdentifiers.isDisjoint(with: appliedIdentifiers) {
// Migration is applied, but we have some merged identifiers to delete
executions.append(Execution(migration: migration, mode: .deleteMergedIdentifiers))
}
} else {
// Migration is not applied yet.
let appliedMergedIdentifiers = migration.mergedIdentifiers.intersection(appliedIdentifiers)
executions.append(Execution(
migration: migration,
mode: .run(mergedIdentifiers: appliedMergedIdentifiers)
))
}
if identifier == targetIdentifier {
foundTarget = true
break
}
}
// targetIdentifier must refer to a registered migration
GRDBPrecondition(
expectedMigrations.last?.identifier == targetIdentifier,
foundTarget,
"undefined migration: \(String(reflecting: targetIdentifier))")
return expectedMigrations.filter { !appliedIdentifiers.contains($0.identifier) }
return executions
}
private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws {
try db.execute(sql: "CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)")
let appliedIdentifiers = try self.appliedMigrations(db)
// Subsequent migration must not be applied
if let targetIndex = _migrations.firstIndex(where: { $0.identifier == targetIdentifier }),
let lastAppliedIdentifier = appliedIdentifiers.last,
let lastAppliedIndex = _migrations.firstIndex(where: { $0.identifier == lastAppliedIdentifier }),
let appliedMigrations = try self.appliedMigrations(db) // Only known ids
if let targetIndex = _migrations.keys.firstIndex(of: targetIdentifier),
let lastAppliedMigration = appliedMigrations.last,
let lastAppliedIndex = _migrations.keys.firstIndex(of: lastAppliedMigration),
targetIndex < lastAppliedIndex
{
fatalError("database is already migrated beyond migration \(String(reflecting: targetIdentifier))")
}
let unappliedMigrations = self.unappliedMigrations(
let appliedIdentifiers = try self.appliedIdentifiers(db) // All ids, even unknown ones
let unappliedExecutions = self.unappliedExecutions(
upTo: targetIdentifier,
appliedIdentifiers: appliedIdentifiers)
if unappliedMigrations.isEmpty {
if unappliedExecutions.isEmpty {
return
}
for migration in unappliedMigrations {
try migration.run(db)
for execution in unappliedExecutions {
switch execution.mode {
case .run(let mergedIdentifiers):
try execution.migration.run(db, mergedIdentifiers: mergedIdentifiers)
case .deleteMergedIdentifiers:
try execution.migration.deleteMergedIdentifiers(db)
}
}
}
+54 -25
View File
@@ -6,40 +6,68 @@ struct Migration: Sendable {
case disabled
}
let identifier: String
var foreignKeyChecks: ForeignKeyChecks
let migrate: @Sendable (Database) throws -> Void
typealias Migrate = @Sendable (_ db: Database, _ mergedIdentifiers: Set<String>) throws -> Void
func run(_ db: Database) throws {
if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false {
switch foreignKeyChecks {
case .deferred:
try runWithDeferredForeignKeysChecks(db)
case .immediate:
try runWithImmediateForeignKeysChecks(db)
case .disabled:
try runWithDisabledForeignKeysChecks(db)
let identifier: String
let mergedIdentifiers: Set<String>
var foreignKeyChecks: ForeignKeyChecks
// Private so that the guarantees of `run(_:)` are enforced.
private let migrate: Migrate
init(
identifier: String,
mergedIdentifiers: Set<String>,
foreignKeyChecks: ForeignKeyChecks,
migrate: @escaping Migrate
) {
self.identifier = identifier
self.mergedIdentifiers = mergedIdentifiers
self.foreignKeyChecks = foreignKeyChecks
self.migrate = migrate
}
func run(_ db: Database, mergedIdentifiers: Set<String>) throws {
// Migrations access the raw SQLite schema, without alteration due
// to the schemaSource. The goal is to ensure that migrations are
// immutable, immune from spooky actions at a distance.
try db.withSchemaSource(nil) {
if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false {
switch foreignKeyChecks {
case .deferred:
try runWithDeferredForeignKeysChecks(db, mergedIdentifiers: mergedIdentifiers)
case .immediate:
try runWithImmediateForeignKeysChecks(db, mergedIdentifiers: mergedIdentifiers)
case .disabled:
try runWithDisabledForeignKeysChecks(db, mergedIdentifiers: mergedIdentifiers)
}
} else {
try runWithImmediateForeignKeysChecks(db, mergedIdentifiers: mergedIdentifiers)
}
} else {
try runWithImmediateForeignKeysChecks(db)
}
}
private func runWithImmediateForeignKeysChecks(_ db: Database) throws {
func deleteMergedIdentifiers(_ db: Database) throws {
if mergedIdentifiers.isEmpty == false {
try db.execute(literal: "DELETE FROM grdb_migrations WHERE identifier IN \(mergedIdentifiers)")
}
}
private func runWithImmediateForeignKeysChecks(_ db: Database, mergedIdentifiers: Set<String>) throws {
try db.inTransaction(.immediate) {
try migrate(db)
try insertAppliedIdentifier(db)
try migrate(db, mergedIdentifiers)
try updateAppliedIdentifier(db)
return .commit
}
}
private func runWithDisabledForeignKeysChecks(_ db: Database) throws {
private func runWithDisabledForeignKeysChecks(_ db: Database, mergedIdentifiers: Set<String>) throws {
try db.execute(sql: "PRAGMA foreign_keys = OFF")
try throwingFirstError(
execute: {
try db.inTransaction(.immediate) {
try migrate(db)
try insertAppliedIdentifier(db)
try migrate(db, mergedIdentifiers)
try updateAppliedIdentifier(db)
return .commit
}
},
@@ -48,7 +76,7 @@ struct Migration: Sendable {
})
}
private func runWithDeferredForeignKeysChecks(_ db: Database) throws {
private func runWithDeferredForeignKeysChecks(_ db: Database, mergedIdentifiers: Set<String>) throws {
// Support for database alterations described at
// https://www.sqlite.org/lang_altertable.html#otheralter
//
@@ -60,8 +88,8 @@ struct Migration: Sendable {
execute: {
// > 2. Start a transaction.
try db.inTransaction(.immediate) {
try migrate(db)
try insertAppliedIdentifier(db)
try migrate(db, mergedIdentifiers)
try updateAppliedIdentifier(db)
// > 10. If foreign key constraints were originally enabled
// > then run PRAGMA foreign_key_check to verify that the
@@ -80,7 +108,8 @@ struct Migration: Sendable {
})
}
private func insertAppliedIdentifier(_ db: Database) throws {
try db.execute(sql: "INSERT INTO grdb_migrations (identifier) VALUES (?)", arguments: [identifier])
private func updateAppliedIdentifier(_ db: Database) throws {
try deleteMergedIdentifiers(db)
try db.execute(literal: "INSERT INTO grdb_migrations (identifier) VALUES (\(identifier))")
}
}
@@ -636,7 +636,7 @@ public struct AssociationAggregate<RowDecoder> {
fileprivate let preparation: AssociationAggregatePreparation<RowDecoder>
/// The SQL name for the value of this aggregate. See forKey(_:).
var key: String? = nil
var key: String?
/// Extends the request with the associated records used to compute the
/// aggregate, and returns the aggregated expression.
@@ -362,11 +362,13 @@ extension QueryInterfaceRequest: SelectionRequest {
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
where RowDecoder: Identifiable
{
selectWhenConnected { db in
let primaryKey = try db.primaryKey(self.databaseTableName)
let databaseTableName = self.databaseTableName
return selectWhenConnected { db in
let primaryKey = try db.primaryKey(databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"selectID requires a single-column primary key in the table \(self.databaseTableName)")
"selectID requires a single-column primary key in the table \(databaseTableName)")
return [Column(primaryKey.columns[0])]
}.asRequest(of: RowDecoder.ID.self)
}
@@ -633,15 +635,18 @@ extension QueryInterfaceRequest {
@discardableResult
public func deleteAll(_ db: Database) throws -> Int {
let statement = try SQLQueryGenerator(relation: relation).makeDeleteStatement(db)
try statement.execute()
return db.changesCount
var changesCount = 0
try db.countChanges(&changesCount, forTable: relation.source.tableName) {
try statement.execute()
}
return changesCount
}
}
// MARK: - Batch Delete and Fetch
extension QueryInterfaceRequest {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Returns a `DELETE RETURNING` prepared statement.
///
/// For example:
@@ -1133,8 +1138,11 @@ extension QueryInterfaceRequest {
// database not hit
return 0
}
try updateStatement.execute()
return db.changesCount
var changesCount = 0
try db.countChanges(&changesCount, forTable: relation.source.tableName) {
try updateStatement.execute()
}
return changesCount
}
/// Updates matching rows, and returns the number of updated rows.
@@ -1168,7 +1176,7 @@ extension QueryInterfaceRequest {
// MARK: - Batch Update and Fetch
extension QueryInterfaceRequest {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Returns an `UPDATE RETURNING` prepared statement.
///
/// For example:
@@ -1864,6 +1872,18 @@ public struct ColumnAssignment {
}
}
/// A strategy for updating database rows in case of upsert conflict.
public struct UpsertUpdateStrategy: OptionSet, Sendable {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
/// Only the specified columns are updated in the existing row.
public static let noColumnUnlessSpecified = Self([])
/// All columns are updated in the existing row, unless specified otherwise.
public static let allColumns = Self(rawValue: 1 << 0)
}
extension ColumnExpression {
/// Returns an assignment of this column to an SQL expression.
///
@@ -826,10 +826,17 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
// ("foo", "bar") do not contain a unique key (primary key
// or unique index).
guard let columns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else {
fatalError("""
table \(databaseTableName) has no unique key on column(s) \
\(key.keys.sorted().joined(separator: ", "))
""")
if (try? db.viewExists(databaseTableName)) == true {
fatalError("""
database view \(databaseTableName) has no unique key on column(s) \
\(key.keys.sorted().joined(separator: ", "))
""")
} else {
fatalError("""
table \(databaseTableName) has no unique key on column(s) \
\(key.keys.sorted().joined(separator: ", "))
""")
}
}
let lowercaseColumns = columns.map { $0.lowercased() }
+7 -7
View File
@@ -517,7 +517,7 @@ public struct SQLExpression: Sendable {
/// The `>>` bitwise right shift operator
static let rightShift = BinaryOperator(">>")
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// The `->` SQL operator
static let jsonExtractJSON = BinaryOperator("->", isJSONValue: true)
@@ -1592,7 +1592,7 @@ extension SQLExpression {
case let .associativeBinary(op, expressions):
assert(expressions.count > 1)
if op == .and {
var result: Set<Int64>? = nil
var result: Set<Int64>?
for expression in expressions {
if let expressionRowIDs = try expression.identifyingRowIDs(db, for: alias) {
if var rowIDs = result {
@@ -2020,8 +2020,8 @@ struct SQLAggregateFunctionInvocation {
var name: String
var arguments: [SQLExpression]
var isDistinct = false
var ordering: SQLOrdering? = nil // SQLite 3.44.0+
var filter: SQLExpression? = nil // @available(iOS 14, macOS 10.16, tvOS 14, *) SQLite 3.30+
var ordering: SQLOrdering? // SQLite 3.44.0+
var filter: SQLExpression? // @available(iOS 14, macOS 10.16, tvOS 14, *) SQLite 3.30+
/// A boolean value indicating if a function is known to return a
/// JSON value.
@@ -2121,7 +2121,7 @@ extension SQLExpression {
}
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Returns an expression suitable in JSON building contexts.
var jsonBuilderExpression: SQLExpression {
switch preferredJSONInterpretation {
@@ -2373,7 +2373,7 @@ extension SQLSpecificExpressible {
.desc(sqlExpression)
}
#if GRDBCUSTOMSQLITE
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// An ordering term for ascending order (nulls last).
public var ascNullsLast: SQLOrdering {
.ascNullsLast(sqlExpression)
@@ -2383,7 +2383,7 @@ extension SQLSpecificExpressible {
public var descNullsFirst: SQLOrdering {
.descNullsFirst(sqlExpression)
}
#elseif !GRDBCIPHER
#else
/// An ordering term for ascending order (nulls last).
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+
public var ascNullsLast: SQLOrdering {
@@ -123,7 +123,7 @@ struct SQLForeignKeyRequest {
}
private func tableType(_ db: Database, for name: String) throws -> TableType? {
for schemaID in try db.schemaIdentifiers() {
for schemaID in try db.fetchSchemaIdentifiers() {
if try db.schema(schemaID).containsObjectNamed(name, ofType: .table) {
return TableType(isView: false)
}
+5 -5
View File
@@ -10,7 +10,7 @@ public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression {
.function("ABS", [value.sqlExpression])
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// The `AVG` SQL aggregate function.
///
/// For example:
@@ -163,7 +163,7 @@ public func max(
.simpleFunction("MAX", [value1.sqlExpression, value2.sqlExpression] + values.map(\.sqlExpression))
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// The `MAX` SQL aggregate function.
///
/// For example:
@@ -224,7 +224,7 @@ public func min(
.simpleFunction("MIN", [value1.sqlExpression, value2.sqlExpression] + values.map(\.sqlExpression))
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// The `MIN` SQL aggregate function.
///
/// For example:
@@ -269,7 +269,7 @@ public func min(_ value: some SQLSpecificExpressible) -> SQLExpression {
}
#endif
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// The `SUM` SQL aggregate function.
///
/// For example:
@@ -333,7 +333,7 @@ public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression {
}
#endif
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// The `TOTAL` SQL aggregate function.
///
/// For example:
+5 -3
View File
@@ -285,12 +285,14 @@ extension SQLRelation: Refinable {
func withStableOrder() -> Self {
with { relation in
relation.ordering = relation.ordering.appending(Ordering(orderings: { [relation] db in
if try db.tableExists(source.tableName) {
do {
// Order by primary key. Don't order by rowid because those are
// not stable: rowids can change after a vacuum.
return try db.primaryKey(source.tableName).columns.map { SQLExpression.column($0).sqlOrdering }
} else {
// Support for views: create a stable order from all columns:
} catch {
// Could not find the primary key. Assume we're ordering
// a view that is not customized with the schemaSource.
// Create a stable order from all columns:
// ORDER BY 1, 2, 3, ...
let columnCount = try SQLQueryGenerator(relation: relation).columnCount(db)
return (1...columnCount).map { SQL(sql: $0.description).sqlOrdering }
@@ -120,7 +120,7 @@ struct SQLTableGenerator {
var tableOptions: [String] = []
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
if options.contains(.strict) {
tableOptions.append("STRICT")
}
@@ -350,7 +350,7 @@ public final class ColumnDefinition {
return self
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Defines the column as a generated column.
///
/// For example:
@@ -79,7 +79,7 @@ public final class TableAlteration {
alterations.append(.addColumnLiteral(literal))
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Renames a column.
///
/// For example:
@@ -15,7 +15,7 @@ public struct TableOptions: OptionSet, Sendable {
/// Such tables can not be tracked with <doc:DatabaseObservation> tools.
public static let withoutRowID = TableOptions(rawValue: 1 << 2)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Creates a [STRICT](https://www.sqlite.org/stricttables.html) table.
public static let strict = TableOptions(rawValue: 1 << 3)
#else
+1 -1
View File
@@ -39,7 +39,7 @@ import Foundation // For JSONEncoder
/// - ``databaseChanges(from:)``
/// - ``databaseChanges(modify:)``
/// - ``databaseEquals(_:)``
public protocol EncodableRecord {
public protocol EncodableRecord: GRDBSendableMetatype {
/// Encodes the record into the provided persistence container.
///
/// In your implementation of this method, store in the `container` argument
+8 -9
View File
@@ -1,10 +1,13 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
import SQLite3
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
#elseif SQLCipher
import SQLCipher
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
import GRDBSQLite
#endif
import Foundation
@@ -519,20 +522,16 @@ private struct SingleValueRowDecoder<R: FetchableRecord>: SingleValueDecodingCon
func decode(_ type: Int16.Type) throws -> Int16 { try columnDecoder.decode(type) }
func decode(_ type: Int32.Type) throws -> Int32 { try columnDecoder.decode(type) }
func decode(_ type: Int64.Type) throws -> Int64 { try columnDecoder.decode(type) }
#if compiler(>=6)
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
func decode(_ type: Int128.Type) throws -> Int128 { try columnDecoder.decode(type) }
#endif
func decode(_ type: UInt.Type) throws -> UInt { try columnDecoder.decode(type) }
func decode(_ type: UInt8.Type) throws -> UInt8 { try columnDecoder.decode(type) }
func decode(_ type: UInt16.Type) throws -> UInt16 { try columnDecoder.decode(type) }
func decode(_ type: UInt32.Type) throws -> UInt32 { try columnDecoder.decode(type) }
func decode(_ type: UInt64.Type) throws -> UInt64 { try columnDecoder.decode(type) }
#if compiler(>=6)
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
func decode(_ type: UInt128.Type) throws -> UInt128 { try columnDecoder.decode(type) }
#endif
func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
if let type = T.self as? any FetchableRecord.Type {
// Prefer FetchableRecord decoding over Decodable.
+16 -13
View File
@@ -42,6 +42,7 @@ final class DAO<Record: MutablePersistableRecord> {
func upsertStatement(
_ db: Database,
onConflict conflictTargetColumns: [String],
updating strategy: UpsertUpdateStrategy,
doUpdate assignments: ((_ excluded: TableAlias<Record>) -> [ColumnAssignment])?,
updateCondition: ((
_ existing: TableAlias<Record>,
@@ -78,20 +79,22 @@ final class DAO<Record: MutablePersistableRecord> {
sql += " DO UPDATE SET "
let excluded = TableAlias<Record>(name: "excluded")
var assignments = assignments?(excluded) ?? []
let lowercaseExcludedColumns = Set(primaryKey.columns.map { $0.lowercased() })
.union(conflictTargetColumns.map { $0.lowercased() })
for column in persistenceContainer.columns {
let lowercasedColumn = column.lowercased()
if lowercaseExcludedColumns.contains(lowercasedColumn) {
// excluded (primary key or conflict target)
continue
if strategy.contains(.allColumns) {
let lowercaseExcludedColumns = Set(primaryKey.columns.map { $0.lowercased() })
.union(conflictTargetColumns.map { $0.lowercased() })
for column in persistenceContainer.columns {
let lowercasedColumn = column.lowercased()
if lowercaseExcludedColumns.contains(lowercasedColumn) {
// excluded (primary key or conflict target)
continue
}
if assignments.contains(where: { $0.columnName.lowercased() == lowercasedColumn }) {
// already updated from the `assignments` argument
continue
}
// overwrite
assignments.append(Column(column).set(to: excluded[column]))
}
if assignments.contains(where: { $0.columnName.lowercased() == lowercasedColumn }) {
// already updated from the `assignments` argument
continue
}
// overwrite
assignments.append(Column(column).set(to: excluded[column]))
}
let context = SQLGenerationContext(db)
let updateSQL = try assignments
@@ -53,7 +53,10 @@ extension MutablePersistableRecord {
// Nil primary key
return false
}
try statement.execute()
return db.changesCount > 0
var changesCount = 0
try db.countChanges(&changesCount, forTable: type(of: self).databaseTableName) {
try statement.execute()
}
return changesCount > 0
}
}
@@ -90,7 +90,7 @@ extension MutablePersistableRecord {
// MARK: - Insert and Fetch
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -86,7 +86,7 @@ extension MutablePersistableRecord {
// MARK: - Save and Fetch
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
@@ -213,7 +213,7 @@ extension MutablePersistableRecord {
// MARK: - Update and Fetch
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Executes an `UPDATE RETURNING` statement on all columns, and returns a
/// new record built from the updated row.
///
@@ -839,7 +839,7 @@ extension MutablePersistableRecord {
// MARK: - Internals
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
@inlinable // allow specialization so that empty callbacks are removed
func updateChangesAndFetch<T>(
_ db: Database,
@@ -956,8 +956,11 @@ extension MutablePersistableRecord {
// Nil primary key
try dao.recordNotFound()
}
let returned = try fetch(statement)
if db.changesCount == 0 {
var changesCount = 0
let returned = try db.countChanges(&changesCount, forTable: type(of: self).databaseTableName) {
try fetch(statement)
}
if changesCount == 0 {
// No row was updated
try dao.recordNotFound()
}
+283 -126
View File
@@ -1,7 +1,7 @@
// MARK: - Upsert
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Executes an `INSERT ON CONFLICT DO UPDATE` statement.
///
/// The upsert behavior is triggered by a violation of any uniqueness
@@ -73,55 +73,52 @@ extension MutablePersistableRecord {
/// let upsertedPlayer = try player.upsertAndFetch(db)
/// ```
///
/// With `conflictTarget` and `assignments` arguments, you can further
/// control the upsert behavior. Make sure you check
/// With the `conflictTarget`, `strategy`, and `assignments` arguments,
/// you can further control the upsert behavior. Make sure you check
/// <https://www.sqlite.org/lang_UPSERT.html> for detailed information.
///
/// The conflict target are the columns of the uniqueness constraint
/// (primary key or unique index) that triggers the upsert. If empty, all
/// uniqueness constraint are considered.
///
/// The assignments describe how to update columns in case of violation of
/// a uniqueness constraint. In the next example, we insert the new
/// vocabulary word "jovial" if that word is not already in the dictionary.
/// If the word is already in the dictionary, it increments the counter,
/// does not overwrite the tainted flag, and overwrites the
/// remaining columns:
/// The strategy controls which columns are updated in case of
/// uniqueness constraint violation: all columns unless specified (the
/// default), or only the specified columns.
///
/// For example, compare:
///
/// ```swift
/// // CREATE TABLE vocabulary(
/// // word TEXT PRIMARY KEY,
/// // kind TEXT NOT NULL,
/// // isTainted BOOLEAN DEFAULT 0,
/// // count INT DEFAULT 1))
/// struct Vocabulary: Encodable, MutablePersistableRecord {
/// var word: String
/// var kind: String
/// var isTainted: Bool
/// // In case of conflict, updates all columns, including columns added
/// // in a future migration.
/// let upserted = try player.upsertAndFetch(db)
///
/// // In case of conflict, updates all columns, including future ones,
/// // but 'score'.
/// let upserted = try player.upsertAndFetch(db) { _ in
/// [Column("score").noOverwrite]
/// }
///
/// // INSERT INTO vocabulary(word, kind, isTainted)
/// // VALUES('jovial', 'adjective', 0)
/// // ON CONFLICT(word) DO UPDATE SET \
/// // count = count + 1,
/// // kind = excluded.kind
/// // RETURNING *
/// var vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false)
/// let upserted = try vocabulary.upsertAndFetch(
/// db,
/// onConflict: ["word"],
/// doUpdate: { _ in
/// [Column("count") += 1,
/// Column("isTainted").noOverwrite]
/// })
/// // In case of conflict, do not update any column.
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified)
///
/// // In case of conflict, only update 'name'.
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified) { excluded in
/// [Column("name").set(to: excluded[Column("name")])]
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictTarget: The conflict target.
/// - parameter strategy: The default strategy, `.allColumns`, updates
/// all columns in case of conflict, unless specified otherwise in the
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
/// update the columns assigned in the `assignments` parameter.
/// - parameter assignments: An optional function that returns an array of
/// ``ColumnAssignment``. In case of violation of a uniqueness
/// constraints, these assignments are performed, and remaining columns
/// are overwritten by inserted values.
/// constraint, these assignments are performed, and remaining columns
/// are overwritten by inserted values, or not, depending on the
/// chosen `strategy`. To use the value that would have been inserted
/// had the constraint not failed, use the `excluded` parameter.
/// - returns: The upserted record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
@@ -129,26 +126,36 @@ extension MutablePersistableRecord {
public mutating func upsertAndFetch(
_ db: Database,
onConflict conflictTarget: [String] = [],
updating strategy: UpsertUpdateStrategy = .allColumns,
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
throws -> Self
where Self: FetchableRecord
{
try upsertAndFetch(db, as: Self.self, onConflict: conflictTarget, doUpdate: assignments)
try upsertAndFetch(
db, as: Self.self, onConflict: conflictTarget,
updating: strategy, doUpdate: assignments)
}
/// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and
/// returns the upserted record.
///
/// See `upsertAndFetch(_:onConflict:doUpdate:)` for more information about
/// the `conflictTarget` and `assignments` parameters.
/// See ``upsertAndFetch(_:onConflict:updating:doUpdate:)`` for more
/// information about the `conflictTarget`, `strategy`, and
/// `assignments` parameters.
///
/// - parameter db: A database connection.
/// - parameter returnedType: The type of the returned record.
/// - parameter conflictTarget: The conflict target.
/// - parameter strategy: The default strategy, `.allColumns`, updates
/// all columns in case of conflict, unless specified otherwise in the
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
/// update the columns assigned in the `assignments` parameter.
/// - parameter assignments: An optional function that returns an array of
/// ``ColumnAssignment``. In case of violation of a uniqueness
/// constraints, these assignments are performed, and remaining columns
/// are overwritten by inserted values.
/// constraint, these assignments are performed, and remaining columns
/// are overwritten by inserted values, or not, depending on the
/// chosen `strategy`. To use the value that would have been inserted
/// had the constraint not failed, use the `excluded` parameter.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
@@ -157,6 +164,7 @@ extension MutablePersistableRecord {
_ db: Database,
as returnedType: T.Type,
onConflict conflictTarget: [String] = [],
updating strategy: UpsertUpdateStrategy = .allColumns,
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
throws -> T
{
@@ -166,7 +174,7 @@ extension MutablePersistableRecord {
try aroundSave(db) {
success = try upsertAndFetchWithCallbacks(
db, onConflict: conflictTarget,
doUpdate: assignments,
updating: strategy, doUpdate: assignments,
selection: T.databaseSelection,
decode: { try T(row: $0) })
return PersistenceSuccess(success!.inserted)
@@ -250,55 +258,52 @@ extension MutablePersistableRecord {
/// let upsertedPlayer = try player.upsertAndFetch(db)
/// ```
///
/// With `conflictTarget` and `assignments` arguments, you can further
/// control the upsert behavior. Make sure you check
/// With the `conflictTarget`, `strategy`, and `assignments` arguments,
/// you can further control the upsert behavior. Make sure you check
/// <https://www.sqlite.org/lang_UPSERT.html> for detailed information.
///
/// The conflict target are the columns of the uniqueness constraint
/// (primary key or unique index) that triggers the upsert. If empty, all
/// uniqueness constraint are considered.
///
/// The assignments describe how to update columns in case of violation of
/// a uniqueness constraint. In the next example, we insert the new
/// vocabulary word "jovial" if that word is not already in the dictionary.
/// If the word is already in the dictionary, it increments the counter,
/// does not overwrite the tainted flag, and overwrites the
/// remaining columns:
/// The strategy controls which columns are updated in case of
/// uniqueness constraint violation: all columns unless specified (the
/// default), or only the specified columns.
///
/// For example, compare:
///
/// ```swift
/// // CREATE TABLE vocabulary(
/// // word TEXT PRIMARY KEY,
/// // kind TEXT NOT NULL,
/// // isTainted BOOLEAN DEFAULT 0,
/// // count INT DEFAULT 1))
/// struct Vocabulary: Encodable, MutablePersistableRecord {
/// var word: String
/// var kind: String
/// var isTainted: Bool
/// // In case of conflict, updates all columns, including columns added
/// // in a future migration.
/// let upserted = try player.upsertAndFetch(db)
///
/// // In case of conflict, updates all columns, including future ones,
/// // but 'score'.
/// let upserted = try player.upsertAndFetch(db) { _ in
/// [Column("score").noOverwrite]
/// }
///
/// // INSERT INTO vocabulary(word, kind, isTainted)
/// // VALUES('jovial', 'adjective', 0)
/// // ON CONFLICT(word) DO UPDATE SET \
/// // count = count + 1,
/// // kind = excluded.kind
/// // RETURNING *
/// var vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false)
/// let upserted = try vocabulary.upsertAndFetch(
/// db,
/// onConflict: ["word"],
/// doUpdate: { _ in
/// [Column("count") += 1,
/// Column("isTainted").noOverwrite]
/// })
/// // In case of conflict, do not update any column.
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified)
///
/// // In case of conflict, only update 'name'.
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified) { excluded in
/// [Column("name").set(to: excluded[Column("name")])]
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictTarget: The conflict target.
/// - parameter strategy: The default strategy, `.allColumns`, updates
/// all columns in case of conflict, unless specified otherwise in the
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
/// update the columns assigned in the `assignments` parameter.
/// - parameter assignments: An optional function that returns an array of
/// ``ColumnAssignment``. In case of violation of a uniqueness
/// constraints, these assignments are performed, and remaining columns
/// are overwritten by inserted values.
/// constraint, these assignments are performed, and remaining columns
/// are overwritten by inserted values, or not, depending on the
/// chosen `strategy`. To use the value that would have been inserted
/// had the constraint not failed, use the `excluded` parameter.
/// - returns: The upserted record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
@@ -307,26 +312,36 @@ extension MutablePersistableRecord {
public mutating func upsertAndFetch(
_ db: Database,
onConflict conflictTarget: [String] = [],
updating strategy: UpsertUpdateStrategy = .allColumns,
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
throws -> Self
where Self: FetchableRecord
{
try upsertAndFetch(db, as: Self.self, onConflict: conflictTarget, doUpdate: assignments)
try upsertAndFetch(
db, as: Self.self, onConflict: conflictTarget,
updating: strategy, doUpdate: assignments)
}
/// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and
/// returns the upserted record.
///
/// See ``upsertAndFetch(_:onConflict:doUpdate:)`` for more information
/// about the `conflictTarget` and `assignments` parameters.
/// See ``upsertAndFetch(_:onConflict:updating:doUpdate:)`` for more
/// information about the `conflictTarget`, `strategy`, and
/// `assignments` parameters.
///
/// - parameter db: A database connection.
/// - parameter returnedType: The type of the returned record.
/// - parameter conflictTarget: The conflict target.
/// - parameter strategy: The default strategy, `.allColumns`, updates
/// all columns in case of conflict, unless specified otherwise in the
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
/// update the columns assigned in the `assignments` parameter.
/// - parameter assignments: An optional function that returns an array of
/// ``ColumnAssignment``. In case of violation of a uniqueness
/// constraints, these assignments are performed, and remaining columns
/// are overwritten by inserted values.
/// constraint, these assignments are performed, and remaining columns
/// are overwritten by inserted values, or not, depending on the
/// chosen `strategy`. To use the value that would have been inserted
/// had the constraint not failed, use the `excluded` parameter.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
@@ -336,6 +351,7 @@ extension MutablePersistableRecord {
_ db: Database,
as returnedType: T.Type,
onConflict conflictTarget: [String] = [],
updating strategy: UpsertUpdateStrategy = .allColumns,
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
throws -> T
{
@@ -345,7 +361,7 @@ extension MutablePersistableRecord {
try aroundSave(db) {
success = try upsertAndFetchWithCallbacks(
db, onConflict: conflictTarget,
doUpdate: assignments,
updating: strategy, doUpdate: assignments,
selection: T.databaseSelection,
decode: { try T(row: $0) })
return PersistenceSuccess(success!.inserted)
@@ -367,18 +383,17 @@ extension MutablePersistableRecord {
mutating func upsertWithCallbacks(_ db: Database)
throws -> InsertionSuccess
{
let (inserted, _) = try upsertAndFetchWithCallbacks(
try upsertWithCallbacks(
db, onConflict: [],
doUpdate: nil,
selection: [],
decode: { _ in /* Nothing to decode */ })
return inserted
updating: .allColumns,
doUpdate: nil)
}
@inlinable // allow specialization so that empty callbacks are removed
mutating func upsertAndFetchWithCallbacks<T>(
_ db: Database,
onConflict conflictTarget: [String],
updating strategy: UpsertUpdateStrategy,
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])?,
selection: [any SQLSelectable],
decode: (Row) throws -> T)
@@ -390,7 +405,7 @@ extension MutablePersistableRecord {
try aroundInsert(db) {
success = try upsertAndFetchWithoutCallbacks(
db, onConflict: conflictTarget,
doUpdate: assignments,
updating: strategy, doUpdate: assignments,
selection: selection,
decode: decode)
return success!.inserted
@@ -403,63 +418,205 @@ extension MutablePersistableRecord {
return success
}
@inlinable // allow specialization so that empty callbacks are removed
mutating func upsertWithCallbacks(
_ db: Database,
onConflict conflictTarget: [String],
updating strategy: UpsertUpdateStrategy,
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])?
) throws -> InsertionSuccess {
try willInsert(db)
var inserted: InsertionSuccess?
try aroundInsert(db) {
inserted = try upsertWithoutCallbacks(
db, onConflict: conflictTarget,
updating: strategy, doUpdate: assignments)
return inserted!
}
guard let inserted else {
try persistenceCallbackMisuse("aroundInsert")
}
didInsert(inserted)
return inserted
}
/// Executes an `INSERT` statement, and DOES NOT run
/// insertion callbacks.
@usableFromInline
func upsertWithoutCallbacks(
_ db: Database,
onConflict conflictTarget: [String],
updating strategy: UpsertUpdateStrategy,
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])?)
throws -> InsertionSuccess
{
let primaryKey = try db.primaryKey(Self.databaseTableName)
if primaryKey.tableHasRowID {
let dao = try DAO(db, self)
let statement = try dao.upsertStatement(
db, onConflict: conflictTarget,
updating: strategy,
doUpdate: assignments,
updateCondition: nil,
returning: [Column.rowID])
let cursor = try Row.fetchCursor(statement)
// Keep cursor alive until we can process the fetched row
let rowid: Int64 = try withExtendedLifetime(cursor) { cursor in
guard let row = try cursor.next() else {
throw DatabaseError(message: "Insertion failed")
}
let rowid: Int64 = row[0]
// Now that we have fetched the values we need, we could stop
// there. But let's make sure we fully consume the cursor
// anyway, until SQLITE_DONE. This is necessary, for example,
// for upserts in tables that are synchronized with an
// FTS5 table.
// See <https://github.com/groue/GRDB.swift/issues/1390>
while try cursor.next() != nil { }
return rowid
}
// Update the persistenceContainer with the inserted rowid.
// This allows the Record class to set its `hasDatabaseChanges` property
// to false in its `aroundInsert` callback.
var persistenceContainer = dao.persistenceContainer
let rowIDColumn = dao.primaryKey.rowIDColumn
if let rowIDColumn {
persistenceContainer[rowIDColumn] = rowid
}
let inserted = InsertionSuccess(
rowID: rowid,
rowIDColumn: rowIDColumn,
persistenceContainer: persistenceContainer)
return inserted
} else {
let dao = try DAO(db, self)
let statement = try dao.upsertStatement(
db, onConflict: conflictTarget,
updating: strategy,
doUpdate: assignments,
updateCondition: nil,
returning: [])
let cursor = try Row.fetchCursor(statement)
// Let's make sure we fully consume the cursor, until SQLITE_DONE.
// This is necessary, for example, for upserts in tables that
// are synchronized with an FTS5 table.
// See <https://github.com/groue/GRDB.swift/issues/1390>
while try cursor.next() != nil { }
let inserted = InsertionSuccess(
rowID: 0, // Meaningless in WITHOUT ROWID tables.
rowIDColumn: nil,
persistenceContainer: dao.persistenceContainer)
return inserted
}
}
/// Executes an `INSERT RETURNING` statement, and DOES NOT run
/// insertion callbacks.
@usableFromInline
func upsertAndFetchWithoutCallbacks<T>(
_ db: Database,
onConflict conflictTarget: [String],
updating strategy: UpsertUpdateStrategy,
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])?,
selection: [any SQLSelectable],
decode: (Row) throws -> T)
throws -> (InsertionSuccess, T)
{
// Append the rowID to the returned columns
let selection = selection + [Column.rowID]
let primaryKey = try db.primaryKey(Self.databaseTableName)
let dao = try DAO(db, self)
let statement = try dao.upsertStatement(
db,
onConflict: conflictTarget,
doUpdate: assignments,
updateCondition: nil,
returning: selection)
let cursor = try Row.fetchCursor(statement)
// Keep cursor alive until we can process the fetched row
let (rowid, returned): (Int64, T) = try withExtendedLifetime(cursor) { cursor in
guard let row = try cursor.next() else {
throw DatabaseError(message: "Insertion failed")
if primaryKey.tableHasRowID {
// Append the rowID to the returned columns
let selection = selection + [Column.rowID]
let dao = try DAO(db, self)
let statement = try dao.upsertStatement(
db, onConflict: conflictTarget,
updating: strategy,
doUpdate: assignments,
updateCondition: nil,
returning: selection)
let cursor = try Row.fetchCursor(statement)
// Keep cursor alive until we can process the fetched row
let (rowid, returned): (Int64, T) = try withExtendedLifetime(cursor) { cursor in
guard let row = try cursor.next() else {
throw DatabaseError(message: "Insertion failed")
}
// Rowid is the last column
let rowid: Int64 = row[row.count - 1]
let returned = try decode(row)
// Now that we have fetched the values we need, we could stop
// there. But let's make sure we fully consume the cursor
// anyway, until SQLITE_DONE. This is necessary, for example,
// for upserts in tables that are synchronized with an
// FTS5 table.
// See <https://github.com/groue/GRDB.swift/issues/1390>
while try cursor.next() != nil { }
return (rowid, returned)
}
// Rowid is the last column
let rowid: Int64 = row[row.count - 1]
let returned = try decode(row)
// Update the persistenceContainer with the inserted rowid.
// This allows the Record class to set its `hasDatabaseChanges` property
// to false in its `aroundInsert` callback.
var persistenceContainer = dao.persistenceContainer
let rowIDColumn = dao.primaryKey.rowIDColumn
if let rowIDColumn {
persistenceContainer[rowIDColumn] = rowid
}
// Now that we have fetched the values we need, we could stop
// there. But let's make sure we fully consume the cursor
// anyway, until SQLITE_DONE. This is necessary, for example,
// for upserts in tables that are synchronized with an
// FTS5 table.
// See <https://github.com/groue/GRDB.swift/issues/1390>
while try cursor.next() != nil { }
let inserted = InsertionSuccess(
rowID: rowid,
rowIDColumn: rowIDColumn,
persistenceContainer: persistenceContainer)
return (inserted, returned)
} else {
let dao = try DAO(db, self)
let statement = try dao.upsertStatement(
db, onConflict: conflictTarget,
updating: strategy,
doUpdate: assignments,
updateCondition: nil,
returning: selection)
let cursor = try Row.fetchCursor(statement)
return (rowid, returned)
// Keep cursor alive until we can process the fetched row
let returned: T = try withExtendedLifetime(cursor) { cursor in
guard let row = try cursor.next() else {
throw DatabaseError(message: "Insertion failed")
}
let returned = try decode(row)
// Now that we have fetched the values we need, we could stop
// there. But let's make sure we fully consume the cursor
// anyway, until SQLITE_DONE. This is necessary, for example,
// for upserts in tables that are synchronized with an
// FTS5 table.
// See <https://github.com/groue/GRDB.swift/issues/1390>
while try cursor.next() != nil { }
return returned
}
let inserted = InsertionSuccess(
rowID: 0, // Meaningless in WITHOUT ROWID tables.
rowIDColumn: nil,
persistenceContainer: dao.persistenceContainer)
return (inserted, returned)
}
// Update the persistenceContainer with the inserted rowid.
// This allows the Record class to set its `hasDatabaseChanges` property
// to false in its `aroundInsert` callback.
var persistenceContainer = dao.persistenceContainer
let rowIDColumn = dao.primaryKey.rowIDColumn
if let rowIDColumn {
persistenceContainer[rowIDColumn] = rowid
}
let inserted = InsertionSuccess(
rowID: rowid,
rowIDColumn: rowIDColumn,
persistenceContainer: persistenceContainer)
return (inserted, returned)
}
}
+8 -2
View File
@@ -62,8 +62,9 @@
/// - ``insertAndFetch(_:onConflict:as:)``
/// - ``insertAndFetch(_:onConflict:selection:fetch:)``
/// - ``insertAndFetch(_:onConflict:fetch:select:)``
/// - ``upsertAndFetch(_:onConflict:doUpdate:)``
/// - ``upsertAndFetch(_:as:onConflict:doUpdate:)``
/// - ``upsertAndFetch(_:onConflict:updating:doUpdate:)``
/// - ``upsertAndFetch(_:as:onConflict:updating:doUpdate:)``
/// - ``UpsertUpdateStrategy``
///
/// ### Updating a Record
///
@@ -184,6 +185,11 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord {
/// }
/// ```
///
/// - important: Due to an SQLite limitation, this callback is
/// unreliable when the record type writes into a database view
/// through an INSTEAD OF trigger. The `inserted.rowID` value is
/// not the rowid of the inserted row.
///
/// - parameter inserted: Information about the inserted row.
mutating func didInsert(_ inserted: InsertionSuccess)
+1 -1
View File
@@ -55,7 +55,7 @@ extension PersistableRecord {
// MARK: - Insert and Fetch
extension PersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
+1 -1
View File
@@ -38,7 +38,7 @@ extension PersistableRecord {
// MARK: - Save and Fetch
extension PersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
+124 -85
View File
@@ -1,7 +1,7 @@
// MARK: - Upsert
extension PersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Executes an `INSERT ON CONFLICT DO UPDATE` statement.
///
/// The upsert behavior is triggered by a violation of any uniqueness
@@ -73,55 +73,52 @@ extension PersistableRecord {
/// let upsertedPlayer = try player.upsertAndFetch(db)
/// ```
///
/// With `conflictTarget` and `assignments` arguments, you can further
/// control the upsert behavior. Make sure you check
/// With the `conflictTarget`, `strategy`, and `assignments` arguments,
/// you can further control the upsert behavior. Make sure you check
/// <https://www.sqlite.org/lang_UPSERT.html> for detailed information.
///
/// The conflict target are the columns of the uniqueness constraint
/// (primary key or unique index) that triggers the upsert. If empty, all
/// uniqueness constraint are considered.
///
/// The assignments describe how to update columns in case of violation of
/// a uniqueness constraint. In the next example, we insert the new
/// vocabulary word "jovial" if that word is not already in the dictionary.
/// If the word is already in the dictionary, it increments the counter,
/// does not overwrite the tainted flag, and overwrites the
/// remaining columns:
/// The strategy controls which columns are updated in case of
/// uniqueness constraint violation: all columns unless specified (the
/// default), or only the specified columns.
///
/// For example, compare:
///
/// ```swift
/// // CREATE TABLE vocabulary(
/// // word TEXT PRIMARY KEY,
/// // kind TEXT NOT NULL,
/// // isTainted BOOLEAN DEFAULT 0,
/// // count INT DEFAULT 1))
/// struct Vocabulary: Encodable, PersistableRecord {
/// var word: String
/// var kind: String
/// var isTainted: Bool
/// // In case of conflict, updates all columns, including columns added
/// // in a future migration.
/// let upserted = try player.upsertAndFetch(db)
///
/// // In case of conflict, updates all columns, including future ones,
/// // but 'score'.
/// let upserted = try player.upsertAndFetch(db) { _ in
/// [Column("score").noOverwrite]
/// }
///
/// // INSERT INTO vocabulary(word, kind, isTainted)
/// // VALUES('jovial', 'adjective', 0)
/// // ON CONFLICT(word) DO UPDATE SET \
/// // count = count + 1,
/// // kind = excluded.kind
/// // RETURNING *
/// let vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false)
/// let upserted = try vocabulary.upsertAndFetch(
/// db,
/// onConflict: ["word"],
/// doUpdate: { _ in
/// [Column("count") += 1,
/// Column("isTainted").noOverwrite]
/// })
/// // In case of conflict, do not update any column.
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified)
///
/// // In case of conflict, only update 'name'.
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified) { excluded in
/// [Column("name").set(to: excluded[Column("name")])]
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictTarget: The conflict target.
/// - parameter strategy: The default strategy, `.allColumns`, updates
/// all columns in case of conflict, unless specified otherwise in the
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
/// update the columns assigned in the `assignments` parameter.
/// - parameter assignments: An optional function that returns an array of
/// ``ColumnAssignment``. In case of violation of a uniqueness
/// constraints, these assignments are performed, and remaining columns
/// are overwritten by inserted values.
/// constraint, these assignments are performed, and remaining columns
/// are overwritten by inserted values, or not, depending on the
/// chosen `strategy`. To use the value that would have been inserted
/// had the constraint not failed, use the `excluded` parameter.
/// - returns: The upserted record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
@@ -129,26 +126,36 @@ extension PersistableRecord {
public func upsertAndFetch(
_ db: Database,
onConflict conflictTarget: [String] = [],
updating strategy: UpsertUpdateStrategy = .allColumns,
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
throws -> Self
where Self: FetchableRecord
{
try upsertAndFetch(db, as: Self.self, onConflict: conflictTarget, doUpdate: assignments)
try upsertAndFetch(
db, as: Self.self, onConflict: conflictTarget,
updating: strategy, doUpdate: assignments)
}
/// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and
/// returns the upserted record.
///
/// See `upsertAndFetch(_:onConflict:doUpdate:)` for more information about
/// the `conflictTarget` and `assignments` parameters.
/// See ``upsertAndFetch(_:onConflict:updating:doUpdate:)`` for more
/// information about the `conflictTarget`, `strategy`, and
/// `assignments` parameters.
///
/// - parameter db: A database connection.
/// - parameter returnedType: The type of the returned record.
/// - parameter conflictTarget: The conflict target.
/// - parameter strategy: The default strategy, `.allColumns`, updates
/// all columns in case of conflict, unless specified otherwise in the
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
/// update the columns assigned in the `assignments` parameter.
/// - parameter assignments: An optional function that returns an array of
/// ``ColumnAssignment``. In case of violation of a uniqueness
/// constraints, these assignments are performed, and remaining columns
/// are overwritten by inserted values.
/// constraint, these assignments are performed, and remaining columns
/// are overwritten by inserted values, or not, depending on the
/// chosen `strategy`. To use the value that would have been inserted
/// had the constraint not failed, use the `excluded` parameter.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
@@ -157,6 +164,7 @@ extension PersistableRecord {
_ db: Database,
as returnedType: T.Type,
onConflict conflictTarget: [String] = [],
updating strategy: UpsertUpdateStrategy = .allColumns,
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
throws -> T
{
@@ -166,7 +174,7 @@ extension PersistableRecord {
try aroundSave(db) {
success = try upsertAndFetchWithCallbacks(
db, onConflict: conflictTarget,
doUpdate: assignments,
updating: strategy, doUpdate: assignments,
selection: T.databaseSelection,
decode: { try T(row: $0) })
return PersistenceSuccess(success!.inserted)
@@ -250,55 +258,52 @@ extension PersistableRecord {
/// let upsertedPlayer = try player.upsertAndFetch(db)
/// ```
///
/// With `conflictTarget` and `assignments` arguments, you can further
/// control the upsert behavior. Make sure you check
/// With the `conflictTarget`, `strategy`, and `assignments` arguments,
/// you can further control the upsert behavior. Make sure you check
/// <https://www.sqlite.org/lang_UPSERT.html> for detailed information.
///
/// The conflict target are the columns of the uniqueness constraint
/// (primary key or unique index) that triggers the upsert. If empty, all
/// uniqueness constraint are considered.
///
/// The assignments describe how to update columns in case of violation of
/// a uniqueness constraint. In the next example, we insert the new
/// vocabulary word "jovial" if that word is not already in the dictionary.
/// If the word is already in the dictionary, it increments the counter,
/// does not overwrite the tainted flag, and overwrites the
/// remaining columns:
/// The strategy controls which columns are updated in case of
/// uniqueness constraint violation: all columns unless specified (the
/// default), or only the specified columns.
///
/// For example, compare:
///
/// ```swift
/// // CREATE TABLE vocabulary(
/// // word TEXT PRIMARY KEY,
/// // kind TEXT NOT NULL,
/// // isTainted BOOLEAN DEFAULT 0,
/// // count INT DEFAULT 1))
/// struct Vocabulary: Encodable, PersistableRecord {
/// var word: String
/// var kind: String
/// var isTainted: Bool
/// // In case of conflict, updates all columns, including columns added
/// // in a future migration.
/// let upserted = try player.upsertAndFetch(db)
///
/// // In case of conflict, updates all columns, including future ones,
/// // but 'score'.
/// let upserted = try player.upsertAndFetch(db) { _ in
/// [Column("score").noOverwrite]
/// }
///
/// // INSERT INTO vocabulary(word, kind, isTainted)
/// // VALUES('jovial', 'adjective', 0)
/// // ON CONFLICT(word) DO UPDATE SET \
/// // count = count + 1,
/// // kind = excluded.kind
/// // RETURNING *
/// let vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false)
/// let upserted = try vocabulary.upsertAndFetch(
/// db,
/// onConflict: ["word"],
/// doUpdate: { _ in
/// [Column("count") += 1,
/// Column("isTainted").noOverwrite]
/// })
/// // In case of conflict, do not update any column.
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified)
///
/// // In case of conflict, only update 'name'.
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified) { excluded in
/// [Column("name").set(to: excluded[Column("name")])]
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictTarget: The conflict target.
/// - parameter strategy: The default strategy, `.allColumns`, updates
/// all columns in case of conflict, unless specified otherwise in the
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
/// update the columns assigned in the `assignments` parameter.
/// - parameter assignments: An optional function that returns an array of
/// ``ColumnAssignment``. In case of violation of a uniqueness
/// constraints, these assignments are performed, and remaining columns
/// are overwritten by inserted values.
/// constraint, these assignments are performed, and remaining columns
/// are overwritten by inserted values, or not, depending on the
/// chosen `strategy`. To use the value that would have been inserted
/// had the constraint not failed, use the `excluded` parameter.
/// - returns: The upserted record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
@@ -307,26 +312,36 @@ extension PersistableRecord {
public func upsertAndFetch(
_ db: Database,
onConflict conflictTarget: [String] = [],
updating strategy: UpsertUpdateStrategy = .allColumns,
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
throws -> Self
where Self: FetchableRecord
{
try upsertAndFetch(db, as: Self.self, onConflict: conflictTarget, doUpdate: assignments)
try upsertAndFetch(
db, as: Self.self, onConflict: conflictTarget,
updating: strategy, doUpdate: assignments)
}
/// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and
/// returns the upserted record.
///
/// See ``upsertAndFetch(_:onConflict:doUpdate:)`` for more information
/// about the `conflictTarget` and `assignments` parameters.
/// See ``upsertAndFetch(_:onConflict:updating:doUpdate:)`` for more
/// information about the `conflictTarget`, `strategy`, and
/// `assignments` parameters.
///
/// - parameter db: A database connection.
/// - parameter returnedType: The type of the returned record.
/// - parameter conflictTarget: The conflict target.
/// - parameter strategy: The default strategy, `.allColumns`, updates
/// all columns in case of conflict, unless specified otherwise in the
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
/// update the columns assigned in the `assignments` parameter.
/// - parameter assignments: An optional function that returns an array of
/// ``ColumnAssignment``. In case of violation of a uniqueness
/// constraints, these assignments are performed, and remaining columns
/// are overwritten by inserted values.
/// constraint, these assignments are performed, and remaining columns
/// are overwritten by inserted values, or not, depending on the
/// chosen `strategy`. To use the value that would have been inserted
/// had the constraint not failed, use the `excluded` parameter.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
@@ -336,6 +351,7 @@ extension PersistableRecord {
_ db: Database,
as returnedType: T.Type,
onConflict conflictTarget: [String] = [],
updating strategy: UpsertUpdateStrategy = .allColumns,
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
throws -> T
{
@@ -345,7 +361,7 @@ extension PersistableRecord {
try aroundSave(db) {
success = try upsertAndFetchWithCallbacks(
db, onConflict: conflictTarget,
doUpdate: assignments,
updating: strategy, doUpdate: assignments,
selection: T.databaseSelection,
decode: { try T(row: $0) })
return PersistenceSuccess(success!.inserted)
@@ -367,18 +383,17 @@ extension PersistableRecord {
func upsertWithCallbacks(_ db: Database)
throws -> InsertionSuccess
{
let (inserted, _) = try upsertAndFetchWithCallbacks(
try upsertWithCallbacks(
db, onConflict: [],
doUpdate: nil,
selection: [],
decode: { _ in /* Nothing to decode */ })
return inserted
updating: .allColumns,
doUpdate: nil)
}
@inlinable // allow specialization so that empty callbacks are removed
func upsertAndFetchWithCallbacks<T>(
_ db: Database,
onConflict conflictTarget: [String],
updating strategy: UpsertUpdateStrategy,
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])?,
selection: [any SQLSelectable],
decode: (Row) throws -> T)
@@ -390,7 +405,7 @@ extension PersistableRecord {
try aroundInsert(db) {
success = try upsertAndFetchWithoutCallbacks(
db, onConflict: conflictTarget,
doUpdate: assignments,
updating: strategy, doUpdate: assignments,
selection: selection,
decode: decode)
return success!.inserted
@@ -402,4 +417,28 @@ extension PersistableRecord {
didInsert(success.inserted)
return success
}
@inlinable // allow specialization so that empty callbacks are removed
func upsertWithCallbacks(
_ db: Database,
onConflict conflictTarget: [String],
updating strategy: UpsertUpdateStrategy,
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])?
) throws -> InsertionSuccess {
try willInsert(db)
var inserted: InsertionSuccess?
try aroundInsert(db) {
inserted = try upsertWithoutCallbacks(
db, onConflict: conflictTarget,
updating: strategy, doUpdate: assignments)
return inserted!
}
guard let inserted else {
try persistenceCallbackMisuse("aroundInsert")
}
didInsert(inserted)
return inserted
}
}
+8 -2
View File
@@ -24,8 +24,9 @@
/// - ``insertAndFetch(_:onConflict:as:)``
/// - ``insertAndFetch(_:onConflict:selection:fetch:)``
/// - ``insertAndFetch(_:onConflict:fetch:select:)``
/// - ``upsertAndFetch(_:onConflict:doUpdate:)``
/// - ``upsertAndFetch(_:as:onConflict:doUpdate:)``
/// - ``upsertAndFetch(_:onConflict:updating:doUpdate:)``
/// - ``upsertAndFetch(_:as:onConflict:updating:doUpdate:)``
/// - ``UpsertUpdateStrategy``
///
/// ### Saving a Record
///
@@ -73,6 +74,11 @@ public protocol PersistableRecord: MutablePersistableRecord {
/// - note: If you need a mutating variant of this method, adopt the
/// ``MutablePersistableRecord`` protocol instead.
///
/// - important: Due to an SQLite limitation, this callback is
/// unreliable when the record type writes into a database view
/// through an INSTEAD OF trigger. The `inserted.rowID` value is
/// not the rowid of the inserted row.
///
/// - parameter inserted: Information about the inserted row.
func didInsert(_ inserted: InsertionSuccess)
}
+5 -1
View File
@@ -134,7 +134,7 @@ import Foundation
/// - ``select(_:as:)-tjh0``
/// - ``updateAll(_:onConflict:_:)-7vv9x``
/// - ``updateAll(_:onConflict:_:)-7atfw``
public protocol TableRecord {
public protocol TableRecord: GRDBSendableMetatype {
/// A type that defines columns.
///
/// For example:
@@ -209,6 +209,10 @@ public protocol TableRecord {
/// // SELECT * FROM player
/// try Player.fetchAll(db)
/// ```
///
/// You can specify the name of a database table, or the name of a
/// database view. When you target a database view, some extra
/// configuration might be needed. Please check <doc:ViewRecords>.
static var databaseTableName: String { get }
/// The columns selected by the record.
+4 -2
View File
@@ -27,7 +27,7 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
self.attemptToFulfill = attemptToFulfill
}
func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
func receive<S>(subscriber: S) where S: Subscriber & GRDBSendableMetatype, Failure == S.Failure, Output == S.Input {
let subscription = OnDemandFutureSubscription(
attemptToFulfill: attemptToFulfill,
downstream: subscriber)
@@ -35,7 +35,9 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
}
}
private class OnDemandFutureSubscription<Downstream: Subscriber>: Subscription, @unchecked Sendable {
private class OnDemandFutureSubscription<Downstream>: Subscription, @unchecked Sendable
where Downstream: Subscriber & GRDBSendableMetatype
{
// @unchecked because `state` is protected with `lock`.
typealias Promise = @Sendable (Result<Downstream.Input, Downstream.Failure>) -> Void
Loaded 100 of 378 files, more files were not shown because too many files have changed in this diff. Show more