Compare commits

...
Author SHA1 Message Date
Gwendal Roué 4c541a99b5 Min iOS target: v18 2024-09-14 12:23:07 +02:00
Gwendal Roué 2cf6c756e1 Merge branch 'development' 2024-09-07 14:20:48 +02:00
Gwendal Roué d56223cba1 v6.29.3 2024-09-07 12:59:25 +02:00
Gwendal Roué bc4fd8ff58 Merge pull request #1613 from groue/dev/fix-1612
Avoid SQLite misuse when releasing memory on a closed database connection
2024-09-07 12:56:16 +02:00
Gwendal Roué cdb181d9ca Don't invoke sqlite3_db_release_memory on closed database connections 2024-09-04 09:21:30 +02:00
Gwendal Roué f4b4035704 Fix Swiftlint warnings 2024-08-24 14:39:44 +02:00
Gwendal Roué 57a4587b5b Merge branch 'development' 2024-08-24 14:30:20 +02:00
Gwendal Roué ae837a3a44 v6.29.2 2024-08-24 11:46:45 +02:00
Gwendal Roué c64bc11627 Remove ill-advised TODO
This would force users to force-unwrap their custom `ColumnType(rawValue: "WHATEVER")!`
2024-08-24 11:38:37 +02:00
Gwendal Roué de96d5f6f0 Merge pull request #1595 from groue/dev/string_h
Enhance imports for strcmp
2024-08-24 11:33:39 +02:00
Gwendal Roué d3d2a9c4f7 Stop testing error messages that depend on the SQLite version 2024-08-24 10:26:34 +02:00
Gwendal Roué f10c74c374 Merge pull request #1593 from mingchen/development
README.md: Fix sample code
2024-08-22 09:13:28 +02:00
Gwendal Roué fcfdab2f11 Import string_h for strcmp
Thanks to @karianneberg in https://github.com/groue/GRDB.swift/commit/344878cdb2e3af07f46954e3bc2b93541489bd82
2024-08-22 08:17:04 +02:00
Ming C. f441341543 README.md: Fix sample code 2024-08-17 11:43:05 -07:00
Gwendal Roué dd6b98ce04 Merge branch 'development' 2024-08-07 12:18:34 +02:00
Gwendal Roué 5b73581126 v6.29.1 2024-08-07 12:16:57 +02:00
Gwendal Roué 9a896650ff Merge pull request #1589 from noremac/development
Fix compilation issue with Xcode 16 beta 5 due to a missing import.
2024-08-07 12:11:38 +02:00
Cameron Pulsford 344878cdb2 Fix compilation issue with Xcode 16 beta 5 due to a missing import. 2024-08-06 19:46:09 -04:00
Gwendal Roué 20ffddd572 Update TODO.md 2024-07-31 12:51:26 +02:00
Gwendal Roué 4ddb6b89ce Merge pull request #1584 from SagarSDagdu/update-cocoapods-instructions
Update README to highlight deployment issue with CocoaPods
2024-07-30 17:34:26 +02:00
Sagar DagduandGwendal Roué 9da1a83cca Fix indentation for code blocks
Co-authored-by: Gwendal Roué <gr@pierlis.com>
2024-07-30 21:00:14 +05:30
Sagar Dagdu 8205f02672 Address code review comments 2024-07-30 20:54:24 +05:30
Sagar Dagdu 78377d5cc0 Update README to highlight deployment issue with CocoaPods 2024-07-30 20:21:26 +05:30
Gwendal Roué 04543755d8 Merge pull request #1579 from groue/dev/modernize-demo-apps
Modernise the demo apps
2024-07-21 11:25:36 +02:00
Gwendal Roué cdc0131369 Modernize demo apps:
iOS 17+
GRDBQuery 0.9.0
#Preview macro
2024-07-20 14:38:14 +02:00
Gwendal Roué 1cd6c7cbff Merge branch 'development' 2024-07-20 11:22:16 +02:00
Gwendal Roué bbbe0d899d v6.29.0 2024-07-20 11:17:13 +02:00
Gwendal Roué 9f16865ff1 Merge pull request #1575 from Jason-Abbott/development
Show trigger comments for expanded statement tracing
2024-07-17 18:21:56 +02:00
Jason Abbott 14d2b931a4 Also return untrimmed comments when tracing without visible values 2024-07-17 09:17:03 -06:00
Jason Abbott 802b4ca78a Correct suffix/prefix test 2024-07-16 16:57:57 -06:00
Jason Abbott 1c60e5ef42 Show trigger comments for expanded statement tracing 2024-07-16 16:51:50 -06:00
Gwendal Roué 9f41e56c32 Merge pull request #1574 from sroebert/feature/single-value-container-decoding
Support for single value decoding
2024-07-13 17:07:15 +02:00
Steven RoebertandGwendal Roué 0ae3f32f7f Added compiler checks for Swift 6 specific code
Co-authored-by: Gwendal Roué <gr@pierlis.com>
2024-07-13 12:53:00 +02:00
Steven Roebert c977cb8226 Implemented support for single value decoding in _RowDecoder 2024-07-13 11:48:02 +02:00
Gwendal Roué 78448cf8f4 Merge branch 'development' 2024-07-11 07:49:09 +02:00
Gwendal Roué 30de9853d6 v6.28.0 2024-07-11 07:48:54 +02:00
Gwendal Roué 7a1196263d CHANGELOG 2024-07-11 07:46:32 +02:00
Gwendal Roué 3043d7dca5 DatabaseUUIDEncodingStrategy is Sendable
Fix #1567
2024-07-11 07:46:23 +02:00
Gwendal Roué d2dd757d0c CHANGELOG 2024-07-11 07:44:30 +02:00
Gwendal Roué 764ad4bf72 Merge pull request #1570 from groue/dev/single-value-encoding
Support single-value encoding
2024-07-11 07:42:41 +02:00
Gwendal Roué e6d4223b14 EncodableRecord takes precedence over Encodable when a record is encoded with a SingleValueEncodingContainer. 2024-07-10 08:47:49 +02:00
Gwendal Roué ba3c938eb9 Fix failing test for #1565 2024-07-09 13:42:52 +02:00
Gwendal Roué 5999227c01 Failing test for #1565 2024-07-09 13:31:54 +02:00
Gwendal Roué 78545f2c8c Tests for #1541 2024-06-09 13:02:27 +02:00
Gwendal Roué 263a549c21 Test that a cancelled ValueObservation does not notify of changes that were enqueued before cancellation.
This is a test for #1550
2024-06-08 13:47:21 +02:00
Gwendal Roué 6689470457 Remove Double infinities from database dump tests
Some SQLite versions store or read +inf and -inf as 9.0e+999 and -9.0e+999, and this makes some tests fail.

Known failure: SQLCipher4, test_quote_value_formatting(), https://github.com/groue/GRDB.swift/actions/runs/9388768610/job/25854709627

I could not reproduce.
2024-06-06 07:50:02 +02:00
Gwendal Roué bbbd6bba90 Add Set methods union, formUnion, intersection and formIntersection that accept a cursor. 2024-06-05 19:38:16 +02:00
Gwendal Roué bb789e3dee QueryInterfaceRequest.deleteAndFetchIds 2024-06-05 18:42:36 +02:00
Gwendal Roué b312d4cf5a Add missing DocC links to cast(_:as:) 2024-06-05 18:36:24 +02:00
Gwendal Roué f335123c2b Update link to SQLite RETURNING caveats 2024-06-05 18:23:56 +02:00
Gwendal Roué 34d87c0e85 Merge pull request #1544 from JoeParker/fix-cte-doc-example
Fix error in CTE association documentation
2024-06-02 12:09:59 +02:00
Joe Parker 0f2e993790 Update example snippet in CommonTableExpressions.md 2024-05-10 17:19:01 +01:00
Gwendal Roué 1831017d64 TODO
Related issue: https://github.com/groue/GRDB.swift/issues/1539
2024-05-01 13:38:14 +02:00
Gwendal Roué 4b934fda75 Fix link 2024-04-21 17:47:03 +02:00
Gwendal Roué 53c40fd80f Fix Swiftlint warning 2024-04-21 17:45:58 +02:00
Gwendal Roué 639fa9168d Merge branch 'development' 2024-04-21 16:00:34 +02:00
Gwendal Roué 1c5017a108 v6.27.0 2024-04-21 15:18:13 +02:00
Gwendal Roué 9ca1f6644c CHANGELOG 2024-04-21 15:15:54 +02:00
Gwendal Roué 3f3cfa5381 Merge pull request #1534 from groue/dev/singleton-rewrite
Update the "Single-Row Tables" guide, with support for default values
2024-04-21 15:10:46 +02:00
Gwendal Roué bde61b26ab Rewrite SingleRowTables, accounting for nullable columns
This addresses https://github.com/groue/GRDB.swift/discussions/1526
2024-04-21 15:02:52 +02:00
Gwendal Roué 0a5bef4c0e SingletonUserDefaultsTest 2024-04-21 14:56:47 +02:00
Gwendal Roué 218774d39a CHANGELOG 2024-04-21 14:56:09 +02:00
Gwendal Roué a0a9cfca65 Merge pull request #1535 from groue/dev/doc-ValueObservation-scheduling
Improve the documentation about the scheduling of ValueObservation fetches
2024-04-21 14:53:09 +02:00
Gwendal Roué c8bb0a4799 Improve the documentation about the scheduling of ValueObservation fetches 2024-04-21 14:42:47 +02:00
Gwendal Roué f1ff7f2a2a Fix compiler warnings 2024-04-21 12:20:37 +02:00
Gwendal Roué 725cccccab CHANGELOG 2024-04-21 12:16:41 +02:00
Gwendal Roué 1525075cce Merge pull request #1533 from groue/dev/fix-1531
Fix a bug in Decodable support
2024-04-21 12:14:35 +02:00
Gwendal Roué 7110a1fab3 Fix failing tests for decodeNil()
Fix https://github.com/groue/GRDB.swift/issues/1531
2024-04-21 12:13:24 +02:00
Gwendal Roué de382d30b8 Test decodeNil
Two failing tests related to https://github.com/groue/GRDB.swift/issues/1531
2024-04-21 12:13:24 +02:00
Gwendal Roué 3521030e13 Test _RowDecoder.KeyedContainer.allKeys, contains(_:), and support some nested keyed containers 2024-04-21 12:13:24 +02:00
Gwendal Roué eeacf93772 Don't mention async sequences in the GRDBAsyncDemo introduction
Been there, done that: when one feeds a SwiftUI view from an async sequence, the view MUST display an initial empty state, until the Swift Concurrency runtime provides the initial value of the sequence. That's why the demo app uses a Combine publisher for feeding views with database value. This commit removes a misleading reference to async sequences.

Fix #1532
2024-04-20 12:40:38 +02:00
Gwendal Roué 000aaa8698 Add test that specifically addresses #1517 2024-03-29 13:21:12 +01:00
Gwendal Roué 77b85bed25 Merge branch 'development' 2024-03-23 14:06:22 +01:00
Gwendal Roué bb8323b91d v6.26.0 2024-03-23 14:06:05 +01:00
Gwendal Roué d804b5ed9c Bump performance dependencies 2024-03-23 14:06:05 +01:00
Gwendal Roué 2af60cb324 CHANGELOG 2024-03-23 11:46:44 +01:00
Gwendal Roué 0434567f30 Merge pull request #1515 from groue/dev/cast
Support for the CAST SQLite function
2024-03-23 11:42:56 +01:00
Gwendal Roué 155a16bef8 CHANGELOG 2024-03-23 10:52:28 +01:00
Gwendal Roué 2ad1f37d2b Documentation for cast function 2024-03-23 10:48:20 +01:00
Gwendal Roué 32642d566b Test cast function 2024-03-23 10:47:57 +01:00
Gwendal Roué 1f4d5ac61a Fix test ambiguity 2024-03-23 10:47:49 +01:00
Gwendal Roué 87fdd9a66f cast function 2024-03-23 10:47:19 +01:00
Gwendal Roué 79d82337b2 CAST expression 2024-03-23 10:47:13 +01:00
Gwendal Roué fab4638fc9 Database.StorageClass 2024-03-23 10:46:52 +01:00
Gwendal Roué a49fd85627 Regression tests for #1512 2024-03-21 14:25:12 +01:00
Gwendal Roué ac8c4aea63 Report correct error when decoding NULL into Date or Data
Fixes #1512
2024-03-21 14:25:12 +01:00
Gwendal Roué 5413dcfeeb Remove jsonErrorPosition unless GRDBCUSTOMSQLITE || GRDBCIPHER
For some reason, if #available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) has stopped being able to skip the test (WTF?)
2024-03-19 12:15:47 +01:00
Gwendal Roué 4e0ab25106 Fix flaky tests due to Recorder incorrect critical section 2024-03-17 22:40:38 +01:00
Gwendal Roué c52db6095a Stop testing test_CocoaPodsLint
Because it does no longer work due to https://github.com/CocoaPods/CocoaPods/issues/11839
2024-03-17 22:15:08 +01:00
Gwendal Roué 1464940eeb Merge pull request #1511 from groue/dev/schema-dump
Database schema dump
2024-03-17 22:11:55 +01:00
Gwendal Roué f274e464cd CHANGELOG 2024-03-17 20:45:48 +01:00
Gwendal Roué c3e7736534 Dump schema 2024-03-17 20:45:31 +01:00
Gwendal Roué 9b95dd5be1 Merge pull request #1510 from groue/dev/trivial-sendable-conformances
Add Sendable conformances and unavailabilities
2024-03-17 20:45:01 +01:00
Gwendal Roué 77da5f4a30 CHANGELOG 2024-03-17 19:18:30 +01:00
Gwendal Roué 43ced9b2f0 Trivial Sendable conformances
Either added, either made explicitly unavailable.
2024-03-17 18:25:04 +01:00
Gwendal Roué 4ffad63f1b Fix Swift 5.10 warning on WALSnapshot 2024-03-17 17:55:25 +01:00
Gwendal Roué 62e7ea1ef2 CHANGELOG 2024-03-17 17:55:15 +01:00
Gwendal Roué 91492b849d Merge pull request #1508 from groue/dev/issue-1500
Fix ValueObservation mishandling of database schema modification
2024-03-17 17:53:28 +01:00
Gwendal Roué d54d0abc07 Fix WALSnapshotTransaction so that it clears its schema cache if needed 2024-03-17 16:13:35 +01:00
Gwendal Roué 3b096b38e7 Failing test for #1500 2024-03-17 16:13:35 +01:00
Gwendal Roué 9593297cf0 CHANGELOG 2024-03-17 14:54:07 +01:00
Gwendal Roué 8ac5591189 Merge pull request #1503 from simba909/master
Conform Database.ColumnType to Sendable
2024-03-17 14:51:44 +01:00
Simon Jarbrant 4232fa687d Conform Database.ColumnType to Sendable 2024-03-08 14:28:36 +01:00
Gwendal Roué bd9aea303d Merge branch 'development' 2024-02-25 16:32:30 +01:00
Gwendal Roué 5abc737bf0 v6.25.0 2024-02-25 16:31:11 +01:00
Gwendal Roué d4d14e3dd7 CHANGELOG 2024-02-25 16:28:06 +01:00
Gwendal Roué 660d2b1fe7 Merge pull request #1496 from danielepantaleone/development
Added privacy manifest file
2024-02-25 16:23:15 +01:00
Gwendal Roué bb44f48414 Add the PrivacyInfo.xcprivacy file to the GRDB target 2024-02-25 15:08:53 +01:00
Gwendal Roué bbe7d2f1ca Remove PrivacyInfo.xcprivacy from podspec
This technique has CocoaPods overwrite the app and other pods's manifest file and is not correct.

Currently, there's no CocoaPods support for privacy manifest unless I'm mistaken: https://github.com/CocoaPods/CocoaPods/issues/11990

And we can't publish new GRDB version on CocoaPods anyway: https://github.com/CocoaPods/CocoaPods/issues/11839
2024-02-25 15:07:35 +01:00
Daniele Pantaleone 45e0de9960 Added privacy manifest to GRDBCustom project 2024-02-18 17:03:43 +01:00
Daniele Pantaleone 1920482158 Added privacy manifest file 2024-02-15 16:57:46 +01:00
Gwendal Roué 0437c0fed6 Merge pull request #1490 from danielinoa/patch-2
Update LICENSE to 2024
2024-02-07 08:53:45 +01:00
Daniel Inoa d08d2f52fb Update LICENSE 2024-02-06 18:30:52 -08:00
Gwendal Roué d1ff0912f1 Fix release date 2024-01-21 12:27:30 +01:00
Gwendal Roué e069e2732e Merge branch 'development' 2024-01-21 11:14:33 +01:00
Gwendal Roué c791e376e8 v6.24.2 2024-01-21 11:14:20 +01:00
Gwendal Roué acf1eb935b Merge pull request #1485 from groue/dev/immediate_transactions
Recommend IMMEDIATE transactions when a database is shared between multiple processes
2024-01-17 21:10:45 +01:00
Gwendal Roué 87c4b1cfa8 CHANGELOG 2024-01-17 20:06:38 +01:00
Gwendal Roué d0fc34b199 Recommend IMMEDIATE transactions in the Sharing a Database guide
Fix #1483
2024-01-17 20:04:39 +01:00
Gwendal Roué 9cee1e218d Tests for SQLITE_BUSY prevention with IMMEDIATE transactions
Those tests support the recommendation of IMMEDIATE transactions for shared databasesS.

See #1483
2024-01-17 19:39:40 +01:00
Gwendal Roué f5d55cb1a1 TODO 2024-01-17 10:51:42 +01:00
Gwendal Roué 345a3dae28 CHANGELOG 2024-01-14 17:31:17 +01:00
Gwendal Roué 1239178bee Improve diagnostic when an association to/from view are lacking an explicit ForeignKey
Related discussion: https://github.com/groue/GRDB.swift/discussions/1481
2024-01-14 17:31:17 +01:00
Gwendal Roué e5a7c73dc9 Tests for associations to or from views 2024-01-14 14:33:17 +01:00
Gwendal Roué 11e914db12 Fix code signing issues with GRDBDemoiOS 2024-01-13 13:09:53 +01:00
Gwendal Roué 181ccd8d7d Merge branch 'development' 2024-01-06 19:56:07 +01:00
Gwendal Roué 2800e9a81e v6.24.1 2024-01-06 19:55:52 +01:00
Gwendal Roué 18d2d512f0 Merge pull request #1477 from groue/dev/dump-virtual-tables
Remove shadow tables from database dump
2024-01-06 19:52:33 +01:00
Gwendal Roué c06552fbd4 Document that shadow tables are not recorded by dumpContent() 2024-01-06 18:36:58 +01:00
Gwendal Roué a00a3f7c80 Fix failing test that dumpContent ignores shadow tables 2024-01-06 18:14:37 +01:00
Gwendal Roué b9ac9b1ca8 Failing test that dumpContent ignores shadow tables 2024-01-06 18:12:45 +01:00
Gwendal Roué 07f1ddac04 Test that dumpContent ignores GRDB internal tables 2024-01-06 18:12:21 +01:00
Gwendal Roué 12829e5bfb Merge branch 'development' 2024-01-06 14:53:16 +01:00
Gwendal Roué 09fa46a0d9 v6.24.0 2024-01-06 13:27:00 +01:00
Gwendal Roué e359529503 When releasing, run the full test suite from a pristine repository 2024-01-06 13:27:00 +01:00
Gwendal Roué ac8d1b77b9 Merge pull request #1466 from barnettben/1463-schema-names
Add schema name option to table introspection methods
2024-01-06 13:18:50 +01:00
Gwendal Roué 002c5ec2f1 Revert "Report test results from Github actions"
This reverts commit aadb887b34.
2024-01-06 12:27:26 +01:00
Gwendal Roué b42f618a01 Disable tests for attached schemas when databases are encrypted 2024-01-06 12:08:54 +01:00
Ben Barnett 27a4215424 Add schemaName parameter to foreign key checking functions 2023-12-08 18:22:49 +00:00
Ben Barnett 65167ec7da Add schemaName parameter to table/view/triggerExists() 2023-12-08 18:22:49 +00:00
Ben Barnett 73489fc0e7 Add schemaName parameter to indexes(on:) 2023-12-08 18:22:49 +00:00
Ben Barnett 1aca8efa65 Add schemaName parameter to foreignKeys(on:) 2023-12-08 18:22:49 +00:00
Ben Barnett a22bf83ae8 Split duplicate nested conditions into separate function 2023-12-07 18:32:34 +00:00
Ben Barnett f00a974211 Add schemaName parameter to columns(in:) 2023-12-06 20:49:48 +00:00
Ben Barnett ac475cc158 Add schemaName parameter to primaryKey(_:) 2023-12-06 20:32:17 +00:00
Gwendal Roué eacbdf23af Merge branch 'development' 2023-12-01 08:21:27 +01:00
Gwendal Roué e31a80e3c4 v6.23.0 2023-12-01 08:06:55 +01:00
Gwendal Roué e3cf966c81 Documentation organization 2023-12-01 08:02:32 +01:00
Gwendal Roué eeb71039d4 Merge pull request #1462 from groue/dev/read-only
Temporary read-only access
2023-11-30 13:48:52 +01:00
Gwendal Roué c5203f078d Make Database.readOnly public 2023-11-30 07:56:21 +01:00
Gwendal Roué e29c52d7e5 Update obsolete documentation of stopObservingDatabaseChangesUntilNextTransaction 2023-11-27 10:00:41 +01:00
Gwendal Roué 06ac26a213 Merge branch 'development' 2023-11-26 12:02:16 +01:00
Gwendal Roué fae845a986 v6.22.0 2023-11-26 10:48:42 +01:00
Gwendal Roué b671bb0faa CHANGELOG 2023-11-26 10:37:27 +01:00
Gwendal Roué 93462cfd2c Documentation 2023-11-26 10:33:00 +01:00
Gwendal Roué 54357e4fec Merge pull request #1460 from groue/dev/notify-changes
Explicit change notifications
2023-11-26 08:34:23 +01:00
Gwendal Roué d8760253ff Add missing DocC reference 2023-11-25 17:10:40 +01:00
Gwendal Roué dc281cee25 Cleanup tests for unspecified changes to a column 2023-11-25 17:01:11 +01:00
Gwendal Roué a8ed98e414 Mention undetected changes in the Database Sharing Guide 2023-11-25 16:50:01 +01:00
Gwendal Roué f1a8c5ac92 Wording 2023-11-25 16:49:37 +01:00
Gwendal Roué 079c0c7f26 The unit of change notification is the event kind, not the region 2023-11-25 16:44:18 +01:00
Gwendal Roué bced461c4f Fix failing test for DatabaseRegionObservation and Database.notifyChanges(in:) 2023-11-25 15:32:35 +01:00
Gwendal Roué 9d6e127822 Failing test for DatabaseRegionObservation and Database.notifyChanges(in:) 2023-11-25 15:32:35 +01:00
Gwendal Roué dff7971cd7 Fix failing test for ValueObservation and Database.notifyChanges(in:) 2023-11-25 15:32:35 +01:00
Gwendal Roué 3df718c1a6 Failing test for ValueObservation and Database.notifyChanges(in:) 2023-11-25 15:32:35 +01:00
Gwendal Roué 3e52e265ce Fix failing test for stopObservingDatabaseChangesUntilNextTransaction() from databaseDidChange() 2023-11-25 15:32:35 +01:00
Gwendal Roué abf48eb86f Failing test for stopObservingDatabaseChangesUntilNextTransaction() from databaseDidChange() 2023-11-25 15:32:35 +01:00
Gwendal Roué 56ad833ab7 New Dealing with Undetected Changes documentation chapter 2023-11-25 15:32:35 +01:00
Gwendal Roué 8afd986790 Fix failing tests for Database.notifyChanges(in:) and master tables 2023-11-25 15:32:35 +01:00
Gwendal Roué 918afbd33e Fix failing tests for Database.notifyChanges(in:) and regular tables 2023-11-25 14:39:13 +01:00
Gwendal Roué b5cb8fadf0 Failing tests for Database.notifyChanges(in:) 2023-11-25 14:39:13 +01:00
Gwendal Roué 1a16bdeac8 TransactionObserver.databaseDidChange() 2023-11-25 13:30:23 +01:00
Gwendal Roué 5e749eb50b Document that changes performed by SQLite statements that are not compiled and executed by GRDB are not detected. 2023-11-24 14:10:57 +01:00
Gwendal Roué 836e7733da Prepare TransactionObserverTests for unspecified change notifications 2023-11-24 13:40:02 +01:00
Gwendal Roué 8b19c3424c Test async read after async write 2023-11-11 13:38:03 +01:00
Gwendal Roué 7eaf67fb6a CHANGELOG 2023-11-02 15:04:45 +01:00
Gwendal Roué 753d7db65f Merge pull request #1452 from groue/dev/SQLite-3.44.0
SQLite 3.44.0, FILTER and ORDER BY clauses in aggregate functions
2023-11-02 15:03:30 +01:00
Gwendal Roué f0fe5ff017 TODO GRDB7 2023-11-02 14:08:15 +01:00
Gwendal Roué 225d7a8c2d Fix test for SQLCipher 2023-11-02 14:03:52 +01:00
Gwendal Roué 46ad19d2e3 Documentation 2023-11-02 14:03:52 +01:00
Gwendal Roué 2603b6ea03 Support for ORDER BY and FILTER in aggregate functions 2023-11-02 14:03:52 +01:00
Gwendal Roué f7156b9490 Custom SQLite 3.44.0 2023-11-02 14:03:52 +01:00
Gwendal Roué f1f8e8438a Merge branch 'development' 2023-10-29 10:00:25 +01:00
Gwendal Roué 6bd1e6b8fb v6.21.0 2023-10-29 08:46:10 +01:00
Gwendal Roué ae21996947 CHANGELOG 2023-10-29 08:43:30 +01:00
Gwendal Roué 8479c4c874 Merge pull request #1449 from groue/dev/temp-copies
Backport temporary copies from GRDBSnapshotTesting
2023-10-29 08:42:20 +01:00
Gwendal Roué 4c8fc93fec Fix tests for encrypted databases 2023-10-29 07:34:23 +01:00
Gwendal Roué 38bb8d3505 Backport temporary copies from GRDBSnapshotTesting 2023-10-28 18:38:15 +02:00
Gwendal Roué 850542dd25 CHANGELOG 2023-10-28 18:37:38 +02:00
Gwendal Roué aaad020b0b Merge pull request #1448 from groue/dev/dump-views
Add support for stable ordering and dump of views.
2023-10-28 18:36:15 +02:00
Gwendal Roué ba320a08e3 Make dumpTables able to print views 2023-10-28 15:46:31 +02:00
Gwendal Roué 42fd32731a Make withStableOrder able to deal with views 2023-10-28 15:46:10 +02:00
Gwendal Roué 8fa434272e Make all read closures explicit in the documentation
The short form dbQueue.read(fetch) can confuse the reader.
2023-10-22 07:59:08 +02:00
166 changed files with 6667 additions and 1038 deletions

No files matched your search

+1 -26
View File
@@ -28,7 +28,6 @@ concurrency:
cancel-in-progress: true
permissions:
contents: read
checks: write
jobs:
Framework:
@@ -80,13 +79,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project GRDB.xcodeproj -scheme GRDB -destination "${{ matrix.destination }}" -resultBundlePath TestResults.xcresult 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
- uses: kishikawakatsumi/xcresulttool@v1
with:
path: TestResults.xcresult
show-passed-tests: false
show-code-coverage: false
if: success() || failure()
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:
name: SPM
runs-on: ${{ matrix.runsOn }}
@@ -133,12 +126,6 @@ jobs:
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher3Encrypted
- uses: kishikawakatsumi/xcresulttool@v1
with:
path: Tests/CocoaPods/SQLCipher3/TestResults_encrypted.xcresult
show-passed-tests: false
show-code-coverage: false
if: success() || failure()
SQLCipher4:
name: SQLCipher4
runs-on: ${{ matrix.runsOn }}
@@ -159,12 +146,6 @@ jobs:
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher4Encrypted
- uses: kishikawakatsumi/xcresulttool@v1
with:
path: Tests/CocoaPods/SQLCipher4/TestResults_encrypted.xcresult
show-passed-tests: false
show-code-coverage: false
if: success() || failure()
CustomSQLite:
name: CustomSQLite
runs-on: ${{ matrix.runsOn }}
@@ -185,12 +166,6 @@ jobs:
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: make test_framework_GRDBCustomSQLiteOSX
- uses: kishikawakatsumi/xcresulttool@v1
with:
path: TestResults.xcresult
show-passed-tests: false
show-code-coverage: false
if: success() || failure()
XCFramework:
name: XCFramework
runs-on: ${{ matrix.runsOn }}
-3
View File
@@ -115,6 +115,3 @@ Tests/SPM/Packages
# Test products
Tests/products
# CI
*.xcresult
+112
View File
@@ -7,6 +7,15 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 6.x Releases
- `6.29.x` Releases - [6.29.0](#6290) - [6.29.1](#6291) - [6.29.2](#6292) - [6.29.3](#6293)
- `6.28.x` Releases - [6.28.0](#6280)
- `6.27.x` Releases - [6.27.0](#6270)
- `6.26.x` Releases - [6.26.0](#6260)
- `6.25.x` Releases - [6.25.0](#6250)
- `6.24.x` Releases - [6.24.0](#6240) - [6.24.1](#6241) - [6.24.2](#6242)
- `6.23.x` Releases - [6.23.0](#6230)
- `6.22.x` Releases - [6.22.0](#6220)
- `6.21.x` Releases - [6.21.0](#6210)
- `6.20.x` Releases - [6.20.0](#6200) - [6.20.1](#6201) - [6.20.2](#6202)
- `6.19.x` Releases - [6.19.0](#6190)
- `6.18.x` Releases - [6.18.0](#6180)
@@ -118,6 +127,109 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 6.29.3
Released September 7, 2024
- **Fixed**: [#1613](https://github.com/groue/GRDB.swift/pull/1613) by [@groue](https://github.com/groue): Avoid SQLite misuse when releasing memory on a closed database connection
## 6.29.2
Released August 24, 2024
- **New**: [#1593](https://github.com/groue/GRDB.swift/pull/1593) by [@mingchen](https://github.com/mingchen): Fix sample code in README
## 6.29.1
Released August 7, 2024
- **New**: [#1579](https://github.com/groue/GRDB.swift/pull/1579) by [@groue](https://github.com/groue): Modernize the demo apps
- **New**: [#1584](https://github.com/groue/GRDB.swift/pull/1584) by [@SagarSDagdu](https://github.com/SagarSDagdu): Update README to highlight deployment issue with CocoaPods
- **New**: [#1589](https://github.com/groue/GRDB.swift/pull/1589) by [@groue](https://github.com/groue): Fix compilation issue with Xcode 16 beta 5 due to a missing import
## 6.29.0
Released July 20, 2024
- **New**: [#1574](https://github.com/groue/GRDB.swift/pull/1574) by [@sroebert](https://github.com/sroebert): Support for single value decoding (the complement of [#1570](https://github.com/groue/GRDB.swift/pull/1570) shipped in 6.28.0)
- **New**: [#1575](https://github.com/groue/GRDB.swift/pull/1575) by [@Jason-Abbott](https://github.com/Jason-Abbott): Show comments when tracing expanded statements
## 6.28.0
Released July 11, 2024
- **New**: [#1570](https://github.com/groue/GRDB.swift/pull/1570) by [@groue](https://github.com/groue): Support single-value encoding
- **New**: Added `QueryInterfaceRequest.deleteAndFetchIds(_:)` which returns the set of deleted ids.
- **New**: Added `Set` methods `union`, `formUnion`, `intersection` and `formIntersection` that accept a cursor.
- **New**: `DatabaseUUIDEncodingStrategy` is Sendable.
## 6.27.0
Released April 21, 2024
- **Fixed**: [#1533](https://github.com/groue/GRDB.swift/pull/1533) by [@groue](https://github.com/groue): Fix a bug in Decodable support
- **Documentation Update**: [#1534](https://github.com/groue/GRDB.swift/pull/1534) The [Single-Row Tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables) guide was updated with guidance about default configuration values.
- **Documentation Update**: [#1535](https://github.com/groue/GRDB.swift/pull/1535) The [ValueObservation Scheduling](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation#ValueObservation-Scheduling) documentation chapter explains the default behavior of `ValueObservation` fetches, and explains how to make sure they are never performed on the main thread.
## 6.26.0
Released March 23, 2024
- **New**: [#1503](https://github.com/groue/GRDB.swift/pull/1503) by [@simba909](https://github.com/simba909): Conform Database.ColumnType to Sendable
- **New**: [#1510](https://github.com/groue/GRDB.swift/pull/1510) by [@groue](https://github.com/groue): Add Sendable conformances and unavailabilities
- **New**: [#1511](https://github.com/groue/GRDB.swift/pull/1511) by [@groue](https://github.com/groue): Database schema dump
- **New**: [#1515](https://github.com/groue/GRDB.swift/pull/1515) by [@groue](https://github.com/groue): Support for the CAST SQLite function
- **Fixed**: [#1508](https://github.com/groue/GRDB.swift/pull/1508) by [@groue](https://github.com/groue): Fix ValueObservation mishandling of database schema modification
- **Fixed**: [#1512](https://github.com/groue/GRDB.swift/issues/1512): Decoding errors are now correctly reported when decoding NULL into a non-optional property of type `Data` or `Date`.
## 6.25.0
Released February 25, 2024
- **New**: [#1496](https://github.com/groue/GRDB.swift/pull/1496) by [@danielepantaleone](https://github.com/danielepantaleone): Add privacy manifest file.
A `PrivacyInfo.xcprivacy` resource was added to the GRDB SPM package and Xcode projects. It declares that GRDB does not collect anything.
## 6.24.2
Released January 21, 2024
- **Documentation Update**: [#1485](https://github.com/groue/GRDB.swift/pull/1485) The [Sharing a Database](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing) guide was updated with a new recommendation for databases shared between multiple processes. Writers should always perform IMMEDIATE transactions in order to avoid the `SQLITE_BUSY` error that can occur when transactions overlap. The new recommendation fits in a single line of code: `configuration.defaultTransactionKind = .immediate`.
- **New**: Associations that involve views instead of tables were already supported, with an explicit `ForeignKey` in their definition. When the foreign key is missing, a clear diagnostic message is now emitted, instead of an unhelpful "no such table" runtime error.
## 6.24.1
Released January 6, 2024
- **New**: [#1477](https://github.com/groue/GRDB.swift/pull/1477): Remove shadow tables from database dump
## 6.24.0
Released January 6, 2024
- **New**: [#1466](https://github.com/groue/GRDB.swift/pull/1466) by [@barnettben](https://github.com/barnettben): Add schema name option to database introspection methods
## 6.23.0
Released December 1, 2023
- **New**: [#1462](https://github.com/groue/GRDB.swift/pull/1462) Temporary read-only access
## 6.22.0
Released November 26, 2023
- **New**: [#1452](https://github.com/groue/GRDB.swift/pull/1452) by [@groue](https://github.com/groue): SQLite 3.44.0, FILTER and ORDER BY clauses in aggregate functions
- **New**: [#1460](https://github.com/groue/GRDB.swift/pull/1460) by [@groue](https://github.com/groue): Explicit change notifications help applications deal with undetected database changes.
- **Documentation Update**: The documentations of [`ValueObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation), [`DatabaseRegionObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation), and [`TransactionObserver`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver) have a new "Dealing with Undetected Changes" that documents possible strategies for notifying applications of undetected database changes.
## 6.21.0
Released October 29, 2023
- **New**: [#1448](https://github.com/groue/GRDB.swift/pull/1448) by [@groue](https://github.com/groue): Add support for stable ordering and dump of views
- **New**: [#1449](https://github.com/groue/GRDB.swift/pull/1449) by [@groue](https://github.com/groue): Backport temporary copies from GRDBSnapshotTesting
## 6.20.2
Released October 15, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.20.1...v6.20.2)
+1 -1
View File
@@ -2661,7 +2661,7 @@ Aggregates can be modified and combined with Swift operators:
let request = Team.annotated(with: Team.players.min(Column("score")) ?? 0)
```
- SQL functions `ABS` and `LENGTH` are available as the `abs` and `length` Swift functions:
- SQL functions `ABS`, `CAST`, and `LENGTH` are available as the `abs`, `cast`, and `length` Swift functions:
<details>
<summary>SQL</summary>
+4 -2
View File
@@ -251,7 +251,7 @@ let rightCTE = ...
let association = LeftRecord.association(
to: rightCTE,
on: { left, right in
left[Column("x")] = right[Column("y")]
left[Column("x")] == right[Column("y")]
})
```
@@ -362,7 +362,9 @@ And we can fetch the data that feeds our application screen:
```swift
let chatInfos: [ChatInfos] = try dbQueue.read(request.fetchAll)
let chatInfos: [ChatInfos] = try dbQueue.read { db in
try request.fetchAll(db)
}
```
> :bulb: **Tip**: the joining methods are generally type-safe: they won't allow you to join apples to oranges. This works when associations have a *precise* type. In this context, anonymous `CommonTableExpression` CTEs can work against type safety. When you want to define associations between several CTEs, and make sure the compiler will notice wrong uses of those associations, tag your common table expressions with an explicit type: `CommonTableExpression<SomeType>`.
+1 -1
View File
@@ -3,7 +3,7 @@ Custom SQLite Builds
By default, GRDB uses the version of SQLite that ships with the target operating system.
**You can build GRDB with a custom build of [SQLite 3.42.0](https://www.sqlite.org/changes.html).**
**You can build GRDB with a custom build of [SQLite 3.44.0](https://www.sqlite.org/changes.html).**
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver).
@@ -354,6 +354,7 @@
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = GRDBAsyncDemoTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -373,6 +374,7 @@
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = GRDBAsyncDemoTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -512,7 +514,7 @@
DEVELOPMENT_TEAM = "";
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = GRDBAsyncDemo/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -534,7 +536,7 @@
DEVELOPMENT_TEAM = "";
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = GRDBAsyncDemo/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -5,8 +5,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/groue/GRDBQuery",
"state" : {
"revision" : "aefc0d7e7a64e841da33e1c8be7429da1bd9b5d6",
"version" : "0.6.0"
"revision" : "a6c46dd38ecf11a5c37732870dc03a384d582fba",
"version" : "0.9.0"
}
}
],
@@ -5,17 +5,12 @@ import SwiftUI
struct GRDBAsyncDemoApp: App {
var body: some Scene {
WindowGroup {
AppView().environment(\.appDatabase, .shared)
AppView().appDatabase(.shared)
}
}
}
// MARK: - Give SwiftUI access to the database
//
// Define a new environment key that grants access to an AppDatabase.
//
// The technique is documented at
// <https://developer.apple.com/documentation/swiftui/environmentkey>.
private struct AppDatabaseKey: EnvironmentKey {
static var defaultValue: AppDatabase { .empty() }
@@ -28,13 +23,10 @@ extension EnvironmentValues {
}
}
// In this demo app, views observe the database with the @Query property
// wrapper, defined in the GRDBQuery package. Its documentation recommends to
// define a dedicated initializer for `appDatabase` access, so we comply:
extension Query where Request.DatabaseContext == AppDatabase {
/// Convenience initializer for requests that feed from `AppDatabase`.
init(_ request: Request) {
self.init(request, in: \.appDatabase)
extension View {
func appDatabase(_ appDatabase: AppDatabase) -> some View {
self
.environment(\.appDatabase, appDatabase)
.databaseContext(.readOnly { appDatabase.reader })
}
}
@@ -1,4 +1,3 @@
import Combine
import GRDB
import GRDBQuery
@@ -14,37 +13,18 @@ import GRDBQuery
/// List(players) { player in ... )
/// }
/// }
struct PlayerRequest: Queryable {
struct PlayerRequest: ValueObservationQueryable {
enum Ordering {
case byScore
case byName
}
static var defaultValue: [Player] { [] }
/// The ordering used by the player request.
var ordering: Ordering
// MARK: - Queryable Implementation
static var defaultValue: [Player] { [] }
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> {
// Build the publisher from the general-purpose read-only access
// granted by `appDatabase.reader`.
// Some apps will prefer to call a dedicated method of `appDatabase`.
ValueObservation
.tracking(fetchValue(_:))
.publisher(
in: appDatabase.reader,
// The `.immediate` scheduling feeds the view right on
// subscription, and avoids an undesired animation when the
// application starts.
scheduling: .immediate)
.eraseToAnyPublisher()
}
// This method is not required by Queryable, but it makes it easier
// to test PlayerRequest.
func fetchValue(_ db: Database) throws -> [Player] {
func fetch(_ db: Database) throws -> [Player] {
switch ordering {
case .byScore:
return try Player.all().orderedByScore().fetchAll(db)
@@ -43,7 +43,7 @@ struct AppView: View {
stopEditing()
}))
.toolbar { toolbarContent }
.onChange(of: players) { players in
.onChange(of: players) {
if players.isEmpty {
stopEditing()
}
@@ -141,14 +141,14 @@ private struct ToggleOrderingButton: View {
}
}
struct AppView_Previews: PreviewProvider {
static var previews: some View {
Group {
// Preview the default, empty database
AppView()
// Preview a database of random players
AppView().environment(\.appDatabase, .random())
}
}
// MARK: - Previews
#Preview("Empty") {
// Preview the default, empty database
AppView()
}
#Preview("Populated") {
// Preview a database of random players
AppView().appDatabase(.random())
}
@@ -43,8 +43,8 @@ struct PlayerCreationView: View {
}
}
struct PlayerCreationSheet_Previews: PreviewProvider {
static var previews: some View {
PlayerCreationView()
}
// MARK: - Previews
#Preview {
PlayerCreationView()
}
@@ -15,7 +15,7 @@ struct PlayerEditionView: View {
var body: some View {
PlayerFormView(form: $form)
.onChange(of: isPresented) { isPresented in
.onChange(of: isPresented) {
// Save when back button is pressed
if !isPresented {
Task {
@@ -30,11 +30,11 @@ struct PlayerEditionView: View {
}
}
struct PlayerEditionView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
PlayerEditionView(player: Player.makeRandom())
.navigationBarTitle("Player Edition")
}
// MARK: - Previews
#Preview {
NavigationView {
PlayerEditionView(player: Player.makeRandom())
.navigationBarTitle("Player Edition")
}
}
@@ -33,15 +33,16 @@ extension PlayerForm {
}
}
struct PlayerFormView_Previews: PreviewProvider {
static var previews: some View {
Group {
PlayerFormView(form: .constant(PlayerForm(
name: "",
score: "")))
PlayerFormView(form: .constant(PlayerForm(
name: Player.randomName(),
score: "\(Player.randomScore())")))
}
}
// MARK: - Previews
#Preview("Empty") {
PlayerFormView(form: .constant(PlayerForm(
name: "",
score: "")))
}
#Preview("Prefilled") {
PlayerFormView(form: .constant(PlayerForm(
name: Player.randomName(),
score: "\(Player.randomScore())")))
}
@@ -46,14 +46,14 @@ private struct PlayerRow: View {
}
}
struct PlayerList_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
PlayerList(players: [
Player(id: 1, name: "Arthur", score: 100),
Player(id: 2, name: "Barbara", score: 1000),
])
.navigationTitle("Preview")
}
// MARK: - Previews
#Preview {
NavigationView {
PlayerList(players: [
Player(id: 1, name: "Arthur", score: 100),
Player(id: 2, name: "Barbara", score: 1000),
])
.navigationTitle("Preview")
}
}
@@ -16,7 +16,7 @@ class PlayerRequestTests: XCTestCase {
// When we fetch players ordered by name
let playerRequest = PlayerRequest(ordering: .byName)
let players = try dbQueue.read(playerRequest.fetchValue)
let players = try dbQueue.read(playerRequest.fetch)
// Then the players are the two players ordered by name
XCTAssertEqual(players, [player1, player2])
@@ -35,7 +35,7 @@ class PlayerRequestTests: XCTestCase {
// When we fetch players ordered by score
let playerRequest = PlayerRequest(ordering: .byScore)
let players = try dbQueue.read(playerRequest.fetchValue)
let players = try dbQueue.read(playerRequest.fetch)
// Then the players are the two players ordered by score descending
XCTAssertEqual(players, [player2, player1])
@@ -13,8 +13,9 @@ The topics covered in this demo are:
- How to setup a database in an iOS app.
- How to define a simple [Codable Record](../../../README.md#codable-records).
- How to track database changes and animate a SwiftUI List with an async sequence built from [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation).
- How to track database changes and animate a SwiftUI List with [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) Combine publishers.
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
- How to perform `async` database accesses.
- How to feed SwiftUI previews with a transient database.
**Files of interest:**
@@ -354,6 +354,7 @@
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = GRDBCombineDemoTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -373,6 +374,7 @@
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
INFOPLIST_FILE = GRDBCombineDemoTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -512,6 +514,7 @@
DEVELOPMENT_TEAM = "";
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -533,6 +536,7 @@
DEVELOPMENT_TEAM = "";
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -5,8 +5,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/groue/GRDBQuery",
"state" : {
"revision" : "aefc0d7e7a64e841da33e1c8be7429da1bd9b5d6",
"version" : "0.6.0"
"revision" : "a6c46dd38ecf11a5c37732870dc03a384d582fba",
"version" : "0.9.0"
}
}
],
@@ -5,17 +5,12 @@ import SwiftUI
struct GRDBCombineDemoApp: App {
var body: some Scene {
WindowGroup {
AppView().environment(\.appDatabase, .shared)
AppView().appDatabase(.shared)
}
}
}
// MARK: - Give SwiftUI access to the database
//
// Define a new environment key that grants access to an AppDatabase.
//
// The technique is documented at
// <https://developer.apple.com/documentation/swiftui/environmentkey>.
private struct AppDatabaseKey: EnvironmentKey {
static var defaultValue: AppDatabase { .empty() }
@@ -28,13 +23,10 @@ extension EnvironmentValues {
}
}
// In this demo app, views observe the database with the @Query property
// wrapper, defined in the GRDBQuery package. Its documentation recommends to
// define a dedicated initializer for `appDatabase` access, so we comply:
extension Query where Request.DatabaseContext == AppDatabase {
/// Convenience initializer for requests that feed from `AppDatabase`.
init(_ request: Request) {
self.init(request, in: \.appDatabase)
extension View {
func appDatabase(_ appDatabase: AppDatabase) -> some View {
self
.environment(\.appDatabase, appDatabase)
.databaseContext(.readOnly { appDatabase.reader })
}
}
@@ -1,4 +1,3 @@
import Combine
import GRDB
import GRDBQuery
@@ -14,37 +13,18 @@ import GRDBQuery
/// List(players) { player in ... )
/// }
/// }
struct PlayerRequest: Queryable {
struct PlayerRequest: ValueObservationQueryable {
enum Ordering {
case byScore
case byName
}
static var defaultValue: [Player] { [] }
/// The ordering used by the player request.
var ordering: Ordering
// MARK: - Queryable Implementation
static var defaultValue: [Player] { [] }
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> {
// Build the publisher from the general-purpose read-only access
// granted by `appDatabase.reader`.
// Some apps will prefer to call a dedicated method of `appDatabase`.
ValueObservation
.tracking(fetchValue(_:))
.publisher(
in: appDatabase.reader,
// The `.immediate` scheduling feeds the view right on
// subscription, and avoids an undesired animation when the
// application starts.
scheduling: .immediate)
.eraseToAnyPublisher()
}
// This method is not required by Queryable, but it makes it easier
// to test PlayerRequest.
func fetchValue(_ db: Database) throws -> [Player] {
func fetch(_ db: Database) throws -> [Player] {
switch ordering {
case .byScore:
return try Player.all().orderedByScore().fetchAll(db)
@@ -43,7 +43,7 @@ struct AppView: View {
stopEditing()
}))
.toolbar { toolbarContent }
.onChange(of: players) { players in
.onChange(of: players) {
if players.isEmpty {
stopEditing()
}
@@ -132,14 +132,14 @@ private struct ToggleOrderingButton: View {
}
}
struct AppView_Previews: PreviewProvider {
static var previews: some View {
Group {
// Preview the default, empty database
AppView()
// Preview a database of random players
AppView().environment(\.appDatabase, .random())
}
}
// MARK: - Previews
#Preview("Empty") {
// Preview the default, empty database
AppView()
}
#Preview("Populated") {
// Preview a database of random players
AppView().appDatabase(.random())
}
@@ -43,8 +43,8 @@ struct PlayerCreationView: View {
}
}
struct PlayerCreationSheet_Previews: PreviewProvider {
static var previews: some View {
PlayerCreationView()
}
// MARK: - Previews
#Preview {
PlayerCreationView()
}
@@ -15,7 +15,7 @@ struct PlayerEditionView: View {
var body: some View {
PlayerFormView(form: $form)
.onChange(of: isPresented) { isPresented in
.onChange(of: isPresented) {
// Save when back button is pressed
if !isPresented {
var savedPlayer = player
@@ -28,11 +28,11 @@ struct PlayerEditionView: View {
}
}
struct PlayerEditionView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
PlayerEditionView(player: Player.makeRandom())
.navigationBarTitle("Player Edition")
}
// MARK: - Previews
#Preview {
NavigationView {
PlayerEditionView(player: Player.makeRandom())
.navigationBarTitle("Player Edition")
}
}
@@ -33,15 +33,16 @@ extension PlayerForm {
}
}
struct PlayerFormView_Previews: PreviewProvider {
static var previews: some View {
Group {
PlayerFormView(form: .constant(PlayerForm(
name: "",
score: "")))
PlayerFormView(form: .constant(PlayerForm(
name: Player.randomName(),
score: "\(Player.randomScore())")))
}
}
// MARK: - Previews
#Preview("Empty") {
PlayerFormView(form: .constant(PlayerForm(
name: "",
score: "")))
}
#Preview("Prefilled") {
PlayerFormView(form: .constant(PlayerForm(
name: Player.randomName(),
score: "\(Player.randomScore())")))
}
@@ -44,14 +44,14 @@ private struct PlayerRow: View {
}
}
struct PlayerList_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
PlayerList(players: [
Player(id: 1, name: "Arthur", score: 100),
Player(id: 2, name: "Barbara", score: 1000),
])
.navigationTitle("Preview")
}
// MARK: - Previews
#Preview {
NavigationView {
PlayerList(players: [
Player(id: 1, name: "Arthur", score: 100),
Player(id: 2, name: "Barbara", score: 1000),
])
.navigationTitle("Preview")
}
}
@@ -16,7 +16,7 @@ class PlayerRequestTests: XCTestCase {
// When we fetch players ordered by name
let playerRequest = PlayerRequest(ordering: .byName)
let players = try dbQueue.read(playerRequest.fetchValue)
let players = try dbQueue.read(playerRequest.fetch)
// Then the players are the two players ordered by name
XCTAssertEqual(players, [player1, player2])
@@ -35,7 +35,7 @@ class PlayerRequestTests: XCTestCase {
// When we fetch players ordered by score
let playerRequest = PlayerRequest(ordering: .byScore)
let players = try dbQueue.read(playerRequest.fetchValue)
let players = try dbQueue.read(playerRequest.fetch)
// Then the players are the two players ordered by score descending
XCTAssertEqual(players, [player2, player1])
@@ -25,7 +25,7 @@
<key>NSExtensionAttributes</key>
<dict>
<key>WKAppBundleIdentifier</key>
<string>com.github.groue.GRDBDemoiOS.watchkitapp</string>
<string>com.github.groue.GRDBDemoiOS2.watchkitapp</string>
</dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.watchkit</string>
@@ -26,7 +26,7 @@
<string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>
<key>WKCompanionAppBundleIdentifier</key>
<string>com.github.groue.GRDBDemoiOS</string>
<string>com.github.groue.GRDBDemoiOS2</string>
<key>WKWatchKitApp</key>
<true/>
</dict>
@@ -588,6 +588,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
GCC_C_LANGUAGE_STANDARD = gnu11;
INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -614,6 +615,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
GCC_C_LANGUAGE_STANDARD = gnu11;
INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
@@ -640,7 +642,7 @@
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -660,7 +662,7 @@
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -677,7 +679,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
IBSC_MODULE = GRDBDemoWatchOS_Extension;
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -694,7 +696,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
IBSC_MODULE = GRDBDemoWatchOS_Extension;
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -828,11 +830,12 @@
CLANG_ENABLE_OBJC_WEAK = YES;
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Debug;
@@ -845,11 +848,12 @@
CLANG_ENABLE_OBJC_WEAK = YES;
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 17.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
+3 -1
View File
@@ -397,7 +397,9 @@ let publisher = observation
// NEW: GRDB 5
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
let (sql, arguments) = try dbQueue.read(query.build)
let (sql, arguments) = try dbQueue.read { db in
try query.build(db)
}
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(arguments) // prints ["O'Brien", 42]
```
+5 -3
View File
@@ -6,7 +6,7 @@ Release Process
To release a new GRDB version:
- Tests
- `make test`
- `make distclean test`
- Build and run GRDBDemoiOS in Release configuration on a device
- Archive GRDBDemoiOS
- Check for performance regression with GRDBOSXPerformanceTests
@@ -18,8 +18,10 @@ To release a new GRDB version:
- README.md
- Support/Info.plist
- Commit and tag
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
- Push to the master & development branch
- Look for undesired tags: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
- Push to the `master` branch
- Push to the `development` branch
- Push to the `GRDB6` branch
- `pod trunk push --allow-warnings GRDB.swift.podspec`
- Update [performance comparison](https://github.com/groue/GRDB.swift/wiki/Performance):
+7 -5
View File
@@ -112,13 +112,15 @@ let components: [SQL] = [
let query = components.joined(separator: " ")
```
Extract the plain SQL string from a literal:
To extract the plain SQL string from a literal, you need a `Database` connection such as the one provided by the `read` and `write` methods:
```swift
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
let (sql, arguments) = try dbQueue.read(query.build)
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(arguments) // prints ["O'Brien", 42]
try dbQueue.read { db in
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
let (sql, arguments) = try query.build(db)
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(arguments) // prints ["O'Brien", 42]
}
```
Build a literal from a plain SQL string:
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '6.20.2'
s.version = '6.29.3'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+16
View File
@@ -75,6 +75,8 @@
562393601DEE06D300A6B01F /* CursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623935F1DEE06D300A6B01F /* CursorTests.swift */; };
562393691DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */; };
562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393711DEE104400A6B01F /* MapCursorTests.swift */; };
5623B6142AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623B6122AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift */; };
5623B6152AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623B6132AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift */; };
56256ED025D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; };
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; };
562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
@@ -155,6 +157,7 @@
5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; };
5653EB2120944C7C00F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */; };
5653EC122098738B00F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */; };
565498612B8B815500585804 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */; };
5656A7FF22946B34001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A7F822946B33001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; };
5656A81E2295B12F001FF3FF /* SQLAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A81D2295B12F001FF3FF /* SQLAssociation.swift */; };
5656A8AD2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8A92295BFD5001FF3FF /* TableRecord+Association.swift */; };
@@ -273,6 +276,7 @@
56AFEF2F29969F6E00CA1E51 /* TransactionClock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */; };
56AFEF372996B9DC00CA1E51 /* TransactionDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF362996B9DC00CA1E51 /* TransactionDateTests.swift */; };
56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; };
56B6AB062BD3DCAC009A0B71 /* SingletonUserDefaultsTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6AB052BD3DCAC009A0B71 /* SingletonUserDefaultsTest.swift */; };
56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; };
56B7EE832863781300C0525F /* WALSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7EE822863781300C0525F /* WALSnapshot.swift */; };
56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; };
@@ -489,6 +493,8 @@
5623935F1DEE06D300A6B01F /* CursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CursorTests.swift; sourceTree = "<group>"; };
562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FlattenCursorTests.swift; sourceTree = "<group>"; };
562393711DEE104400A6B01F /* MapCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MapCursorTests.swift; sourceTree = "<group>"; };
5623B6122AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueInMemoryCopyTests.swift; sourceTree = "<group>"; };
5623B6132AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueTemporaryCopyTests.swift; sourceTree = "<group>"; };
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = "<group>"; };
56256ECF25D1ACD0008C2BDD /* Table.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = "<group>"; };
56256ED825D1B316008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
@@ -765,6 +771,7 @@
56AFEF362996B9DC00CA1E51 /* TransactionDateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionDateTests.swift; sourceTree = "<group>"; };
56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = "<group>"; };
56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = "<group>"; };
56B6AB052BD3DCAC009A0B71 /* SingletonUserDefaultsTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SingletonUserDefaultsTest.swift; sourceTree = "<group>"; };
56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = "<group>"; };
56B7EE822863781300C0525F /* WALSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WALSnapshot.swift; sourceTree = "<group>"; };
56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = "<group>"; };
@@ -848,6 +855,7 @@
56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.swift; sourceTree = "<group>"; };
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = "<group>"; };
6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = "<group>"; };
648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
C96C0F242084A442006B2981 /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = "<group>"; };
D263F40926C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseColumnEncodingStrategyTests.swift; sourceTree = "<group>"; };
DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = "<group>"; };
@@ -1125,8 +1133,10 @@
5687359E1CEDE16C009B9116 /* Betty.jpeg */,
5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */,
563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */,
5623B6122AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift */,
56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */,
567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */,
5623B6132AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift */,
569178451CED9B6000E179EA /* DatabaseQueueTests.swift */,
);
name = DatabaseQueue;
@@ -1544,6 +1554,7 @@
children = (
564E73DE203D50B9000C443C /* JoinSupportTests.swift */,
5616B4FA28B5F5220052017E /* SingletonRecordTest.swift */,
56B6AB052BD3DCAC009A0B71 /* SingletonUserDefaultsTest.swift */,
5674A7251F30A8EF0095F066 /* FetchableRecord */,
560B3FA41C19DFF800C58EC7 /* PersistableRecord */,
56176C9E1EACEDF9000F3F2B /* Record */,
@@ -1731,6 +1742,7 @@
children = (
56A2FA3524424D2A00E97D23 /* Export.swift */,
566DDE0C288D763C0000DCFB /* Fixits.swift */,
648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */,
56A2386F1B9C75030082EB20 /* Core */,
567B5BDF2AD3284100629622 /* Dump */,
5698AC291D9E5A480056AF8C /* FTS */,
@@ -1867,6 +1879,7 @@
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
565498612B8B815500585804 /* PrivacyInfo.xcprivacy in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -2006,6 +2019,7 @@
56419C6B24A519A2004967E1 /* Support.swift in Sources */,
56D496871D81316E008276D7 /* DatabaseTimestampTests.swift in Sources */,
5615B26A222AFE8F00061C1C /* AssociationHasOneThroughRowScopeTests.swift in Sources */,
5623B6152AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift in Sources */,
561CFA9C2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */,
56176C5A1EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */,
56D496581D81304E008276D7 /* FoundationDateTests.swift in Sources */,
@@ -2075,11 +2089,13 @@
562393181DECC02000A6B01F /* RowFetchTests.swift in Sources */,
56677C0D241CD0D00050755D /* ValueObservationRecorder.swift in Sources */,
5653EADA20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
56B6AB062BD3DCAC009A0B71 /* SingletonUserDefaultsTest.swift in Sources */,
563B5336267E2F90009549B5 /* TableTests.swift in Sources */,
56D4965A1D81304E008276D7 /* FoundationNSDataTests.swift in Sources */,
56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */,
56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */,
5623B6142AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift in Sources */,
56AFEF372996B9DC00CA1E51 /* TransactionDateTests.swift in Sources */,
564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */,
D263F40A26C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift in Sources */,
+1 -1
View File
@@ -294,7 +294,7 @@ public struct Configuration {
/// connection is opened.
///
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_journal_mode>
public enum JournalModeConfiguration {
public enum JournalModeConfiguration: Sendable {
/// The default setup has ``DatabaseQueue`` perform no specific
/// configuration of the journal mode, and ``DatabasePool``
/// configure the database for the WAL mode (just like the
+90
View File
@@ -195,6 +195,56 @@ extension Set {
// database cursors.
try cursor.forEach { insert($0) }
}
/// Returns a new set with the elements of both this set and the
/// given cursor.
///
/// If the set already contains one or more elements that are also in
/// the cursor, the existing members are kept. If the cursor contains
/// multiple instances of equivalent elements, only the first instance
/// is kept.
///
/// - parameter cursor: A cursor of elements.
/// - returns: A new set with the unique elements of this set
/// and `cursor`.
public func union(_ cursor: some Cursor<Element>) throws -> Set<Element> {
var result = self
try result.formUnion(cursor)
return result
}
/// Inserts the elements of the given cursor into the set.
///
/// If the set already contains one or more elements that are also in
/// the cursor, the existing members are kept. If the cursor contains
/// multiple instances of equivalent elements, only the first instance
/// is kept.
///
/// - parameter cursor: A cursor of elements.
public mutating func formUnion(_ cursor: some Cursor<Element>) throws {
while let element = try cursor.next() {
insert(element)
}
}
/// Returns a new set with the elements that are common to both this set
/// and the given cursor.
///
/// - parameter cursor: A cursor of elements.
/// - returns: A new set.
public func intersection(_ cursor: some Cursor<Element>) throws -> Set<Element> {
var result = self
try result.formIntersection(cursor)
return result
}
/// Removes the elements of the set that aren’t also in the
/// given cursor.
///
/// - parameter cursor: A cursor of elements.
public mutating func formIntersection(_ cursor: some Cursor<Element>) throws {
try formIntersection(Set(cursor))
}
}
extension Sequence {
@@ -733,6 +783,11 @@ public final class AnyCursor<Element>: Cursor {
}
}
// Explicit non-conformance to Sendable: a type-erased cursor can't be more
// sendable than non-sendable cursors (such as `DatabaseCursor`).
@available(*, unavailable)
extension AnyCursor: Sendable { }
/// A `Cursor` that consumes and drops n elements from an underlying `Base`
/// cursor before possibly returning the first available element.
public final class DropFirstCursor<Base: Cursor> {
@@ -747,6 +802,11 @@ public final class DropFirstCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable: `DropFirstCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension DropFirstCursor: Sendable { }
extension DropFirstCursor: Cursor {
public func next() throws -> Base.Element? {
while dropped < limit {
@@ -773,6 +833,11 @@ public final class DropWhileCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable: `DropWhileCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension DropWhileCursor: Sendable { }
extension DropWhileCursor: Cursor {
public func next() throws -> Base.Element? {
if predicateHasFailed {
@@ -818,6 +883,11 @@ public final class EnumeratedCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable: `EnumeratedCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension EnumeratedCursor: Sendable { }
extension EnumeratedCursor: Cursor {
public func next() throws -> (Int, Base.Element)? {
guard let element = try base.next() else { return nil }
@@ -875,6 +945,11 @@ public final class FlattenCursor<Base: Cursor> where Base.Element: Cursor {
}
}
// Explicit non-conformance to Sendable: `EnumeratedCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension FlattenCursor: Sendable { }
extension FlattenCursor: Cursor {
public func next() throws -> Base.Element.Element? {
while true {
@@ -901,6 +976,11 @@ public final class MapCursor<Base: Cursor, Element> {
}
}
// Explicit non-conformance to Sendable: There is no known reason for making
// it thread-safe (`transform` a Sendable closure).
@available(*, unavailable)
extension MapCursor: Sendable { }
extension MapCursor: Cursor {
public func next() throws -> Element? {
guard let element = try base.next() else { return nil }
@@ -927,6 +1007,11 @@ public final class PrefixCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable: `PrefixCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension PrefixCursor: Sendable { }
extension PrefixCursor: Cursor {
public func next() throws -> Base.Element? {
if taken >= maxLength { return nil }
@@ -954,6 +1039,11 @@ public final class PrefixWhileCursor<Base: Cursor> {
}
}
// Explicit non-conformance to Sendable: `PrefixCursor` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension PrefixWhileCursor: Sendable { }
extension PrefixWhileCursor: Cursor {
public func next() throws -> Base.Element? {
if !predicateHasFailed, let nextElement = try base.next() {
+194 -44
View File
@@ -57,6 +57,14 @@ extension Database {
case let .attached(name): return "\(name).sqlite_master"
}
}
/// The name of the master sqlite table, without the schema name.
var unqualifiedMasterTableName: String { // swiftlint:disable:this inclusive_language
switch self {
case .main, .attached: return "sqlite_master"
case .temp: return "sqlite_temp_master"
}
}
}
/// The identifier of a database table or view.
@@ -146,6 +154,19 @@ extension Database {
return schemaIdentifiers
}
/// The `SchemaIdentifier` named `schemaName` if it exists.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if no such schema exists.
private func schemaIdentifier(named schemaName: String) throws -> SchemaIdentifier {
let allIdentifiers = try schemaIdentifiers()
if let result = allIdentifiers.first(where: { $0.sql.lowercased() == schemaName.lowercased() }) {
return result
} else {
throw DatabaseError.noSuchSchema(schemaName)
}
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Returns information about a table or a view
func table(_ tableName: String) throws -> TableInfo? {
@@ -202,10 +223,19 @@ extension Database {
return tableInfo
}
/// Returns whether a table exists, in the main or temp schema, or in an
/// attached database.
public func tableExists(_ name: String) throws -> Bool {
try schemaIdentifiers().contains {
/// Returns whether a table exists
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
public func tableExists(_ name: String, in schemaName: String? = nil) throws -> Bool {
if let schemaName {
return try exists(type: .table, name: name, in: schemaName)
}
return try schemaIdentifiers().contains {
try exists(type: .table, name: name, in: $0)
}
}
@@ -238,20 +268,57 @@ extension Database {
/// Returns whether a view exists, in the main or temp schema, or in an
/// attached database.
public func viewExists(_ name: String) throws -> Bool {
try schemaIdentifiers().contains {
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
public func viewExists(_ name: String, in schemaName: String? = nil) throws -> Bool {
if let schemaName {
return try exists(type: .view, name: name, in: schemaName)
}
return try schemaIdentifiers().contains {
try exists(type: .view, name: name, in: $0)
}
}
/// Returns whether a trigger exists, in the main or temp schema, or in an
/// attached database.
public func triggerExists(_ name: String) throws -> Bool {
try schemaIdentifiers().contains {
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
public func triggerExists(_ name: String, in schemaName: String? = nil) throws -> Bool {
if let schemaName {
return try exists(type: .trigger, name: name, in: schemaName)
}
return try schemaIdentifiers().contains {
try exists(type: .trigger, name: name, in: $0)
}
}
/// Checks if an entity exists in a given schema
///
/// This is checking for the existence of the entity specified by
/// `type` and `name`. It is assumed that the existence of a schema
/// named `schemaName` is already known and will throw an error if it
/// cannot be found.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
private func exists(type: SchemaObjectType, name: String, in schemaName: String) throws -> Bool {
if let schemaID = try schemaIdentifiers().first(where: { $0.sql.lowercased() == schemaName.lowercased() }) {
return try exists(type: type, name: name, in: schemaID)
} else {
throw DatabaseError.noSuchSchema(schemaName)
}
}
private func exists(type: SchemaObjectType, name: String, in schemaID: SchemaIdentifier) throws -> Bool {
// SQLite identifiers are case-insensitive, case-preserving:
// http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html
@@ -264,10 +331,17 @@ extension Database {
/// table has no explicit primary key, the result is the hidden
/// "rowid" column.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
/// such table exists in the main or temp schema, or in an
/// attached database.
public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo {
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist, or if no such table exists in
/// the main or temp schema, or in an attached database.
public func primaryKey(_ tableName: String, in schemaName: String? = nil) throws -> PrimaryKeyInfo {
if let schemaName {
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: primaryKey(_:))
}
for schemaIdentifier in try schemaIdentifiers() {
if let result = try primaryKey(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
@@ -426,10 +500,18 @@ extension Database {
/// the columns contain the primary key or a unique index, use
/// ``table(_:hasUniqueKey:)``.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
/// such table exists in the main or temp schema, or in an
/// attached database.
public func indexes(on tableName: String) throws -> [IndexInfo] {
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist, or if no such table or view
/// with this name exists in the main or temp schema, or in an attached
/// database.
public func indexes(on tableName: String, in schemaName: String? = nil) throws -> [IndexInfo] {
if let schemaName {
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: indexes(on:))
}
for schemaIdentifier in try schemaIdentifiers() {
if let result = try indexes(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
@@ -518,10 +600,18 @@ extension Database {
/// Returns the foreign keys defined on table named `tableName`.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
/// such table exists in the main or temp schema, or in an
/// attached database.
public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] {
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist, or if no such table or view
/// with this name exists in the main or temp schema, or in an attached
/// database.
public func foreignKeys(on tableName: String, in schemaName: String? = nil) throws -> [ForeignKeyInfo] {
if let schemaName {
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: foreignKeys(on:))
}
for schemaIdentifier in try schemaIdentifiers() {
if let result = try foreignKeys(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
@@ -602,10 +692,27 @@ extension Database {
/// Returns a cursor over foreign key violations in the table.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
/// such table exists in the main or temp schema, or in an
/// attached database.
public func foreignKeyViolations(in tableName: String) throws -> RecordCursor<ForeignKeyViolation> {
/// When `schemaName` is not specified, known schemas are checked in
/// SQLite resolution order and the first matching table is used.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist, or if no such table or view
/// with this name exists in the main or temp schema, or in an attached
/// database.
public func foreignKeyViolations(
in tableName: String,
in schemaName: String? = nil)
throws -> RecordCursor<ForeignKeyViolation>
{
if let schemaName {
let schemaID = try schemaIdentifier(named: schemaName)
if try exists(type: .table, name: tableName, in: schemaID) {
return try foreignKeyViolations(in: TableIdentifier(schemaID: schemaID, name: tableName))
} else {
throw DatabaseError.noSuchTable(tableName)
}
}
for schemaIdentifier in try schemaIdentifiers() {
if try exists(type: .table, name: tableName, in: schemaIdentifier) {
return try foreignKeyViolations(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName))
@@ -634,14 +741,21 @@ extension Database {
/// Throws an error if there exists a foreign key violation in the table.
///
/// When `schemaName` is not specified, known schemas are checked in
/// SQLite resolution order and the first matching table is used.
///
/// On the first foreign key violation found in the table, this method
/// throws a ``DatabaseError`` with extended code
/// `SQLITE_CONSTRAINT_FOREIGNKEY`.
///
/// If you are looking for the list of foreign key violations, prefer
/// ``foreignKeyViolations(in:)`` instead.
public func checkForeignKeys(in tableName: String) throws {
try checkForeignKeys(from: foreignKeyViolations(in: tableName))
/// ``foreignKeyViolations(in:in:)`` instead.
///
/// - throws: A ``DatabaseError`` as described above; when a
/// specified schema does not exist; if no such table or view with this
/// name exists in the main or temp schema or in an attached database.
public func checkForeignKeys(in tableName: String, in schemaName: String? = nil) throws {
try checkForeignKeys(from: foreignKeyViolations(in: tableName, in: schemaName))
}
private func checkForeignKeys(from violations: RecordCursor<ForeignKeyViolation>) throws {
@@ -658,9 +772,17 @@ extension Database {
/// attached database.
func canonicalTableName(_ tableName: String) throws -> String? {
for schemaIdentifier in try schemaIdentifiers() {
// Regular tables
if let result = try schema(schemaIdentifier).canonicalName(tableName, ofType: .table) {
return result
}
// Master table (sqlite_master, sqlite_temp_master)
// swiftlint:disable:next inclusive_language
let masterTableName = schemaIdentifier.unqualifiedMasterTableName
if tableName.lowercased() == masterTableName.lowercased() {
return masterTableName
}
}
return nil
}
@@ -673,16 +795,44 @@ extension Database {
schemaCache[schemaID].schemaInfo = schemaInfo
return schemaInfo
}
/// Attempts to perform a table introspection function on a given
/// table and schema
///
/// - parameter tableName: The name of the table to examine
/// - parameter schemaName: The name of the schema to check
/// - parameter introspector: An introspection function taking a
/// `TableIdentifier` as the only parameter
private func introspect<T>(
tableNamed tableName: String,
inSchemaNamed schemaName: String,
using introspector: (TableIdentifier) throws -> T?
) throws -> T {
let schemaIdentifier = try schemaIdentifier(named: schemaName)
if let result = try introspector(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
} else {
throw DatabaseError.noSuchTable(tableName)
}
}
}
extension Database {
/// Returns the columns in a table or a view.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
/// such table or view with this name exists in the main or temp schema, or
/// in an attached database.
public func columns(in tableName: String) throws -> [ColumnInfo] {
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist,or if no such table or view
/// with this name exists in the main or temp schema, or in an attached
/// database.
public func columns(in tableName: String, in schemaName: String? = nil) throws -> [ColumnInfo] {
if let schemaName {
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: columns(in:))
}
for schemaIdentifier in try schemaIdentifiers() {
if let result = try columns(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
@@ -840,14 +990,14 @@ extension Database {
/// Information about a column of a database table.
///
/// You get `ColumnInfo` instances with the ``Database/columns(in:)``
/// You get `ColumnInfo` instances with the ``Database/columns(in:in:)``
/// `Database` method.
///
/// Related SQLite documentation:
///
/// - [pragma `table_info`](https://www.sqlite.org/pragma.html#pragma_table_info)
/// - [pragma `table_xinfo`](https://www.sqlite.org/pragma.html#pragma_table_xinfo)
public struct ColumnInfo: FetchableRecord {
public struct ColumnInfo: FetchableRecord, Sendable {
let cid: Int
let hidden: Int?
@@ -926,16 +1076,16 @@ public struct ColumnInfo: FetchableRecord {
/// Information about an index.
///
/// You get `IndexInfo` instances with the ``Database/indexes(on:)``
/// You get `IndexInfo` instances with the ``Database/indexes(on:in:)``
/// `Database` method.
///
/// Related SQLite documentation:
///
/// - [pragma `index_list`](https://www.sqlite.org/pragma.html#pragma_index_list)
/// - [pragma `index_info`](https://www.sqlite.org/pragma.html#pragma_index_info)
public struct IndexInfo {
public struct IndexInfo: Sendable{
/// The origin of an index.
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible {
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible, Sendable {
public var rawValue: String
public init(rawValue: String) {
@@ -969,7 +1119,7 @@ public struct IndexInfo {
///
/// You get instances of `ForeignKeyViolation` from the `Database` methods
/// ``Database/foreignKeyViolations()`` and
/// ``Database/foreignKeyViolations(in:)`` methods.
/// ``Database/foreignKeyViolations(in:in:)`` methods.
///
/// For example:
///
@@ -1008,7 +1158,7 @@ public struct IndexInfo {
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_foreign_key_check>
public struct ForeignKeyViolation {
public struct ForeignKeyViolation: Sendable {
/// The name of the table that contains the foreign key.
public var originTable: String
@@ -1023,7 +1173,7 @@ public struct ForeignKeyViolation {
/// The id of the foreign key constraint that failed.
///
/// This id matches the ``ForeignKeyInfo/id`` property in
/// ``ForeignKeyInfo``. See ``Database/foreignKeys(on:)``.
/// ``ForeignKeyInfo``. See ``Database/foreignKeys(on:in:)``.
public var foreignKeyId: Int
/// A precise description of the foreign key violation.
@@ -1113,7 +1263,7 @@ extension ForeignKeyViolation: CustomStringConvertible {
/// Information about a primary key.
///
/// You get `PrimaryKeyInfo` instances with the ``Database/primaryKey(_:)``
/// You get `PrimaryKeyInfo` instances with the ``Database/primaryKey(_:in:)``
/// `Database` method.
///
/// When the table's primary key is the rowid:
@@ -1157,7 +1307,7 @@ extension ForeignKeyViolation: CustomStringConvertible {
/// pk.rowIDColumn // nil
/// pk.isRowID // false
/// ```
public struct PrimaryKeyInfo {
public struct PrimaryKeyInfo: Sendable {
private enum Impl {
/// The hidden rowID.
case hiddenRowID
@@ -1279,11 +1429,11 @@ public struct PrimaryKeyInfo {
/// Information about a foreign key.
///
/// You get `ForeignKeyInfo` instances with the ``Database/foreignKeys(on:)``
/// You get `ForeignKeyInfo` instances with the ``Database/foreignKeys(on:in:)``
/// `Database` method.
///
/// Related SQLite documentation: [pragma `foreign_key_list`](https://www.sqlite.org/pragma.html#pragma_foreign_key_list).
public struct ForeignKeyInfo {
public struct ForeignKeyInfo: Sendable {
/// The first column in the output of the `foreign_key_list` pragma.
public var id: Int
@@ -1367,7 +1517,7 @@ struct SchemaObject: Hashable, FetchableRecord {
/// All objects in a database schema (tables, views, indexes, triggers).
struct SchemaInfo: Equatable {
private var objects: Set<SchemaObject>
let objects: Set<SchemaObject>
/// Returns whether there exists a object of given type with this name
/// (case-insensitive).
+5
View File
@@ -361,6 +361,11 @@ public class SQLStatementCursor {
}
}
// Explicit non-conformance to Sendable: database cursors must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension SQLStatementCursor: Sendable { }
extension SQLStatementCursor: Cursor {
public func next() throws -> Statement? {
guard offset < cString.count - 1 /* trailing \0 */ else {
+161 -24
View File
@@ -60,6 +60,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``inSavepoint(_:)``
/// - ``inTransaction(_:_:)``
/// - ``isInsideTransaction``
/// - ``readOnly(_:)``
/// - ``rollback()``
/// - ``transactionDate``
/// - ``TransactionCompletion``
@@ -69,8 +70,9 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
///
/// - ``dumpContent(format:to:)``
/// - ``dumpRequest(_:format:to:)``
/// - ``dumpSchema(to:)``
/// - ``dumpSQL(_:format:to:)``
/// - ``dumpTables(_:format:tableHeader:to:)``
/// - ``dumpTables(_:format:tableHeader:stableOrder:to:)``
/// - ``DumpFormat``
/// - ``DumpTableHeaderOptions``
///
@@ -79,6 +81,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``add(transactionObserver:extent:)``
/// - ``remove(transactionObserver:)``
/// - ``afterNextTransaction(onCommit:onRollback:)``
/// - ``notifyChanges(in:)``
/// - ``registerAccess(to:)``
///
/// ### Collations
@@ -112,6 +115,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``trace(options:_:)``
/// - ``CheckpointMode``
/// - ``DatabaseBackupProgress``
/// - ``StorageClass``
/// - ``TraceEvent``
/// - ``TracingOptions``
public final class Database: CustomStringConvertible, CustomDebugStringConvertible {
@@ -120,8 +124,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// MARK: - SQLite C API
// TODO: make it non optional, since one can't get a `Database` instance
// after `close()`.
/// The raw SQLite connection, suitable for the SQLite C API.
///
/// The result is nil after the database has been successfully closed with
@@ -771,11 +773,38 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
/// Grants read-only access in the wrapped closure.
func readOnly<T>(_ block: () throws -> T) throws -> T {
/// Executes read-only database operations, and returns their result
/// after they have finished executing.
///
/// Attempts to write throw a ``DatabaseError`` with
/// resultCode `SQLITE_READONLY`.
///
/// For example:
///
/// ```swift
/// try dbQueue.write do { db in
/// // Write OK
/// try Player(...).insert(db)
///
/// try db.readOnly {
/// // Read OK
/// let players = try Player.fetchAll(db)
///
/// // Throws SQLITE_READONLY
/// try Player(...).insert(db)
/// }
/// }
/// ```
///
/// This method is reentrant.
///
/// - parameter value: A closure that reads from the database.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the
/// error thrown by `value`.
public func readOnly<T>(_ value: () throws -> T) throws -> T {
try beginReadOnly()
return try throwingFirstError(
execute: block,
execute: value,
finally: endReadOnly)
}
@@ -789,6 +818,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// Reports the database region to ``ValueObservation``.
///
/// Calling this method does not fetch any database values. It just
/// helps optimizing `ValueObservation`. See
/// ``ValueObservation/trackingConstantRegion(_:)`` for more
/// information, and some examples of usage.
///
/// For example:
///
/// ```swift
@@ -800,12 +834,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// }
/// ```
///
/// See ``ValueObservation/trackingConstantRegion(_:)`` for some examples
/// of region reporting.
///
/// This method has no effect on a ``ValueObservation`` created with an
/// explicit list of tracked regions. In the example below, only the
/// `player` table is tracked:
/// This method has no effect on a `ValueObservation` created with
/// ``ValueObservation/tracking(regions:fetch:)``. In the example below,
/// only the `player` table is tracked:
///
/// ```swift
/// // Observes the 'player' table only
@@ -820,6 +851,65 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
/// Notifies that some changes were performed in the provided
/// database region.
///
/// This method makes it possible to notify undetected changes, such as
/// changes performed by another process, changes performed by
/// direct calls to SQLite C functions, or changes to the
/// database schema.
/// See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes>
/// for a detailed list of undetected database modifications.
///
/// It triggers active transaction observers (``TransactionObserver``).
/// In particular, ``ValueObservation`` that observe the input `region`
/// will fetch and notify a fresh value.
///
/// For example:
///
/// ```swift
/// try dbQueue.write { db in
/// // Notify observers that some changes were performed in the database
/// try db.notifyChanges(in: .fullDatabase)
///
/// // Notify observers that some changes were performed in the player table
/// try db.notifyChanges(in: Player.all())
///
/// // Equivalent alternative
/// try db.notifyChanges(in: Table("player"))
/// }
/// ```
///
/// This method has no effect when called from a read-only
/// database access.
///
/// > Caveat: Individual rowids in the input region are ignored.
/// > Notifying a change to a specific rowid is the same as notifying a
/// > change in the whole table:
/// >
/// > ```swift
/// > try dbQueue.write { db in
/// > // Equivalent
/// > try db.notifyChanges(in: Player.all())
/// > try db.notifyChanges(in: Player.filter(id: 1))
/// > }
/// > ```
public func notifyChanges(in region: some DatabaseRegionConvertible) throws {
// Don't do anything when read-only, because read-only transactions
// are not notified. We don't want to notify transactions observers
// of changes, and have them wait for a commit notification that
// will never come.
if !isReadOnly, let observationBroker {
let eventKinds = try region
.databaseRegion(self)
// Use canonical table names for case insensitivity of the input.
.canonicalTables(self)
.impactfulEventKinds(self)
try observationBroker.notifyChanges(withEventsOfKind: eventKinds)
}
}
/// Extends the `region` argument with the database region selected by all
/// statements executed by the closure, and all regions explicitly tracked
/// with the ``registerAccess(to:)`` method.
@@ -1165,7 +1255,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// For example:
///
/// ```swift
/// try dbQueue.writeWithoutTransaction do {
/// try dbQueue.writeWithoutTransaction do { db in
/// try db.inTransaction {
/// try db.execute(sql: "INSERT ...")
/// return .commit
@@ -1485,7 +1575,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// Frees as much memory as possible.
public func releaseMemory() {
SchedulingWatchdog.preconditionValidQueue(self)
sqlite3_db_release_memory(sqliteConnection)
if let sqliteConnection {
sqlite3_db_release_memory(sqliteConnection)
}
schemaCache.clear()
internalStatementCache.clear()
publicStatementCache.clear()
@@ -1641,6 +1733,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
// Explicit non-conformance to Sendable: `Database` must be used from a
// serialized database access dispatch queue (see `SerializedDatabase`).
@available(*, unavailable)
extension Database: Sendable { }
#if SQLITE_HAS_CODEC
extension Database {
@@ -1766,7 +1863,7 @@ extension Database {
/// The available checkpoint modes.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/wal_checkpoint_v2.html>
public enum CheckpointMode: CInt {
public enum CheckpointMode: CInt, Sendable {
/// The `SQLITE_CHECKPOINT_PASSIVE` mode.
case passive = 0
@@ -1785,7 +1882,7 @@ extension Database {
/// Related SQLite documentation:
/// - <https://www.sqlite.org/datatype3.html#collating_sequences>
/// - <https://www.sqlite.org/datatype3.html#collation>
public struct CollationName: RawRepresentable, Hashable {
public struct CollationName: RawRepresentable, Hashable, Sendable {
public let rawValue: String
/// Creates a collation name.
@@ -1822,11 +1919,10 @@ extension Database {
///
/// For more information, see
/// [Datatypes In SQLite](https://www.sqlite.org/datatype3.html).
public struct ColumnType: RawRepresentable, Hashable {
public struct ColumnType: RawRepresentable, Hashable, Sendable {
/// The SQL for the column type (`"TEXT"`, `"BLOB"`, etc.)
public let rawValue: String
// TODO: GRDB7 make it an failable initializer that returns nil when rawValue is empty (or blank).
/// Creates an SQL column type.
public init(rawValue: String) {
self.rawValue = rawValue
@@ -1874,7 +1970,7 @@ extension Database {
/// An SQLite conflict resolution.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_conflict.html>
public enum ConflictResolution: String {
public enum ConflictResolution: String, Sendable {
/// The `ROLLBACK` conflict resolution.
case rollback = "ROLLBACK"
@@ -1894,7 +1990,7 @@ extension Database {
/// A foreign key action.
///
/// Related SQLite documentation: <https://www.sqlite.org/foreignkeys.html>
public enum ForeignKeyAction: String {
public enum ForeignKeyAction: String, Sendable {
/// The `CASCADE` foreign key action.
case cascade = "CASCADE"
@@ -1911,13 +2007,39 @@ extension Database {
/// An error log function that takes an error code and message.
public typealias LogErrorFunction = (_ resultCode: ResultCode, _ message: String) -> Void
/// An SQLite storage class.
///
/// For more information, see
/// [Datatypes In SQLite](https://www.sqlite.org/datatype3.html).
public struct StorageClass: RawRepresentable, Hashable, Sendable {
/// The SQL for the storage class (`"INTEGER"`, `"REAL"`, etc.)
public let rawValue: String
/// Creates an SQL storage class.
public init(rawValue: String) {
self.rawValue = rawValue
}
/// The `INTEGER` storage class.
public static let integer = StorageClass(rawValue: "INTEGER")
/// The `REAL` storage class.
public static let real = StorageClass(rawValue: "REAL")
/// The `TEXT` storage class.
public static let text = StorageClass(rawValue: "TEXT")
/// The `BLOB` storage class.
public static let blob = StorageClass(rawValue: "BLOB")
}
/// An option for the SQLite tracing feature.
///
/// You use `TracingOptions` with the `Database`
/// ``Database/trace(options:_:)`` method.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/c_trace.html>
public struct TracingOptions: OptionSet {
public struct TracingOptions: OptionSet, Sendable {
/// The raw trace event code.
public let rawValue: CInt
@@ -1960,7 +2082,8 @@ extension Database {
/// ```
public var sql: String {
if let unexpandedSQL {
return String(cString: unexpandedSQL).trimmedSQLStatement
let sql = String(cString: unexpandedSQL)
return sql.hasPrefix("--") ? sql : sql.trimmedSQLStatement
} else {
return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
}
@@ -1978,6 +2101,10 @@ extension Database {
/// information from leaking in unexpected locations, so use this
/// property with care.
public var expandedSQL: String {
if let unexpandedSQL {
let sql = String(cString: unexpandedSQL)
if sql.hasPrefix("--") { return sql }
}
guard let cString = sqlite3_expanded_sql(sqliteStatement) else {
return ""
}
@@ -2050,7 +2177,7 @@ extension Database {
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
@frozen
public enum TransactionCompletion {
public enum TransactionCompletion: Sendable {
case commit
case rollback
}
@@ -2058,7 +2185,7 @@ extension Database {
/// A transaction kind.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
public enum TransactionKind: String {
public enum TransactionKind: String, Sendable {
/// The `DEFERRED` transaction kind.
case deferred = "DEFERRED"
@@ -2091,3 +2218,13 @@ extension Database {
}
}
}
// Explicit non-conformance to Sendable: a trace event contains transient
// information.
@available(*, unavailable)
extension Database.TraceEvent: Sendable { }
// Explicit non-conformance to Sendable: a trace event contains transient
// information.
@available(*, unavailable)
extension Database.TraceEvent.Statement: Sendable { }
+1 -1
View File
@@ -1,7 +1,7 @@
/// Describe the progress of a database backup.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/backup_finish.html>
public struct DatabaseBackupProgress {
public struct DatabaseBackupProgress: Sendable {
/// The number of pages still to be backed up.
///
/// It is the result of the `sqlite3_backup_remaining` function.
+4
View File
@@ -396,6 +396,10 @@ public struct DatabaseError: Error {
static func noSuchTable(_ tableName: String) -> Self {
DatabaseError(message: "no such table: \(tableName)")
}
static func noSuchSchema(_ schemaName: String) -> Self {
DatabaseError(message: "no such schema: \(schemaName)")
}
}
extension DatabaseError {
+18 -15
View File
@@ -34,19 +34,6 @@ public final class DatabaseFunction: Hashable {
private let kind: Kind
private var eTextRep: CInt { (SQLITE_UTF8 | (isPure ? SQLITE_DETERMINISTIC : 0)) }
var functionFlags: SQLFunctionFlags {
var flags = SQLFunctionFlags(isPure: isPure)
switch kind {
case .function:
break
case .aggregate:
flags.isAggregate = true
}
return flags
}
/// Creates an SQL function.
///
/// For example:
@@ -157,6 +144,7 @@ public final class DatabaseFunction: Hashable {
self.kind = .aggregate { Aggregate() }
}
// TODO: GRDB7 -> expose ORDER BY and FILTER when we have distinct types for simple functions and aggregates.
/// Returns an SQL expression that applies the function.
///
/// You can use a `DatabaseFunction` as a regular Swift function. It returns
@@ -183,9 +171,24 @@ public final class DatabaseFunction: Hashable {
/// }
/// ```
public func callAsFunction(_ arguments: any SQLExpressible...) -> SQLExpression {
.function(name, arguments.map(\.sqlExpression), flags: functionFlags)
switch kind {
case .function:
return .simpleFunction(
name,
arguments.map(\.sqlExpression),
isPure: isPure,
isJSONValue: false)
case .aggregate:
return .aggregateFunction(
name,
arguments.map(\.sqlExpression),
isDistinct: false,
ordering: nil,
filter: nil,
isJSONValue: false)
}
}
/// Calls sqlite3_create_function_v2
/// See <https://sqlite.org/c3ref/create_function.html>
func install(in db: Database) {
+93
View File
@@ -429,3 +429,96 @@ extension DatabaseQueue: DatabaseWriter {
writer.async(updates)
}
}
// MARK: - Temp Copy
extension DatabaseQueue {
/// Returns a connection to an in-memory copy of the database at `path`.
///
/// Changes performed on the returned connection do not impact the
/// original database at `path`.
///
/// The database memory is released when the returned connection
/// is deallocated.
///
/// For example:
///
/// ```swift
/// let path = "/path/to/database.sqlite"
/// let dbQueue = try DatabaseQueue.inMemoryCopy(fromPath: path)
/// ```
public static func inMemoryCopy(
fromPath path: String,
configuration: Configuration = Configuration())
throws -> DatabaseQueue
{
var sourceConfig = configuration
sourceConfig.readonly = true
let source = try DatabaseQueue(path: path, configuration: sourceConfig)
var copyConfig = configuration
copyConfig.readonly = false
let result = try DatabaseQueue(configuration: copyConfig)
try source.backup(to: result)
if configuration.readonly {
// Result was not opened read-only so that we could perform the
// copy. And SQLITE_OPEN_READONLY has no effect on in-memory
// databases anyway.
//
// So let's simulate read-only with PRAGMA query_only.
try result.inDatabase { db in
try db.beginReadOnly()
}
}
return result
}
/// Returns a connection to a private, temporary, on-disk copy of the
/// database at `path`.
///
/// Changes performed on the returned connection do not impact the
/// original database at `path`.
///
/// The on-disk copy will be automatically deleted from disk as soon as
/// the returned connection is closed or deallocated.
///
/// For example:
///
/// ```swift
/// let path = "/path/to/database.sqlite"
/// let dbQueue = try DatabaseQueue.temporaryCopy(fromPath: path)
/// ```
public static func temporaryCopy(
fromPath path: String,
configuration: Configuration = Configuration())
throws -> DatabaseQueue
{
var sourceConfig = configuration
sourceConfig.readonly = true
let source = try DatabaseQueue(path: path, configuration: sourceConfig)
// <https://www.sqlite.org/c3ref/open.html>
// > If the filename is an empty string, then a private, temporary
// > on-disk database will be created. This private database will be
// > automatically deleted as soon as the database connection
// > is closed.
var copyConfig = configuration
copyConfig.readonly = false
let result = try DatabaseQueue(path: "", configuration: copyConfig)
try source.backup(to: result)
if configuration.readonly {
// Result was not opened read-only so that we could perform the
// copy. So let's simulate read-only with PRAGMA query_only.
try result.inDatabase { db in
try db.beginReadOnly()
}
}
return result
}
}
+2 -1
View File
@@ -37,8 +37,9 @@ import Dispatch
///
/// - ``dumpContent(format:to:)``
/// - ``dumpRequest(_:format:to:)``
/// - ``dumpSchema(to:)``
/// - ``dumpSQL(_:format:to:)``
/// - ``dumpTables(_:format:tableHeader:to:)``
/// - ``dumpTables(_:format:tableHeader:stableOrder:to:)``
/// - ``DumpFormat``
/// - ``DumpTableHeaderOptions``
///
+44 -6
View File
@@ -40,7 +40,7 @@
///
/// - ``isModified(byEventsOfKind:)``
/// - ``isModified(by:)``
public struct DatabaseRegion {
public struct DatabaseRegion: Sendable {
private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) {
@@ -169,16 +169,16 @@ public struct DatabaseRegion {
// the observed region, we optimize database observation.
//
// And by canonicalizing table names, we remove views, and help the
// `isModified` methods.
// `isModified` methods. (TODO: is this comment still accurate?
// Isn't it about providing TransactionObserver.observes() with
// real tables names, instead?)
try ignoringInternalSQLiteTables().canonicalTables(db)
}
/// Returns a region only made of actual tables with their canonical names.
/// Canonical names help the `isModified` methods.
///
/// This method removes views (assuming no table exists with the same name
/// as a view).
private func canonicalTables(_ db: Database) throws -> DatabaseRegion {
/// This method removes views.
func canonicalTables(_ db: Database) throws -> DatabaseRegion {
guard let tableRegions else { return .fullDatabase }
var region = DatabaseRegion()
for (table, tableRegion) in tableRegions {
@@ -233,6 +233,44 @@ extension DatabaseRegion {
}
return tableRegion.contains(rowID: event.rowID)
}
/// Returns an array of all event kinds that can impact this region.
///
/// - precondition: the region is canonical.
func impactfulEventKinds(_ db: Database) throws -> [DatabaseEventKind] {
if let tableRegions {
return try tableRegions.flatMap { (table, tableRegion) -> [DatabaseEventKind] in
let tableName = table.rawValue // canonical table name
let columnNames: Set<String>
if let columns = tableRegion.columns {
columnNames = Set(columns.map(\.rawValue))
} else {
columnNames = try Set(db.columns(in: tableName).map(\.name))
}
return [
DatabaseEventKind.delete(tableName: tableName),
DatabaseEventKind.insert(tableName: tableName),
DatabaseEventKind.update(tableName: tableName, columnNames: columnNames),
]
}
} else {
// full database
return try db.schemaIdentifiers().flatMap { schemaIdentifier in
let schema = try db.schema(schemaIdentifier)
return try schema.objects
.filter { $0.type == .table }
.flatMap { table in
let columnNames = try Set(db.columns(in: table.name).map(\.name))
return [
DatabaseEventKind.delete(tableName: table.name),
DatabaseEventKind.insert(tableName: table.name),
DatabaseEventKind.update(tableName: table.name, columnNames: columnNames),
]
}
}
}
}
}
extension DatabaseRegion: Equatable {
@@ -161,6 +161,11 @@ private class DatabaseRegionObserver: TransactionObserver {
region.isModified(byEventsOfKind: eventKind)
}
func databaseDidChange() {
isChanged = true
stopObservingDatabaseChangesUntilNextTransaction()
}
func databaseDidChange(with event: DatabaseEvent) {
if region.isModified(by: event) {
isChanged = true
+6 -2
View File
@@ -59,10 +59,14 @@ import Dispatch
/// let snapshot2 = try dbPool.makeSnapshot()
///
/// // Guaranteed to be zero
/// let count1 = try snapshot1.read(Player.fetchCount)
/// let count1 = try snapshot1.read { db in
/// try Player.fetchCount(db)
/// }
///
/// // Could be anything
/// let count2 = try snapshot2.read(Player.fetchCount)
/// let count2 = try snapshot2.read { db in
/// try Player.fetchCount(db)
/// }
/// ```
///
/// `DatabaseSnapshot` inherits its database access methods from the
+3 -1
View File
@@ -104,7 +104,9 @@ public final class DatabaseSnapshotPool {
///
/// // Later... Maybe some players have been created.
/// // The snapshot is guaranteed to see an empty table of players, though:
/// let count = try snapshot.read(Player.fetchCount)
/// let count = try snapshot.read { db in
/// try Player.fetchCount(db)
/// }
/// assert(count == 0)
/// ```
///
+5
View File
@@ -222,6 +222,11 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
}
}
// Explicit non-conformance to Sendable: database cursors must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension DatabaseValueCursor: Sendable { }
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
/// cursors, arrays, or single values:
///
+5
View File
@@ -152,6 +152,11 @@ public struct PreparedRequest {
}
}
// Explicit non-conformance to Sendable: `PreparedRequest` contains
// a statement.
@available(*, unavailable)
extension PreparedRequest: Sendable { }
extension PreparedRequest: Refinable { }
// MARK: - AdaptedFetchRequest
+12 -1
View File
@@ -245,6 +245,12 @@ public final class Row {
}
}
// Explicit non-conformance to Sendable: a row contains transient
// information. TODO GRDB7: split non sendable statement rows from sendable
// copied rows.
@available(*, unavailable)
extension Row: Sendable { }
extension Row {
// MARK: - Columns
@@ -1377,6 +1383,11 @@ public final class RowCursor: DatabaseCursor {
public func _element(sqliteStatement: SQLiteStatement) -> Row { _row }
}
// Explicit non-conformance to Sendable: database cursors must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension RowCursor: Sendable { }
extension Row {
// MARK: - Fetching From Prepared Statement
@@ -2059,7 +2070,7 @@ typealias RowIndex = Row.Index
extension Row {
/// An index to a (column, value) pair in a ``Row``.
public struct Index {
public struct Index: Sendable {
let index: Int
init(_ index: Int) { self.index = index }
}
+4 -4
View File
@@ -378,7 +378,7 @@ extension RowAdapter {
///
/// This limit adapter may turn out useful in some narrow use cases. You'll
/// be happy to find it when you need it.
public struct EmptyRowAdapter: RowAdapter {
public struct EmptyRowAdapter: RowAdapter, Sendable {
/// Creates an `EmptyRowAdapter`.
public init() { }
@@ -403,7 +403,7 @@ public struct EmptyRowAdapter: RowAdapter {
///
/// Note that columns that are not present in the dictionary are not present
/// in the resulting adapted row.
public struct ColumnMapping: RowAdapter {
public struct ColumnMapping: RowAdapter, Sendable {
/// A dictionary from mapped column names to column names in a base row.
let mapping: [String: String]
@@ -444,7 +444,7 @@ public struct ColumnMapping: RowAdapter {
/// // [c:2, d: 3]
/// try Row.fetchOne(db, sql: sql, adapter: adapter)!
/// ```
public struct SuffixRowAdapter: RowAdapter {
public struct SuffixRowAdapter: RowAdapter, Sendable {
/// The suffix index
let index: Int
@@ -473,7 +473,7 @@ public struct SuffixRowAdapter: RowAdapter {
/// // [b:1 c:2]
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
/// ```
public struct RangeRowAdapter: RowAdapter {
public struct RangeRowAdapter: RowAdapter, Sendable {
/// The range
let range: CountableRange<Int>
+5
View File
@@ -623,6 +623,11 @@ public final class Statement {
}
}
// Explicit non-conformance to Sendable: statements must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension Statement: Sendable { }
extension Statement: CustomStringConvertible {
public var description: String {
SchedulingWatchdog.allows(database) ? sql : "Statement"
+5 -1
View File
@@ -1,5 +1,9 @@
#if os(Linux)
#if canImport(string_h)
import string_h
#elseif os(Linux)
import Glibc
#elseif os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(visionOS)
import Darwin
#endif
/// `StatementAuthorizer` provides information about compiled database
@@ -241,6 +241,11 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
}
}
// Explicit non-conformance to Sendable: database cursors must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension FastDatabaseValueCursor: Sendable { }
/// Types that adopt both DatabaseValueConvertible and
/// StatementColumnConvertible can be efficiently initialized from
/// database values.
@@ -1,10 +1,10 @@
import Foundation
/// A database value that holds date components.
public struct DatabaseDateComponents {
public struct DatabaseDateComponents: Sendable {
/// The SQLite formats for date components.
public enum Format: String {
public enum Format: String, Sendable {
/// The format "yyyy-MM-dd".
case YMD = "yyyy-MM-dd"
@@ -4,7 +4,6 @@ import Foundation
@usableFromInline
struct SQLiteDateParser {
// swiftlint:disable:next unneeded_synthesized_initializer
@usableFromInline
init() { }
+58 -8
View File
@@ -135,7 +135,7 @@ extension Database {
}
/// The extent of the observation performed by a ``TransactionObserver``.
public enum TransactionObservationExtent {
public enum TransactionObservationExtent: Sendable {
/// Observation lasts until observer is deallocated.
case observerLifetime
/// Observation lasts until the next transaction.
@@ -282,6 +282,20 @@ class DatabaseObservationBroker {
}
}
func notifyChanges(withEventsOfKind eventKinds: [DatabaseEventKind]) throws {
// Support for stopObservingDatabaseChangesUntilNextTransaction()
SchedulingWatchdog.current!.databaseObservationBroker = self
defer {
SchedulingWatchdog.current!.databaseObservationBroker = nil
}
for observation in transactionObservations where observation.isEnabled {
if eventKinds.contains(where: { observation.observes(eventsOfKind: $0) }) {
observation.databaseDidChange()
}
}
}
// MARK: - Statement execution
/// Returns true if there exists some transaction observer interested in
@@ -566,6 +580,11 @@ class DatabaseObservationBroker {
// even if we actually execute an empty deferred transaction.
//
// For better or for worse, let's simulate a transaction:
//
// 2023-11-26: I'm glad we did, because that's how we support calls
// to `Database.notifyChanges(in:)` from an empty transaction, as a
// way to tell transaction observers about changes performed by some
// external connection.
do {
try databaseWillCommit()
@@ -782,6 +801,16 @@ public protocol TransactionObserver: AnyObject {
/// from being applied on the observed tables.
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
/// Called when the database was modified in some unspecified way.
///
/// This method allows a transaction observer to handle changes that are
/// not automatically detected. See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes>
/// and ``Database/notifyChanges(in:)`` for more information.
///
/// The exact nature of changes is unknown, but they comply to the
/// ``observes(eventsOfKind:)`` test.
func databaseDidChange()
/// Called when the database is changed by an insert, update, or
/// delete event.
///
@@ -857,11 +886,15 @@ extension TransactionObserver {
public func databaseWillChange(with event: DatabasePreUpdateEvent) { }
#endif
/// Prevents the observer from receiving further change notifications until
/// the next transaction.
/// The default implementation does nothing.
public func databaseDidChange() { }
/// Prevents the observer from receiving further change notifications
/// until the next transaction.
///
/// After this method has been called, the ``databaseDidChange(with:)``
/// method won't be called until the next transaction.
/// and ``databaseDidChange()-7olv7`` methods won't be called until the
/// next transaction.
///
/// For example:
///
@@ -874,6 +907,13 @@ extension TransactionObserver {
/// return eventKind.tableName == "player"
/// }
///
/// func databaseDidChange() {
/// playerTableWasModified = true
///
/// // It is pointless to keep on tracking further changes:
/// stopObservingDatabaseChangesUntilNextTransaction()
/// }
///
/// func databaseDidChange(with event: DatabaseEvent) {
/// playerTableWasModified = true
///
@@ -884,12 +924,12 @@ extension TransactionObserver {
/// ```
///
/// - precondition: This method must be called from
/// ``databaseDidChange(with:)``.
/// ``databaseDidChange(with:)`` or ``databaseDidChange()-7olv7``.
public func stopObservingDatabaseChangesUntilNextTransaction() {
guard let broker = SchedulingWatchdog.current?.databaseObservationBroker else {
fatalError("""
stopObservingDatabaseChangesUntilNextTransaction must be called \
from the databaseDidChange method
from the `databaseDidChange()` or `databaseDidChange(with:)` methods
""")
}
broker.disableUntilNextTransaction(transactionObserver: self)
@@ -942,6 +982,11 @@ final class TransactionObservation {
}
#endif
func databaseDidChange() {
guard isEnabled else { return }
observer?.databaseDidChange()
}
func databaseDidChange(with event: DatabaseEvent) {
guard isEnabled else { return }
observer?.databaseDidChange(with: event)
@@ -1011,7 +1056,7 @@ struct StatementObservation {
/// See the ``TransactionObserver/observes(eventsOfKind:)`` method in the
/// ``TransactionObserver`` protocol for more information.
@frozen
public enum DatabaseEventKind {
public enum DatabaseEventKind: Sendable {
/// The insertion of a row in a database table.
case insert(tableName: String)
@@ -1064,7 +1109,7 @@ protocol DatabaseEventProtocol {
/// ``TransactionObserver`` protocol for more information.
public struct DatabaseEvent {
/// An event kind.
public enum Kind: CInt {
public enum Kind: CInt, Sendable {
/// An insertion event
case insert = 18 // SQLITE_INSERT
@@ -1128,6 +1173,11 @@ public struct DatabaseEvent {
}
}
// Explicit non-conformance to Sendable: this type can't be made Sendable
// until GRDB7 where we can distinguish between a transient event and its copy.
@available(*, unavailable)
extension DatabaseEvent: Sendable { }
extension DatabaseEvent: DatabaseEventProtocol {
func send(to observer: TransactionObservation) {
observer.databaseDidChange(with: self)
+3 -1
View File
@@ -21,7 +21,9 @@
/// Yes, this is an awfully complex logic.
///
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
final class WALSnapshot: Sendable {
final class WALSnapshot: @unchecked Sendable {
// @unchecked because sqlite3_snapshot has no threading requirements.
// <https://www.sqlite.org/c3ref/snapshot.html>
let sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>
init(_ db: Database) throws {
+3 -1
View File
@@ -46,7 +46,9 @@ class WALSnapshotTransaction {
// Open a long-lived transaction, and enter snapshot isolation
self.walSnapshot = try reader.sync(allowingLongLivedTransaction: true) { db in
try db.beginTransaction(.deferred)
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
// This also acquires snapshot isolation because checking
// database schema performs a read access.
try db.clearSchemaCacheIfNeeded()
return try WALSnapshot(db)
}
self.reader = reader
+9 -9
View File
@@ -391,17 +391,17 @@ extension Team: TableRecord {
### Querying the Database Schema
- ``Database/columns(in:)``
- ``Database/foreignKeys(on:)``
- ``Database/indexes(on:)``
- ``Database/columns(in:in:)``
- ``Database/foreignKeys(on:in:)``
- ``Database/indexes(on:in:)``
- ``Database/isGRDBInternalTable(_:)``
- ``Database/isSQLiteInternalTable(_:)``
- ``Database/primaryKey(_:)``
- ``Database/primaryKey(_:in:)``
- ``Database/schemaVersion()``
- ``Database/table(_:hasUniqueKey:)``
- ``Database/tableExists(_:)``
- ``Database/triggerExists(_:)``
- ``Database/viewExists(_:)``
- ``Database/tableExists(_:in:)``
- ``Database/triggerExists(_:in:)``
- ``Database/viewExists(_:in:)``
- ``ColumnInfo``
- ``ForeignKeyInfo``
- ``IndexInfo``
@@ -410,9 +410,9 @@ extension Team: TableRecord {
### Integrity Checks
- ``Database/checkForeignKeys()``
- ``Database/checkForeignKeys(in:)``
- ``Database/checkForeignKeys(in:in:)``
- ``Database/foreignKeyViolations()``
- ``Database/foreignKeyViolations(in:)``
- ``Database/foreignKeyViolations(in:in:)``
- ``ForeignKeyViolation``
### Sunsetted Methods
+7 -4
View File
@@ -152,11 +152,14 @@ If several processes want to write in the database, configure the database pool
```swift
var configuration = Configuration()
configuration.defaultTransactionKind = .immediate
configuration.busyMode = .timeout(/* a TimeInterval */)
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
With such a setup, you may still get `SQLITE_BUSY` errors from all write operations. They will occur if the database remains locked by another process for longer than the specified timeout. You can catch those errors:
Both the `defaultTransactionKind` and `busyMode` are important for preventing `SQLITE_BUSY`. The `immediate` transaction kind prevents write transactions from overlapping, and the busy timeout has write transactions wait, instead of throwing `SQLITE_BUSY`, whenever another process is writing.
With such a setup, you will still get `SQLITE_BUSY` errors if the database remains locked by another process for longer than the specified timeout. You can catch those errors:
```swift
do {
@@ -228,9 +231,7 @@ In applications that use the background modes supported by iOS, post `resumeNoti
<doc:DatabaseObservation> features are not able to detect database changes performed by other processes.
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter].
You can trigger those notifications automatically with ``DatabaseRegionObservation``:
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter]. You can trigger those notifications automatically with ``DatabaseRegionObservation``:
```swift
// Notify all changes made to the database
@@ -246,6 +247,8 @@ let observer = try observation.start(in: dbPool) { db in
}
```
The processes that observe the database can catch those notifications, and deal with the notified changes. See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes> for some related techniques.
[NSFileCoordinator]: https://developer.apple.com/documentation/foundation/nsfilecoordinator
[CFNotificationCenterGetDarwinNotifyCenter]: https://developer.apple.com/documentation/corefoundation/1542572-cfnotificationcentergetdarwinnot
[WAL mode]: https://www.sqlite.org/wal.html
@@ -88,6 +88,8 @@ A `DatabaseQueue` needs your application to follow rules in order to deliver its
- ``init(named:configuration:)``
- ``init(path:configuration:)``
- ``inMemoryCopy(fromPath:configuration:)``
- ``temporaryCopy(fromPath:configuration:)``
### Accessing the Database
@@ -6,11 +6,7 @@
`DatabaseRegionObservation` tracks insertions, updates, and deletions that impact the tracked region, whether performed with raw SQL, or <doc:QueryInterface>. This includes indirect changes triggered by [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
The only changes that are not notified are:
- Changes performed by external database connections.
- 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.
See <doc:GRDB/DatabaseRegionObservation#Dealing-with-Undetected-Changes> below for the list of exceptions.
`DatabaseRegionObservation` calls your application right after changes have been committed in the database, and before any other thread had any opportunity to perform further changes. *This is a pretty strong guarantee, that most applications do not really need.* Instead, most applications prefer to be notified with fresh values: make sure you check ``ValueObservation`` before using `DatabaseRegionObservation`.
@@ -78,6 +74,30 @@ let observation = DatabaseRegionObservation(
tracking: .fullDatabase)
```
## Dealing with Undetected Changes
`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 to the database schema, changes to internal system tables such as `sqlite_master`.
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
To have observations notify such undetected changes, applications can take explicit action: call the ``Database/notifyChanges(in:)`` `Database` method from a write transaction:
```swift
try dbQueue.write { db in
// Notify observations that some changes were performed in the database
try db.notifyChanges(in: .fullDatabase)
// Notify observations that some changes were performed in the player table
try db.notifyChanges(in: Player.all())
// Equivalent alternative
try db.notifyChanges(in: Table("player"))
}
```
## Topics
### Creating DatabaseRegionObservation
@@ -25,13 +25,7 @@ Database changes are notified to the ``databaseDidChange(with:)`` callback. This
Transaction completions are notified to the ``databaseWillCommit()-7mksu``, ``databaseDidCommit(_:)`` and ``databaseDidRollback(_:)`` callbacks.
The only changes and transactions that are not notified are:
- Read-only transactions.
- Changes and transactions performed by external database connections.
- 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).
> Important: Some changes and transactions are not automatically notified. See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes> below.
Notified changes are not actually written to disk until the transaction commits, and the `databaseDidCommit` callback is called. On the other side, `databaseDidRollback` confirms their invalidation:
@@ -189,7 +183,7 @@ class PlayerObserver: TransactionObserver {
}
```
### Support for SQLite Pre-Update Hooks
## Support for SQLite Pre-Update Hooks
When SQLite is built with the `SQLITE_ENABLE_PREUPDATE_HOOK` option, `TransactionObserver` gets an extra callback which lets you observe individual column values in the rows modified by a transaction:
@@ -235,6 +229,41 @@ This extra API can be activated in two ways:
2. Use a [custom SQLite build](http://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md) and activate the `SQLITE_ENABLE_PREUPDATE_HOOK` compilation option.
## Dealing with Undetected Changes
The changes and transactions that are not automatically notified to transaction observers are:
- 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 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).
To notify undetected changes to transaction observers, perform an explicit call to the ``Database/notifyChanges(in:)`` `Database` method. The ``databaseDidChange()-7olv7`` callback will be called accordingly. For example:
```swift
try dbQueue.write { db in
// Notify observers that some changes were performed in the database
try db.notifyChanges(in: .fullDatabase)
// Notify observers that some changes were performed in the player table
try db.notifyChanges(in: Player.all())
// Equivalent alternative
try db.notifyChanges(in: Table("player"))
}
```
To notify a change in the database schema, notify a change to the `sqlite_master` table:
```swift
try dbQueue.write { db in
// Notify all observers of the sqlite_master table
try db.notifyChanges(in: Table("sqlite_master"))
}
```
## Topics
### Filtering Database Changes
@@ -244,6 +273,7 @@ This extra API can be activated in two ways:
### Handling Database Changes
- ``databaseDidChange()-7olv7``
- ``databaseDidChange(with:)``
- ``stopObservingDatabaseChangesUntilNextTransaction()``
- ``DatabaseEvent``
@@ -6,11 +6,7 @@
`ValueObservation` tracks insertions, updates, and deletions that impact the tracked value, whether performed with raw SQL, or <doc:QueryInterface>. This includes indirect changes triggered by [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
The only changes that are not notified are:
- Changes performed by external database connections. See <doc:DatabaseSharing#How-to-perform-cross-process-database-observation> for more information.
- 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.
See <doc:GRDB/ValueObservation#Dealing-with-Undetected-Changes> below for the list of exceptions.
## ValueObservation Usage
@@ -84,6 +80,8 @@ By default, `ValueObservation` notifies a fresh value whenever any component of
By default, `ValueObservation` notifies the initial value, as well as eventual changes and errors, on the main dispatch queue, asynchronously. This can be configured: see <doc:ValueObservation#ValueObservation-Scheduling>.
By default, `ValueObservation` fetches a fresh value immediately after a change is committed in the database. In particular, modifying the database on the main thread triggers a fetch on the main thread as well. This behavior can be configured: see <doc:ValueObservation#ValueObservation-Scheduling>.
`ValueObservation` may coalesce subsequent changes into a single notification.
`ValueObservation` may notify consecutive identical values. You can filter out the undesired duplicates with the ``removeDuplicates()`` method.
@@ -121,16 +119,45 @@ It is very useful in graphic applications, because you can configure views right
The `immediate` scheduling requires that the observation starts from the main dispatch queue (a fatal error is raised otherwise):
```swift
let cancellable = observation.start(in: dbQueue, scheduling: .immediate) { error in
// Called on the main dispatch queue
} onChange: { value in
// Called on the main dispatch queue
print("Fresh value", value)
}
// Immediate scheduling notifies
// the initial value right on subscription.
let cancellable = observation
.start(in: dbQueue, scheduling: .immediate) { error in
// Called on the main dispatch queue
} onChange: { value in
// Called on the main dispatch queue
print("Fresh value", value)
}
// <- Here "Fresh value" has already been printed.
```
The other built-in scheduler ``ValueObservationScheduler/async(onQueue:)`` asynchronously schedules values and errors on the dispatch queue of your choice.
The other built-in scheduler ``ValueObservationScheduler/async(onQueue:)`` asynchronously schedules values and errors on the dispatch queue of your choice. Make sure you provide a serial queue, because a concurrent one such as `DispachQueue.global(qos: .default)` would mess with the ordering of fresh value notifications:
```swift
// Async scheduling notifies all values
// on the specified dispatch queue.
let myQueue: DispatchQueue
let cancellable = observation
.start(in: dbQueue, scheduling: .async(myQueue)) { error in
// Called asynchronously on myQueue
} onChange: { value in
// Called asynchronously on myQueue
print("Fresh value", value)
}
```
As described above, the `scheduling` argument controls the execution of the change and error callbacks. You also have some control on the execution of the database fetch:
- With the `.immediate` scheduling, the initial fetch is always performed synchronously, on the main thread, when the observation starts, so that the initial value can be notified immediately.
- With the default `.async` scheduling, the initial fetch is always performed asynchronouly. It never blocks the main thread.
- By default, fresh values are fetched immediately after the database was changed. In particular, modifying the database on the main thread triggers a fetch on the main thread as well.
To change this behavior, and guarantee that fresh values are never fetched from the main thread, you need a ``DatabasePool`` and an optimized observation created with the ``tracking(regions:fetch:)`` or ``trackingConstantRegion(_:)`` methods. Make sure you read the documentation of those methods, or you might write an observation that misses some database changes.
It is possible to use a ``DatabasePool`` in the application, and an in-memory ``DatabaseQueue`` in tests and Xcode previews, with the common protocol ``DatabaseWriter``.
## ValueObservation Sharing
@@ -174,6 +201,30 @@ let observation = ValueObservation.tracking(
This ``tracking(region:_:fetch:)`` method lets you entirely separate the **observed region(s)** from the **fetched value** itself, for maximum flexibility. See ``DatabaseRegionConvertible`` for more information about the regions that can be tracked.
## Dealing with Undetected Changes
`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 to the database schema, changes to internal system tables such as `sqlite_master`.
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
To have observations notify a fresh values after such an undetected change was performed, applications can take explicit action. For example, cancel and restart observations. Alternatively, call the ``Database/notifyChanges(in:)`` `Database` method from a write transaction:
```swift
try dbQueue.write { db in
// Notify observations that some changes were performed in the database
try db.notifyChanges(in: .fullDatabase)
// Notify observations that some changes were performed in the player table
try db.notifyChanges(in: Player.all())
// Equivalent alternative
try db.notifyChanges(in: Table("player"))
}
```
## ValueObservation Performance
This section further describes runtime aspects of `ValueObservation`, and provides some optimization tips for demanding applications.
@@ -217,7 +268,7 @@ When needed, you can help GRDB optimize observations and reduce database content
>
> The `map` operator performs its job without blocking database accesses, and without blocking the main thread.
> Tip: When the observation tracks a constant database region, create an optimized observation with the ``trackingConstantRegion(_:)`` method. See the documentation of this method for more information about what constitutes a "constant region", and the nature of the optimization.
> Tip: When the observation tracks a constant database region, create an optimized observation with the ``tracking(regions:fetch:)`` or ``trackingConstantRegion(_:)`` methods. Make sure you read the documentation of those methods, or you might write an observation that misses some database changes.
**Truncating WAL checkpoints impact ValueObservation.** Such checkpoints are performed with ``Database/checkpoint(_:on:)`` or [`PRAGMA wal_checkpoint`](https://www.sqlite.org/pragma.html#pragma_wal_checkpoint). When an observation is started on a ``DatabasePool``, from a database that has a missing or empty [wal file](https://www.sqlite.org/tempfiles.html#write_ahead_log_wal_files), the observation will always notify two values when it starts, even if the database content is not changed. This is a consequence of the impossibility to create the [wal snapshot](https://www.sqlite.org/c3ref/snapshot_get.html) needed for detecting that no changes were performed during the observation startup. If your application performs truncating checkpoints, you will avoid this behavior if you recreate a non-empty wal file before starting observations. To do so, perform any kind of no-op transaction (such a creating and dropping a dummy table).
+2 -3
View File
@@ -133,8 +133,8 @@ The `->` and `->>` SQL operators are available on the ``SQLJSONExpressible`` pro
- ``Database/jsonArray(_:)-469db``
- ``Database/jsonObject(_:)``
- ``Database/jsonQuote(_:)``
- ``Database/jsonGroupArray(_:)``
- ``Database/jsonGroupObject(key:value:)``
- ``Database/jsonGroupArray(_:filter:)``
- ``Database/jsonGroupObject(key:value:filter:)``
### Modify JSON values at the SQL level
@@ -147,5 +147,4 @@ The `->` and `->>` SQL operators are available on the ``SQLJSONExpressible`` pro
### Validate JSON values at the SQL level
- ``Database/jsonErrorPosition(_:)``
- ``Database/jsonIsValid(_:)``
+1 -1
View File
@@ -233,7 +233,7 @@ To prevent a migration from committing foreign key violations on disk, you can:
}
```
As in the above example, check for foreign key violations with the ``Database/checkForeignKeys()`` and ``Database/checkForeignKeys(in:)`` methods. They throw a nicely detailed ``DatabaseError`` that contains a lot of debugging information:
As in the above example, check for foreign key violations with the ``Database/checkForeignKeys()`` and ``Database/checkForeignKeys(in:in:)`` methods. They throw a nicely detailed ``DatabaseError`` that contains a lot of debugging information:
```swift
// SQLite error 19: FOREIGN KEY constraint violation - from book(authorId) to author(id),
+97 -69
View File
@@ -8,9 +8,11 @@ Database tables that contain a single row can store configuration values, user p
They are a suitable alternative to `UserDefaults` in some applications, especially when configuration refers to values found in other database tables, and database integrity is a concern.
An alternative way to store such configuration is a table of key-value pairs: two columns, and one row for each configuration value. This technique works, but it has a few drawbacks: you will have to deal with the various types of configuration values (strings, integers, dates, etc), and you won't be able to define foreign keys. This is why we won't explore key-value tables.
A possible way to store such configuration is a table of key-value pairs: two columns, and one row for each configuration value. This technique works, but it has a few drawbacks: one has to deal with the various types of configuration values (strings, integers, dates, etc), and it is not possible to define foreign keys. This is why we won't explore key-value tables.
This guide helps implementing a single-row table with GRDB, with recommendations on the database schema, migrations, and the design of a matching record type.
In this guide, we'll implement a single-row table, with recommendations on the database schema, migrations, and the design of a Swift API for accessing the configuration values. The schema will define one column for each configuration value, because we aim at being able to deal with foreign keys and references to other tables. You may prefer storing configuration values in a single JSON column. In this case, take inspiration from this guide, as well as <doc:JSON>.
We will also aim at providing a default value for a given configuration, even when it is not stored on disk yet. This is a feature similar to [`UserDefaults.register(defaults:)`](https://developer.apple.com/documentation/foundation/userdefaults/1417065-register).
## The Single-Row Table
@@ -20,67 +22,47 @@ We want to instruct SQLite that our table must never contain more than one row.
SQLite is not able to guarantee that the table is never empty, so we have to deal with two cases: either the table is empty, or it contains one row.
Those two cases can create a nagging question for the application. By default, inserts fail when the row already exists, and updates fail when the table is empty. In order to avoid those errors, we will have the app deal with updates in the <doc:SingleRowTables#The-Single-Row-Record> section below. Right now, we instruct SQLite to just replace the eventual existing row in case of conflicting inserts:
Those two cases can create a nagging question for the application. By default, inserts fail when the row already exists, and updates fail when the table is empty. In order to avoid those errors, we will have the app deal with updates in the <doc:SingleRowTables#The-Single-Row-Record> section below. Right now, we instruct SQLite to just replace the eventual existing row in case of conflicting inserts.
```swift
// CREATE TABLE appConfiguration (
// id INTEGER PRIMARY KEY ON CONFLICT REPLACE CHECK (id = 1),
// flag BOOLEAN NOT NULL,
// ...)
try db.create(table: "appConfiguration") { t in
// Single row guarantee: have inserts replace the existing row
t.primaryKey("id", .integer, onConflict: .replace)
// Make sure the id column is always 1
.check { $0 == 1 }
// The configuration columns
t.column("flag", .boolean).notNull()
// ... other columns
}
```
When you use <doc:Migrations>, you may wonder if it is a good idea or not to perform an initial insert just after the table is created. Well, this is not recommended:
```swift
// NOT RECOMMENDED
migrator.registerMigration("appConfiguration") { db in
// CREATE TABLE appConfiguration (
// id INTEGER PRIMARY KEY ON CONFLICT REPLACE CHECK (id = 1),
// storedFlag BOOLEAN,
// ...)
try db.create(table: "appConfiguration") { t in
// The single row guarantee
t.primaryKey("id", .integer, onConflict: .replace).check { $0 == 1 }
// Define sensible defaults for each column
t.column("flag", .boolean).notNull()
.defaults(to: false)
// ... other columns
}
// Populate the table
try db.execute(sql: "INSERT INTO appConfiguration DEFAULT VALUES")
}
```
It is not a good idea to populate the table in a migration, for two reasons:
1. This migration is not a hard guarantee that the table will never be empty. As a consequence, this won't prevent the application code from dealing with the possibility of a missing row. On top of that, this application code may not use the same default values as the SQLite schema, with unclear consequences.
2. Migrations that have been deployed on the users' devices should never change (see <doc:Migrations#Good-Practices-for-Defining-Migrations>). Inserting an initial row in a migration makes it difficult for the application to adjust the sensible default values in a future version.
The recommended migration creates the table, nothing more:
```swift
// RECOMMENDED
migrator.registerMigration("appConfiguration") { db in
try db.create(table: "appConfiguration") { t in
// The single row guarantee
t.primaryKey("id", .integer, onConflict: .replace).check { $0 == 1 }
// Single row guarantee: have inserts replace the existing row,
// and make sure the id column is always 1.
t.primaryKey("id", .integer, onConflict: .replace)
.check { $0 == 1 }
// The configuration columns
t.column("flag", .boolean).notNull()
t.column("storedFlag", .boolean)
// ... other columns
}
}
```
Note how the database table is defined in a migration. That's because most apps evolve, and need to add other configuration columns eventually. See <doc:Migrations> for more information.
We have defined a `storedFlag` column that can be NULL. That may be surprising, because optional booleans are usually a bad idea! But we can deal with this NULL at runtime, and nullable columns have a few advantages:
- NULL means that the application user had not made a choice yet. When `storedFlag` is NULL, the app can use a default value, such as `true`.
- As application evolves, application will need to add new configuration columns. It is not always possible to provide a sensible default value for these new columns, at the moment the table is modified. On the other side, it is generally possible to deal with those NULL values at runtime.
Despite those arguments, some apps absolutely require a value. In this case, don't weaken the application logic and make sure the database can't store a NULL value:
```swift
// DO NOT hesitate requiring NOT NULL columns when the app requires it.
migrator.registerMigration("appConfiguration") { db in
try db.create(table: "appConfiguration") { t in
t.primaryKey("id", .integer, onConflict: .replace).check { $0 == 1 }
t.column("flag", .boolean).notNull() // required
}
}
```
## The Single-Row Record
@@ -91,7 +73,37 @@ struct AppConfiguration: Codable {
// Support for the single row guarantee
private var id = 1
// The configuration properties
// The stored properties
private var storedFlag: Bool?
// ... other properties
}
```
The `storedFlag` property is private, because we want to expose a nice `flag` property that has a default value when `storedFlag` is nil:
```swift
// Support for default values
extension AppConfiguration {
var flag: Bool {
get { storedFlag ?? true /* the default value */ }
set { storedFlag = newValue }
}
mutating func resetFlag() {
storedFlag = nil
}
}
```
This ceremony is not needed when the column can not be null:
```swift
// The simplified setup for non-nullable columns
struct AppConfiguration: Codable {
// Support for the single row guarantee
private var id = 1
// The stored properties
var flag: Bool
// ... other properties
}
@@ -102,7 +114,7 @@ In case the database table would be empty, we need a default configuration:
```swift
extension AppConfiguration {
/// The default configuration
static let `default` = AppConfiguration(flag: false)
static let `default` = AppConfiguration(flag: nil)
}
```
@@ -129,7 +141,7 @@ The standard GRDB method ``FetchableRecord/fetchOne(_:)`` returns an optional wh
```swift
/// Returns the persisted configuration, or the default one if the
/// database table is empty.
static func fetch(_ db: Database) throws -> AppConfiguration {
static func find(_ db: Database) throws -> AppConfiguration {
try fetchOne(db) ?? .default
}
}
@@ -140,7 +152,7 @@ And that's it! Now we can use our singleton record:
```swift
// READ
let config = try dbQueue.read { db in
try AppConfiguration.fetch(db)
try AppConfiguration.find(db)
}
if config.flag {
// ...
@@ -148,17 +160,19 @@ if config.flag {
// WRITE
try dbQueue.write { db in
// Saves a new config in the database
var config = try AppConfiguration.fetch(db)
// Update the config in the database
var config = try AppConfiguration.find(db)
try config.updateChanges(db) {
$0.flag = true
}
// Other possible ways to save the config:
try config.save(db)
try config.update(db)
try config.insert(db)
try config.upsert(db)
var config = try AppConfiguration.find(db)
config.flag = true
try config.save(db) // all the same
try config.update(db) // all the same
try config.insert(db) // all the same
try config.upsert(db) // all the same
}
```
@@ -172,11 +186,13 @@ We all love to copy and paste, don't we? Just customize the template code below:
```swift
// Table creation
try db.create(table: "appConfiguration") { t in
// The single row guarantee
t.primaryKey("id", .integer, onConflict: .replace).check { $0 == 1 }
// Single row guarantee: have inserts replace the existing row,
// and make sure the id column is always 1.
t.primaryKey("id", .integer, onConflict: .replace)
.check { $0 == 1 }
// The configuration columns
t.column("flag", .boolean).notNull()
t.column("storedFlag", .boolean)
// ... other columns
}
```
@@ -192,14 +208,26 @@ struct AppConfiguration: Codable {
// Support for the single row guarantee
private var id = 1
// The configuration properties
var flag: Bool
// The stored properties
private var storedFlag: Bool?
// ... other properties
}
// Support for default values
extension AppConfiguration {
var flag: Bool {
get { storedFlag ?? true /* the default value */ }
set { storedFlag = newValue }
}
mutating func resetFlag() {
storedFlag = nil
}
}
extension AppConfiguration {
/// The default configuration
static let `default` = AppConfiguration(flag: false, ...)
static let `default` = AppConfiguration(storedFlag: nil)
}
// Database Access
@@ -214,7 +242,7 @@ extension AppConfiguration: FetchableRecord, PersistableRecord {
/// Returns the persisted configuration, or the default one if the
/// database table is empty.
static func fetch(_ db: Database) throws -> AppConfiguration {
static func find(_ db: Database) throws -> AppConfiguration {
try fetchOne(db) ?? .default
}
}
+120 -23
View File
@@ -12,7 +12,7 @@ extension Database {
/// // Prints
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// db.dumpSQL("SELECT * FROM player ORDER BY id")
/// try db.dumpSQL("SELECT * FROM player ORDER BY id")
/// }
/// ```
///
@@ -40,7 +40,7 @@ extension Database {
/// // Prints
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// db.dumpRequest(Player.orderByPrimaryKey())
/// try db.dumpRequest(Player.orderByPrimaryKey())
/// }
/// ```
///
@@ -59,7 +59,7 @@ extension Database {
try _dumpRequest(request, format: format, to: &dumpStream)
}
/// Prints the contents of the provided tables.
/// Prints the contents of the provided tables and views.
///
/// For example:
///
@@ -72,7 +72,7 @@ extension Database {
/// // team
/// // 1|Red
/// // 2|Blue
/// db.dumpTables(["player", "team"])
/// try db.dumpTables(["player", "team"])
/// }
/// ```
///
@@ -80,17 +80,29 @@ extension Database {
/// - tables: The table names.
/// - format: The output format.
/// - tableHeader: Options for printing table names.
/// - stableOrder: A boolean value that controls the ordering of
/// rows fetched from views. If false (the default), rows are
/// printed in the order specified by the view (which may be
/// undefined). It true, outputted rows are always printed in the
/// same stable order. The purpose of this stable order is to make
/// the output suitable for testing.
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpTables(
_ tables: [String],
format: some DumpFormat = .debug(),
tableHeader: DumpTableHeaderOptions = .automatic,
stableOrder: Bool = false,
to stream: (any TextOutputStream)? = nil)
throws
{
var dumpStream = DumpStream(stream)
try _dumpTables(tables, format: format, tableHeader: tableHeader, to: &dumpStream)
try _dumpTables(
tables,
format: format,
tableHeader: tableHeader,
stableOrder: stableOrder,
to: &dumpStream)
}
/// Prints the contents of the database.
@@ -99,7 +111,7 @@ extension Database {
///
/// ```swift
/// try dbQueue.read { db in
/// db.dumpContent()
/// try db.dumpContent()
/// }
/// ```
///
@@ -117,6 +129,9 @@ extension Database {
///
/// > Note: Internal SQLite and GRDB schema objects are not recorded
/// > (those with a name that starts with "sqlite_" or "grdb_").
/// >
/// > [Shadow tables](https://www.sqlite.org/vtab.html#xshadowname) are
/// > not recorded, starting SQLite 3.37+.
///
/// - Parameters:
/// - format: The output format.
@@ -130,6 +145,40 @@ extension Database {
var dumpStream = DumpStream(stream)
try _dumpContent(format: format, to: &dumpStream)
}
/// Prints the schema of the database.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// try db.dumpSchema()
/// }
/// ```
///
/// This prints the database schema. For example:
///
/// ```
/// sqlite_master
/// CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)
/// ```
///
/// > Note: Internal SQLite and GRDB schema objects are not recorded
/// > (those with a name that starts with "sqlite_" or "grdb_").
/// >
/// > [Shadow tables](https://www.sqlite.org/vtab.html#xshadowname) are
/// > not recorded, starting SQLite 3.37+.
///
/// - Parameters:
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpSchema(
to stream: (any TextOutputStream)? = nil)
throws
{
var dumpStream = DumpStream(stream)
try _dumpSchema(to: &dumpStream)
}
}
// MARK: -
@@ -186,7 +235,8 @@ extension Database {
func _dumpTables(
_ tables: [String],
format: some DumpFormat,
tableHeader: DumpTableHeaderOptions = .automatic,
tableHeader: DumpTableHeaderOptions,
stableOrder: Bool,
to stream: inout DumpStream)
throws
{
@@ -203,10 +253,21 @@ extension Database {
} else {
stream.write("\n")
}
if header {
stream.writeln(table)
}
try _dumpRequest(Table(table).orderByPrimaryKey(), format: format, to: &stream)
if try tableExists(table) {
// Always sort tables by primary key
try _dumpRequest(Table(table).orderByPrimaryKey(), format: format, to: &stream)
} else if stableOrder {
// View with stable order
try _dumpRequest(Table(table).all().withStableOrder(), format: format, to: &stream)
} else {
// Use view ordering, if any (no guarantee of stable order).
try _dumpRequest(Table(table).all(), format: format, to: &stream)
}
}
}
@@ -214,6 +275,26 @@ extension Database {
format: some DumpFormat,
to stream: inout DumpStream)
throws
{
try _dumpSchema(to: &stream)
stream.margin()
let tables = try String
.fetchAll(self, sql: """
SELECT name
FROM sqlite_master
WHERE type = 'table'
ORDER BY name COLLATE NOCASE
""")
.filter {
try !ignoresObject(named: $0)
}
try _dumpTables(tables, format: format, tableHeader: .always, stableOrder: true, to: &stream)
}
func _dumpSchema(
to stream: inout DumpStream)
throws
{
stream.writeln("sqlite_master")
let sqlRows = try Row.fetchAll(self, sql: """
@@ -228,30 +309,46 @@ extension Database {
""")
for row in sqlRows {
let name: String = row[1]
if Database.isSQLiteInternalTable(name) || Database.isGRDBInternalTable(name) {
if try ignoresObject(named: name) {
continue
}
stream.writeln(row[0])
}
let tables = try String
.fetchAll(self, sql: """
SELECT name
FROM sqlite_master
WHERE type = 'table'
ORDER BY name COLLATE NOCASE
""")
.filter {
!(Database.isSQLiteInternalTable($0) || Database.isGRDBInternalTable($0))
}
private func ignoresObject(named name: String) throws -> Bool {
if Database.isSQLiteInternalTable(name) { return true }
if Database.isGRDBInternalTable(name) { return true }
if try isShadowTable(name) { return true }
return false
}
private func isShadowTable(_ tableName: String) throws -> Bool {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// Maybe SQLCipher is too old: check actual version
if sqlite3_libversion_number() >= 3037000 {
guard let table = try table(tableName) else {
// Not a table
return false
}
if tables.isEmpty { return }
stream.write("\n")
try _dumpTables(tables, format: format, tableHeader: .always, to: &stream)
return table.kind == .shadow
}
#else
if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) { // SQLite 3.37+
guard let table = try table(tableName) else {
// Not a table
return false
}
return table.kind == .shadow
}
#endif
// Don't know
return false
}
}
/// Options for printing table names.
public enum DumpTableHeaderOptions {
public enum DumpTableHeaderOptions: Sendable {
/// Table names are only printed when several tables are printed.
case automatic
+54 -6
View File
@@ -7,7 +7,7 @@ extension DatabaseReader {
/// // Prints
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// dbQueue.dumpSQL("SELECT * FROM player ORDER BY id")
/// try dbQueue.dumpSQL("SELECT * FROM player ORDER BY id")
/// ```
///
/// - Parameters:
@@ -34,7 +34,7 @@ extension DatabaseReader {
/// // Prints
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// dbQueue.dumpRequest(Player.orderByPrimaryKey())
/// try dbQueue.dumpRequest(Player.orderByPrimaryKey())
/// ```
///
/// - Parameters:
@@ -53,7 +53,7 @@ extension DatabaseReader {
}
}
/// Prints the contents of the provided tables.
/// Prints the contents of the provided tables and views.
///
/// For example:
///
@@ -65,24 +65,36 @@ extension DatabaseReader {
/// // team
/// // 1|Red
/// // 2|Blue
/// dbQueue.dumpTables(["player", "team"])
/// try dbQueue.dumpTables(["player", "team"])
/// ```
///
/// - Parameters:
/// - tables: The table names.
/// - format: The output format.
/// - tableHeader: Options for printing table names.
/// - stableOrder: A boolean value that controls the ordering of
/// rows fetched from views. If false (the default), rows are
/// printed in the order specified by the view (which may be
/// undefined). It true, outputted rows are always printed in the
/// same stable order. The purpose of this stable order is to make
/// the output suitable for testing.
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpTables(
_ tables: [String],
format: some DumpFormat = .debug(),
tableHeader: DumpTableHeaderOptions = .automatic,
stableOrder: Bool = false,
to stream: (any TextOutputStream)? = nil)
throws
{
try unsafeReentrantRead { db in
try db.dumpTables(tables, format: format, tableHeader: tableHeader, to: stream)
try db.dumpTables(
tables,
format: format,
tableHeader: tableHeader,
stableOrder: stableOrder,
to: stream)
}
}
@@ -91,7 +103,7 @@ extension DatabaseReader {
/// For example:
///
/// ```swift
/// dbQueue.dumpContent()
/// try dbQueue.dumpContent()
/// ```
///
/// This prints the database schema as well as the content of all
@@ -108,6 +120,9 @@ extension DatabaseReader {
///
/// > Note: Internal SQLite and GRDB schema objects are not recorded
/// > (those with a name that starts with "sqlite_" or "grdb_").
/// >
/// > [Shadow tables](https://www.sqlite.org/vtab.html#xshadowname) are
/// > not recorded, starting SQLite 3.37+.
///
/// - Parameters:
/// - format: The output format.
@@ -122,4 +137,37 @@ extension DatabaseReader {
try db.dumpContent(format: format, to: stream)
}
}
/// Prints the schema of the database.
///
/// For example:
///
/// ```swift
/// try dbQueue.dumpSchema()
/// ```
///
/// This prints the database schema. For example:
///
/// ```
/// sqlite_master
/// CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)
/// ```
///
/// > Note: Internal SQLite and GRDB schema objects are not recorded
/// > (those with a name that starts with "sqlite_" or "grdb_").
/// >
/// > [Shadow tables](https://www.sqlite.org/vtab.html#xshadowname) are
/// > not recorded, starting SQLite 3.37+.
///
/// - Parameters:
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpSchema(
to stream: (any TextOutputStream)? = nil)
throws
{
try unsafeReentrantRead { db in
try db.dumpSchema(to: stream)
}
}
}
+1 -1
View File
@@ -17,7 +17,7 @@ import Foundation
/// // Craig|200
/// try db.dumpRequest(Player.all(), format: .debug())
/// ```
public struct DebugDumpFormat {
public struct DebugDumpFormat: Sendable {
/// A boolean value indicating if column labels are printed as the first
/// line of output.
public var header: Bool
+1 -1
View File
@@ -27,7 +27,7 @@ import Foundation
/// encoder.outputFormatting = .prettyPrinted
/// try db.dumpRequest(Player.all(), format: .json(encoder))
/// ```
public struct JSONDumpFormat {
public struct JSONDumpFormat: Sendable {
/// The default `JSONEncoder` for database values.
///
/// It is configured so that blob values (`Data`) are encoded in the
+1 -1
View File
@@ -13,7 +13,7 @@ import Foundation
/// // score = 1000
/// try db.dumpRequest(Player.all(), format: .line())
/// ```
public struct LineDumpFormat {
public struct LineDumpFormat: Sendable {
/// The string to print for NULL values.
public var nullValue: String
+1 -1
View File
@@ -14,7 +14,7 @@ import Foundation
/// // Craig|200
/// try db.dumpRequest(Player.all(), format: .list())
/// ```
public struct ListDumpFormat {
public struct ListDumpFormat: Sendable {
/// A boolean value indicating if column labels are printed as the first
/// line of output.
public var header: Bool
+1 -1
View File
@@ -9,7 +9,7 @@
/// // 'Craig',200
/// try db.dumpRequest(Player.all(), format: .quote())
/// ```
public struct QuoteDumpFormat {
public struct QuoteDumpFormat: Sendable {
/// A boolean value indicating if column labels are printed as the first
/// line of output.
public var header: Bool
+6 -1
View File
@@ -29,7 +29,7 @@
/// - ``tokenize(_:withTokenizer:)``
public struct FTS3 {
/// Options for Latin script characters.
public enum Diacritics {
public enum Diacritics: Sendable {
/// Do not remove diacritics from Latin script characters. This option
/// matches the `remove_diacritics=0` tokenizer argument.
///
@@ -183,3 +183,8 @@ public final class FTS3TableDefinition {
columns.append(name)
}
}
// Explicit non-conformance to Sendable: `FTS3TableDefinition` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension FTS3TableDefinition: Sendable { }
+1 -1
View File
@@ -16,7 +16,7 @@
/// - ``init(matchingAllTokensIn:)``
/// - ``init(matchingAnyTokenIn:)``
/// - ``init(matchingPhrase:)``
public struct FTS3Pattern {
public struct FTS3Pattern: Sendable {
/// The raw pattern string.
///
/// It is guaranteed to be a valid FTS3/4 pattern.
+1 -1
View File
@@ -20,7 +20,7 @@
/// - ``simple``
/// - ``unicode61(diacritics:separators:tokenCharacters:)``
/// - ``FTS3/Diacritics``
public struct FTS3TokenizerDescriptor {
public struct FTS3TokenizerDescriptor: Sendable {
let name: String
let arguments: [String]
+10
View File
@@ -313,6 +313,11 @@ public final class FTS4TableDefinition {
}
}
// Explicit non-conformance to Sendable: `FTS4TableDefinition` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension FTS4TableDefinition: Sendable { }
/// Describes a column in an ``FTS4`` virtual table.
///
/// You get instances of `FTS4ColumnDefinition` when you create an ``FTS4``
@@ -377,6 +382,11 @@ public final class FTS4ColumnDefinition {
}
}
// Explicit non-conformance to Sendable: `FTS4ColumnDefinition` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension FTS4ColumnDefinition: Sendable { }
extension Database {
/// Deletes the synchronization triggers for a synchronized FTS4 table.
///
+11 -1
View File
@@ -44,7 +44,7 @@ public struct FTS5 {
/// tokenizer argument.
///
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#unicode61_tokenizer>
public enum Diacritics {
public enum Diacritics: Sendable {
/// Do not remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=0" tokenizer argument.
case keep
@@ -492,6 +492,11 @@ public final class FTS5TableDefinition {
}
}
// Explicit non-conformance to Sendable: `FTS5TableDefinition` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension FTS5TableDefinition: Sendable { }
/// Describes a column in an ``FTS5`` virtual table.
///
/// You get instances of `FTS5ColumnDefinition` when you create an ``FTS5``
@@ -534,6 +539,11 @@ public final class FTS5ColumnDefinition {
}
}
// Explicit non-conformance to Sendable: `FTS5ColumnDefinition` is a mutable
// class and there is no known reason for making it thread-safe.
@available(*, unavailable)
extension FTS5ColumnDefinition: Sendable { }
extension Column {
/// The ``FTS5`` rank column.
public static let rank = Column("rank")
+1 -1
View File
@@ -16,7 +16,7 @@
/// - ``init(matchingAnyTokenIn:)``
/// - ``init(matchingPhrase:)``
/// - ``init(matchingPrefixPhrase:)``
public struct FTS5Pattern {
public struct FTS5Pattern: Sendable {
/// The raw pattern string.
///
+1 -1
View File
@@ -16,7 +16,7 @@ public typealias FTS5TokenCallback = @convention(c) (
/// The reason why FTS5 is requesting tokenization.
///
/// See the `FTS5_TOKENIZE_*` constants in <https://www.sqlite.org/fts5.html#custom_tokenizers>.
public struct FTS5Tokenization: OptionSet {
public struct FTS5Tokenization: OptionSet, Sendable {
public let rawValue: CInt
public init(rawValue: CInt) {
+1 -1
View File
@@ -24,7 +24,7 @@
/// ### Instantiating Tokenizers
///
/// - ``Database/makeTokenizer(_:)``
public struct FTS5TokenizerDescriptor {
public struct FTS5TokenizerDescriptor: Sendable {
/// The tokenizer components.
///
/// For example:
+1 -1
View File
@@ -4,7 +4,7 @@ import Foundation
/// Flags that tell SQLite how to register a token.
///
/// See the `FTS5_TOKEN_*` constants in <https://www.sqlite.org/fts5.html#custom_tokenizers>.
public struct FTS5TokenFlags: OptionSet {
public struct FTS5TokenFlags: OptionSet, Sendable {
public let rawValue: CInt
public init(rawValue: CInt) {
+1 -1
View File
@@ -73,7 +73,7 @@
/// > .fetchAll(db)
/// > }
/// > ```
public struct JSONColumn: ColumnExpression, SQLJSONExpressible {
public struct JSONColumn: ColumnExpression, SQLJSONExpressible, Sendable {
public var name: String
/// Creates a `JSONColumn` given its name.
+93 -23
View File
@@ -373,16 +373,61 @@ extension Database {
/// The `JSON_GROUP_ARRAY` SQL function.
///
/// For example:
///
/// ```swift
/// // SELECT JSON_GROUP_ARRAY(name) FROM player
/// Player.select(Database.jsonGroupArray(Column("name")))
///
/// // SELECT JSON_GROUP_ARRAY(name) FILTER (WHERE score > 0) FROM player
/// Player.select(Database.jsonGroupArray(Column("name"), filter: Column("score") > 0))
///
/// // SELECT JSON_GROUP_ARRAY(name ORDER BY name) FROM player
/// Player.select(Database.jsonGroupArray(Column("name"), orderBy: Column("name")))
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
public static func jsonGroupArray(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_GROUP_ARRAY", [value.sqlExpression.jsonBuilderExpression])
public static func jsonGroupArray(
_ value: some SQLExpressible,
orderBy ordering: (any SQLOrderingTerm)? = nil,
filter: (any SQLSpecificExpressible)? = nil)
-> SQLExpression {
.aggregateFunction(
"JSON_GROUP_ARRAY",
[value.sqlExpression.jsonBuilderExpression],
ordering: ordering?.sqlOrdering,
filter: filter?.sqlExpression,
isJSONValue: true)
}
/// The `JSON_GROUP_OBJECT` SQL function.
///
/// For example:
///
/// ```swift
/// // SELECT JSON_GROUP_OBJECT(name, score) FROM player
/// Player.select(Database.jsonGroupObject(
/// key: Column("name"),
/// value: Column("score")))
///
/// // SELECT JSON_GROUP_OBJECT(name, score) FILTER (WHERE score > 0) FROM player
/// Player.select(Database.jsonGroupObject(
/// key: Column("name"),
/// value: Column("score"),
/// filter: Column("score") > 0))
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
public static func jsonGroupObject(key: some SQLExpressible, value: some SQLExpressible) -> SQLExpression {
.function("JSON_GROUP_OBJECT", [key.sqlExpression, value.sqlExpression.jsonBuilderExpression])
public static func jsonGroupObject(
key: some SQLExpressible,
value: some SQLExpressible,
filter: (any SQLSpecificExpressible)? = nil
) -> SQLExpression {
.aggregateFunction(
"JSON_GROUP_OBJECT",
[key.sqlExpression, value.sqlExpression.jsonBuilderExpression],
filter: filter?.sqlExpression,
isJSONValue: true)
}
}
#else
@@ -476,21 +521,6 @@ extension Database {
.function("JSON_ARRAY_LENGTH", [value.sqlExpression, path.sqlExpression])
}
/// The `JSON_ERROR_POSITION` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ERROR_POSITION(info)
/// Database.jsonErrorPosition(Column("info"))
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jerr>
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func jsonErrorPosition(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_ERROR_POSITION", [value.sqlExpression])
}
/// The `JSON_EXTRACT` SQL function.
///
/// For example:
@@ -779,18 +809,58 @@ extension Database {
/// The `JSON_GROUP_ARRAY` SQL function.
///
/// For example:
///
/// ```swift
/// // SELECT JSON_GROUP_ARRAY(name) FROM player
/// Player.select(Database.jsonGroupArray(Column("name")))
///
/// // SELECT JSON_GROUP_ARRAY(name) FILTER (WHERE score > 0) FROM player
/// Player.select(Database.jsonGroupArray(Column("name"), filter: Column("score") > 0))
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonGroupArray(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_GROUP_ARRAY", [value.sqlExpression.jsonBuilderExpression])
public static func jsonGroupArray(
_ value: some SQLExpressible,
filter: (any SQLSpecificExpressible)? = nil)
-> SQLExpression {
.aggregateFunction(
"JSON_GROUP_ARRAY",
[value.sqlExpression.jsonBuilderExpression],
filter: filter?.sqlExpression,
isJSONValue: true)
}
/// The `JSON_GROUP_OBJECT` SQL function.
///
/// For example:
///
/// ```swift
/// // SELECT JSON_GROUP_OBJECT(name, score) FROM player
/// Player.select(Database.jsonGroupObject(
/// key: Column("name"),
/// value: Column("score")))
///
/// // SELECT JSON_GROUP_OBJECT(name, score) FILTER (WHERE score > 0) FROM player
/// Player.select(Database.jsonGroupObject(
/// key: Column("name"),
/// value: Column("score"),
/// filter: Column("score") > 0))
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonGroupObject(key: some SQLExpressible, value: some SQLExpressible) -> SQLExpression {
.function("JSON_GROUP_OBJECT", [key.sqlExpression, value.sqlExpression.jsonBuilderExpression])
public static func jsonGroupObject(
key: some SQLExpressible,
value: some SQLExpressible,
filter: (any SQLSpecificExpressible)? = nil
) -> SQLExpression {
.aggregateFunction(
"JSON_GROUP_OBJECT",
[key.sqlExpression, value.sqlExpression.jsonBuilderExpression],
filter: filter?.sqlExpression,
isJSONValue: true)
}
}
#endif
+3 -3
View File
@@ -42,7 +42,7 @@ import Foundation
/// - ``hasCompletedMigrations(_:)``
public struct DatabaseMigrator {
/// Controls how a migration handle foreign keys constraints.
public enum ForeignKeyChecks {
public enum ForeignKeyChecks: Sendable {
/// The migration runs with disabled foreign keys.
///
/// Foreign keys are checked right before changes are committed on disk,
@@ -50,7 +50,7 @@ public struct DatabaseMigrator {
/// ``DatabaseMigrator/disablingDeferredForeignKeyChecks()``.
///
/// In this case, you can perform your own deferred foreign key checks
/// with ``Database/checkForeignKeys(in:)`` or
/// with ``Database/checkForeignKeys(in:in:)`` or
/// ``Database/checkForeignKeys()``:
///
/// ```swift
@@ -118,7 +118,7 @@ public struct DatabaseMigrator {
/// The returned migrator is _unsafe_, because it no longer guarantees the
/// integrity of the database. It is now _your_ responsibility to register
/// migrations that do not break foreign key constraints. See
/// ``Database/checkForeignKeys()`` and ``Database/checkForeignKeys(in:)``.
/// ``Database/checkForeignKeys()`` and ``Database/checkForeignKeys(in:in:)``.
///
/// Running migrations without foreign key checks can improve migration
/// performance on huge databases.
+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSPrivacyTracking</key>
<false/>
<key>NSPrivacyCollectedDataTypes</key>
<array/>
<key>NSPrivacyTrackingDomains</key>
<array/>
<key>NSPrivacyAccessedAPITypes</key>
<array/>
</dict>
</plist>
+1 -1
View File
@@ -80,7 +80,7 @@
/// using: Book.translatorForeignKey)
/// }
/// ```
public struct ForeignKey: Equatable {
public struct ForeignKey: Equatable, Sendable {
var originColumns: [String]
var destinationColumns: [String]?
@@ -366,6 +366,7 @@ extension AssociationToMany {
/// ### Top-Level Functions
///
/// - ``abs(_:)-43n8v``
/// - ``cast(_:as:)-63ttx``
/// - ``length(_:)-9dr2v``
public struct AssociationAggregate<RowDecoder> {
fileprivate let preparation: AssociationAggregatePreparation<RowDecoder>
@@ -835,7 +836,7 @@ extension AssociationAggregate {
}
}
// MARK: - IFNULL(...)
// MARK: - Functions
extension AssociationAggregate {
/// The `IFNULL` SQL function.
@@ -854,8 +855,6 @@ extension AssociationAggregate {
}
}
// MARK: - ABS(...)
/// The `ABS` SQL function.
public func abs<RowDecoder>(_ aggregate: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
@@ -863,7 +862,18 @@ public func abs<RowDecoder>(_ aggregate: AssociationAggregate<RowDecoder>)
aggregate.map(abs)
}
// MARK: - LENGTH(...)
/// The `CAST` SQL function.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_expr.html#castexpr>
public func cast<RowDecoder>(
_ aggregate: AssociationAggregate<RowDecoder>,
as storageClass: Database.StorageClass)
-> AssociationAggregate<RowDecoder>
{
aggregate
.map { cast($0, as: storageClass) }
.with { $0.key = aggregate.key } // Preserve key
}
/// The `LENGTH` SQL function.
public func length<RowDecoder>(_ aggregate: AssociationAggregate<RowDecoder>)
@@ -61,6 +61,7 @@
/// ### Batch Delete
///
/// - ``deleteAll(_:)``
/// - ``deleteAndFetchIds(_:)``
/// - ``deleteAndFetchCursor(_:)``
/// - ``deleteAndFetchAll(_:)``
/// - ``deleteAndFetchSet(_:)``
@@ -528,7 +529,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter selection: The returned columns (must not be empty).
@@ -561,7 +562,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - returns: A ``RecordCursor`` over the deleted records.
@@ -588,7 +589,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - returns: An array of deleted records.
@@ -614,7 +615,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - returns: A set of deleted records.
@@ -625,6 +626,41 @@ extension QueryInterfaceRequest {
{
try Set(deleteAndFetchCursor(db))
}
/// Executes a `DELETE RETURNING` statement and returns the set of
/// deleted ids.
///
/// For example:
///
/// ```swift
/// // Fetch the ids of deleted players
/// // DELETE FROM player RETURNING id
/// let request = Player.all()
/// let deletedPlayerIds = try request.deleteAndFetchIds(db)
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - returns: A set of deleted ids.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) // Identifiable
public func deleteAndFetchIds(_ db: Database)
throws -> Set<RowDecoder.ID>
where RowDecoder: TableRecord & Identifiable,
RowDecoder.ID: Hashable & DatabaseValueConvertible & StatementColumnConvertible
{
let primaryKey = try db.primaryKey(RowDecoder.databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"Fetching id requires a single-column primary key in the table \(databaseTableName)")
let statement = try deleteAndFetchStatement(db, selection: [Column(primaryKey.columns[0])])
return try RowDecoder.ID.fetchSet(statement)
}
#else
/// Returns a `DELETE RETURNING` prepared statement.
///
@@ -640,7 +676,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter selection: The returned columns (must not be empty).
@@ -674,7 +710,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - returns: A ``RecordCursor`` over the deleted records.
@@ -702,7 +738,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - returns: An array of deleted records.
@@ -729,7 +765,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - returns: A set of deleted records.
@@ -741,6 +777,41 @@ extension QueryInterfaceRequest {
{
try Set(deleteAndFetchCursor(db))
}
/// Executes a `DELETE RETURNING` statement and returns the set of
/// deleted ids.
///
/// For example:
///
/// ```swift
/// // Fetch the ids of deleted players
/// // DELETE FROM player RETURNING id
/// let request = Player.all()
/// let deletedPlayerIds = try request.deleteAndFetchIds(db)
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - returns: A set of deleted ids.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func deleteAndFetchIds(_ db: Database)
throws -> Set<RowDecoder.ID>
where RowDecoder: TableRecord & Identifiable,
RowDecoder.ID: Hashable & DatabaseValueConvertible & StatementColumnConvertible
{
let primaryKey = try db.primaryKey(RowDecoder.databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"Fetching id requires a single-column primary key in the table \(databaseTableName)")
let statement = try deleteAndFetchStatement(db, selection: [Column(primaryKey.columns[0])])
return try RowDecoder.ID.fetchSet(statement)
}
#endif
}
@@ -844,7 +915,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
@@ -893,7 +964,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
@@ -930,7 +1001,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
@@ -962,7 +1033,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
@@ -996,7 +1067,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
@@ -1046,7 +1117,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
@@ -1084,7 +1155,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
@@ -1117,7 +1188,7 @@ extension QueryInterfaceRequest {
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html>.
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
+1 -1
View File
@@ -92,7 +92,7 @@ extension ColumnExpression where Self == Column {
///
/// - ``init(_:)-5grmu``
/// - ``init(_:)-7xc4z``
public struct Column {
public struct Column: Sendable {
/// The hidden rowID column.
public static let rowID = Column("rowid")
+284 -157
View File
@@ -90,6 +90,11 @@ public struct SQLExpression {
/// A literal SQL expression
case literal(SQL)
/// The `CAST(expr AS storage-class)` expression.
///
/// See <https://www.sqlite.org/lang_expr.html#castexpr>.
indirect case cast(SQLExpression, Database.StorageClass)
/// The `BETWEEN` and `NOT BETWEEN` operators.
///
/// <expression> BETWEEN <lowerBound> AND <upperBound>
@@ -165,8 +170,14 @@ public struct SQLExpression {
///
/// <function>(<argument>, ...)
/// <function>(DISTINCT <argument>)
case function(String, flags: SQLFunctionFlags, arguments: [SQLExpression])
indirect case simpleFunction(SQLSimpleFunctionInvocation)
/// An aggregate function call.
///
/// <function>(<argument>, ...)
/// <function>(DISTINCT <argument>)
indirect case aggregateFunction(SQLAggregateFunctionInvocation)
/// An expression that checks for zero or positive values.
///
/// <expression> = 0
@@ -218,6 +229,9 @@ public struct SQLExpression {
case let .literal(sqlLiteral):
return .literal(sqlLiteral.qualified(with: alias))
case let .cast(expression, storageClass):
return .cast(expression.qualified(with: alias), storageClass)
case let .between(
expression: expression,
lowerBound: lowerBound,
@@ -268,11 +282,11 @@ public struct SQLExpression {
case .countAll:
return .countAll
case let .function(name, flags: flags, arguments: arguments):
return .function(
name,
flags: flags,
arguments: arguments.map { $0.qualified(with: alias) })
case let .simpleFunction(invocation):
return .simpleFunction(invocation.qualified(with: alias))
case let .aggregateFunction(invocation):
return .aggregateFunction(invocation.qualified(with: alias))
case let .isEmpty(expression, isNegated: isNegated):
return .isEmpty(expression.qualified(with: alias), isNegated: isNegated)
@@ -309,7 +323,7 @@ public struct SQLExpression {
/// 1000.databaseValue]
/// let request = Player.select(values.joined(operator: .add))
/// ```
public struct AssociativeBinaryOperator: Hashable {
public struct AssociativeBinaryOperator: Hashable, Sendable {
/// The SQL operator
let sql: String
@@ -916,9 +930,154 @@ extension SQLExpression {
// MARK: Functions
// TODO: add missing pure functions:
// https://www.sqlite.org/lang_aggfunc.html
// https://www.sqlite.org/lang_datefunc.html
// https://www.sqlite.org/lang_mathfunc.html
private static let knownPureFunctions: Set<String> = [
"ABS",
"CHAR",
"COALESCE",
"GLOB",
"HEX",
"IFNULL",
"IIF",
"INSTR",
"JSON",
"JSON_ARRAY",
"JSON_GROUP_ARRAY",
"JSON_GROUP_OBJECT",
"JSON_INSERT",
"JSON_OBJECT",
"JSON_PATCH",
"JSON_REMOVE",
"JSON_REPLACE",
"JSON_SET",
"JSON_QUOTE",
"LENGTH",
"LIKE",
"LIKELIHOOD",
"LIKELY",
"LOAD_EXTENSION",
"LOWER",
"LTRIM",
"NULLIF",
"PRINTF",
"QUOTE",
"REPLACE",
"ROUND",
"RTRIM",
"SOUNDEX",
"SQLITE_COMPILEOPTION_GET",
"SQLITE_COMPILEOPTION_USED",
"SQLITE_SOURCE_ID",
"SQLITE_VERSION",
"SUBSTR",
"TRIM",
"TYPEOF",
"UNICODE",
"UNLIKELY",
"UPPER",
"ZEROBLOB",
]
private static let knownAggregateFunctions: Set<String> = [
"AVG",
"COUNT",
"GROUP_CONCAT",
"JSON_GROUP_ARRAY",
"JSON_GROUP_OBJECT",
"MAX", // when single argument
"MIN", // when single argument
"SUM",
"TOTAL",
]
private static let knownFunctionsReturningJSONValue: Set<String> = [
"JSON",
"JSON_ARRAY",
"JSON_GROUP_ARRAY",
"JSON_GROUP_OBJECT",
"JSON_INSERT",
"JSON_OBJECT",
"JSON_PATCH",
"JSON_REMOVE",
"JSON_REPLACE",
"JSON_SET",
"JSON_QUOTE",
]
/// The `COUNT(*)` expression.
static let countAll = SQLExpression(impl: .countAll)
/// A function call.
static func function(_ functionName: String, _ arguments: [SQLExpression]) -> Self {
let name = functionName.uppercased()
if (name == "MAX" || name == "MIN") && arguments.count > 1 {
return .simpleFunction(
functionName,
arguments,
isPure: true,
isJSONValue: false)
} else if Self.knownAggregateFunctions.contains(name) {
return .aggregateFunction(
functionName,
arguments,
isJSONValue: Self.knownFunctionsReturningJSONValue.contains(name))
} else {
let isJSONValue: Bool
if name == "JSON_EXTRACT" && arguments.count > 2 {
isJSONValue = true
} else {
isJSONValue = Self.knownFunctionsReturningJSONValue.contains(name)
}
return .simpleFunction(
functionName, arguments,
isPure: Self.knownPureFunctions.contains(name),
isJSONValue: isJSONValue)
}
}
/// A simple function call.
///
/// - warning: Don't use this method for aggregate functions!
static func simpleFunction(
_ name: String,
_ arguments: [SQLExpression],
isPure: Bool = false,
isJSONValue: Bool = false)
-> Self
{
.init(impl: .simpleFunction(SQLSimpleFunctionInvocation(
name: name,
arguments: arguments,
isPure: isPure,
isJSONValue: isJSONValue)))
}
/// An aggregate function call.
static func aggregateFunction(
_ name: String,
_ arguments: [SQLExpression],
isDistinct: Bool = false,
ordering: SQLOrdering? = nil,
filter: SQLExpression? = nil,
isJSONValue: Bool = false)
-> Self
{
.init(impl: .aggregateFunction(.init(
name: name,
arguments: arguments,
isDistinct: isDistinct,
ordering: ordering,
filter: filter,
isJSONValue: isJSONValue)))
}
/// The `COUNT` function.
///
/// COUNT(<expression>)
@@ -930,24 +1089,7 @@ extension SQLExpression {
///
/// COUNT(DISTINCT <expression>)
static func countDistinct(_ expression: SQLExpression) -> Self {
function("COUNT", [expression], flags: .init(isAggregate: true, isDistinct: true))
}
/// A function call.
///
/// <function>(<argument>, ...)
static func function(_ name: String, _ arguments: [SQLExpression]) -> Self {
.init(impl: .function(
name,
flags: .defaultFlags(for: name, argumentCount: arguments.count),
arguments: arguments))
}
/// A function call with explicit flags.
///
/// <function>(<argument>, ...)
static func function(_ name: String, _ arguments: [SQLExpression], flags: SQLFunctionFlags) -> Self {
.init(impl: .function(name, flags: flags, arguments: arguments))
aggregateFunction("COUNT", [expression], isDistinct: true)
}
/// An expression that checks for zero or positive values.
@@ -958,6 +1100,13 @@ extension SQLExpression {
self.init(impl: .isEmpty(expression, isNegated: isNegated))
}
/// The `CAST(expr AS storage-class)` expression.
///
/// See <https://www.sqlite.org/lang_expr.html#castexpr>.
static func cast(_ expression: SQLExpression, as storageClass: Database.StorageClass) -> Self {
self.init(impl: .cast(expression, storageClass))
}
// MARK: Deferred
// TODO: replace with something that can work for WITHOUT ROWID table with a multi-columns primary key.
@@ -1071,18 +1220,8 @@ extension SQLExpression {
case let .collated(expression, _):
return try expression.column(db, for: alias, acceptsBijection: acceptsBijection)
case let .function(name, flags: flags, arguments: arguments) where !flags.isAggregate:
guard acceptsBijection else {
return nil
}
let name = name.uppercased()
if ["HEX", "QUOTE"].contains(name) && arguments.count == 1 {
return try arguments[0].column(db, for: alias, acceptsBijection: acceptsBijection)
} else if name == "IFNULL" && arguments.count == 2 && arguments[1].isConstantInRequest {
return try arguments[0].column(db, for: alias, acceptsBijection: acceptsBijection)
} else {
return nil
}
case let .simpleFunction(invocation) where acceptsBijection:
return try invocation.column(db, for: alias)
case let .qualifiedFastPrimaryKey(a):
if alias == a {
@@ -1145,6 +1284,9 @@ extension SQLExpression {
}
return resultSQL
case let .cast(expression, storageClass):
return try "CAST(\(expression.sql(context, wrappedInParenthesis: false)) AS \(storageClass.rawValue))"
case let .between(expression: expression, lowerBound: lowerBound, upperBound: upperBound, isNegated: isNegated):
var resultSQL = try """
\(expression.sql(context, wrappedInParenthesis: true)) \
@@ -1266,13 +1408,11 @@ extension SQLExpression {
case .countAll:
return "COUNT(*)"
case let .function(name, flags: flags, arguments: arguments):
assert(!flags.isDistinct || flags.isAggregate, "distinct requires aggregate")
assert(!flags.isDistinct || arguments.count == 1, "distinct requires a single argument")
return try name
+ (flags.isDistinct ? "(DISTINCT " : "(")
+ arguments.map { try $0.sql(context) }.joined(separator: ", ")
+ ")"
case let .simpleFunction(invocation):
return try invocation.sql(context)
case let .aggregateFunction(invocation):
return try invocation.sql(context, wrappedInParenthesis: wrappedInParenthesis)
case let .isEmpty(expression, isNegated: isNegated):
var resultSQL = try """
@@ -1700,6 +1840,9 @@ extension SQLExpression {
let .associativeBinary(_, expressions):
return expressions.allSatisfy(\.isConstantInRequest)
case let .cast(expression, _):
return expression.isConstantInRequest
case let .between(expression: expression, lowerBound: lowerBound, upperBound: upperBound, isNegated: _):
return expression.isConstantInRequest
&& lowerBound.isConstantInRequest
@@ -1721,10 +1864,8 @@ extension SQLExpression {
let .collated(expression, _):
return expression.isConstantInRequest
case let .function(_, flags: flags, arguments: arguments)
where flags.isPure && !flags.isAggregate:
return arguments.allSatisfy(\.isConstantInRequest)
case let .simpleFunction(invocation):
return invocation.isConstantInRequest
default:
return false
@@ -1783,7 +1924,7 @@ extension SQLExpression {
case .countAll:
return true
case let .function(_, flags: flags, arguments: _) where flags.isAggregate:
case .aggregateFunction:
return true
default:
@@ -1792,131 +1933,108 @@ extension SQLExpression {
}
}
// MARK: - Function Flags
/// Information about a function
struct SQLFunctionFlags {
/// https://www.sqlite.org/syntax/simple-function-invocation.html
struct SQLSimpleFunctionInvocation {
var name: String
var arguments: [SQLExpression]
/// A boolean value indicating if a function is known to be pure.
///
/// A false value does not provide any information.
var isPure = false
/// A boolean value indicating if a function is known to be
/// an aggregate.
///
/// A false value does not provide any information.
var isAggregate = false
/// A boolean value indicating if the function should have `DISTINCT`
/// in its SQL generation (as in `COUNT(DISTINCT ...)`).
var isDistinct = false
var isPure: Bool
/// A boolean value indicating if a function is known to return a
/// JSON value.
///
/// A false value does not provide any information.
var isJSONValue = false
var isJSONValue: Bool
var isConstantInRequest: Bool {
isPure && arguments.allSatisfy(\.isConstantInRequest)
}
func qualified(with alias: TableAlias) -> Self {
SQLSimpleFunctionInvocation(
name: name,
arguments: arguments.map { $0.qualified(with: alias) },
isPure: isPure,
isJSONValue: isJSONValue)
}
func column(_ db: Database, for alias: TableAlias) throws -> String? {
let name = name.uppercased()
if ["HEX", "QUOTE"].contains(name) && arguments.count == 1 {
return try arguments[0].column(db, for: alias, acceptsBijection: true)
} else if name == "IFNULL" && arguments.count == 2 && arguments[1].isConstantInRequest {
return try arguments[0].column(db, for: alias, acceptsBijection: true)
} else {
return nil
}
}
func sql(_ context: SQLGenerationContext) throws -> String {
var sql = name
sql += "("
sql += try arguments
.map { try $0.sql(context) }
.joined(separator: ", ")
sql += ")"
return sql
}
}
extension SQLFunctionFlags {
// TODO: add missing pure functions:
// https://www.sqlite.org/lang_aggfunc.html
// https://www.sqlite.org/lang_datefunc.html
// https://www.sqlite.org/lang_mathfunc.html
private static let knownPureFunctions: Set<String> = [
"ABS",
"CHAR",
"COALESCE",
"GLOB",
"HEX",
"IFNULL",
"IIF",
"INSTR",
"JSON",
"JSON_ARRAY",
"JSON_GROUP_ARRAY",
"JSON_GROUP_OBJECT",
"JSON_INSERT",
"JSON_OBJECT",
"JSON_PATCH",
"JSON_REMOVE",
"JSON_REPLACE",
"JSON_SET",
"JSON_QUOTE",
"LENGTH",
"LIKE",
"LIKELIHOOD",
"LIKELY",
"LOAD_EXTENSION",
"LOWER",
"LTRIM",
"NULLIF",
"PRINTF",
"QUOTE",
"REPLACE",
"ROUND",
"RTRIM",
"SOUNDEX",
"SQLITE_COMPILEOPTION_GET",
"SQLITE_COMPILEOPTION_USED",
"SQLITE_SOURCE_ID",
"SQLITE_VERSION",
"SUBSTR",
"TRIM",
"TYPEOF",
"UNICODE",
"UNLIKELY",
"UPPER",
"ZEROBLOB",
]
/// https://www.sqlite.org/syntax/aggregate-function-invocation.html
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, watchOS 7, *) SQLite 3.30+
private static let knownAggregateFunctions: Set<String> = [
"AVG",
"COUNT",
"GROUP_CONCAT",
"JSON_GROUP_ARRAY",
"JSON_GROUP_OBJECT",
"MAX", // when single argument
"MIN", // when single argument
"SUM",
"TOTAL",
]
/// A boolean value indicating if a function is known to return a
/// JSON value.
///
/// A false value does not provide any information.
var isJSONValue: Bool
private static let knownFunctionsReturningJSONValue: Set<String> = [
"JSON",
"JSON_ARRAY",
"JSON_GROUP_ARRAY",
"JSON_GROUP_OBJECT",
"JSON_INSERT",
"JSON_OBJECT",
"JSON_PATCH",
"JSON_REMOVE",
"JSON_REPLACE",
"JSON_SET",
"JSON_QUOTE",
]
func qualified(with alias: TableAlias) -> Self {
SQLAggregateFunctionInvocation(
name: name,
arguments: arguments.map { $0.qualified(with: alias) },
isDistinct: isDistinct,
ordering: ordering?.qualified(with: alias),
filter: filter?.qualified(with: alias),
isJSONValue: isJSONValue)
}
/// Infers flags from the function name and number of arguments.
static func defaultFlags(for functionName: String, argumentCount: Int) -> Self {
var flags = SQLFunctionFlags()
func sql(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
var sql = name
let name = functionName.uppercased()
flags.isPure = Self.knownPureFunctions.contains(name)
if (name == "MAX" || name == "MIN") && argumentCount > 1 {
flags.isPure = true
if isDistinct {
sql += "(DISTINCT "
} else {
flags.isAggregate = Self.knownAggregateFunctions.contains(name.uppercased())
sql += "("
}
if name == "JSON_EXTRACT" && argumentCount > 2 {
flags.isJSONValue = true
} else {
flags.isJSONValue = Self.knownFunctionsReturningJSONValue.contains(name)
sql += try arguments
.map { try $0.sql(context) }
.joined(separator: ", ")
if let ordering {
sql += try " ORDER BY \(ordering.sql(context))"
}
return flags
sql += ")"
if let filter {
sql += try " FILTER (WHERE \(filter.sql(context)))"
}
if wrappedInParenthesis && filter != nil {
return "(\(sql))"
} else {
return sql
}
}
}
@@ -1960,8 +2078,11 @@ extension SQLExpression {
case let .collated(expression, _):
return expression.isJSONValue
case let .function(_, flags: flags, arguments: _):
return flags.isJSONValue
case let .simpleFunction(invocation):
return invocation.isJSONValue
case let .aggregateFunction(invocation):
return invocation.isJSONValue
default:
return false
@@ -2044,7 +2165,9 @@ extension SQLExpressible where Self == Column {
///
/// - ``abs(_:)-5l6xp``
/// - ``average(_:)``
/// - ``average(_:filter:)``
/// - ``capitalized``
/// - ``cast(_:as:)-1dmu3``
/// - ``count(_:)``
/// - ``count(distinct:)``
/// - ``dateTime(_:_:)``
@@ -2056,9 +2179,13 @@ extension SQLExpressible where Self == Column {
/// - ``localizedUppercased``
/// - ``lowercased``
/// - ``min(_:)``
/// - ``min(_:filter:)``
/// - ``max(_:)``
/// - ``max(_:filter:)``
/// - ``sum(_:)``
/// - ``sum(_:filter:)``
/// - ``total(_:)``
/// - ``total(_:filter:)``
/// - ``uppercased``
/// - ``SQLDateModifier``
///
@@ -32,41 +32,76 @@ struct SQLForeignKeyRequest {
}
// Incomplete information: let's look for schema foreign keys
let foreignKeys = try db.foreignKeys(on: originTable).filter { foreignKey in
if destinationTable.lowercased() != foreignKey.destinationTable.lowercased() {
return false
}
if let originColumns {
let originColumns = Set(originColumns.lazy.map { $0.lowercased() })
let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.origin.lowercased() })
if originColumns != foreignKeyColumns {
return false
}
}
if let destinationColumns {
// TODO: test
let destinationColumns = Set(destinationColumns.lazy.map { $0.lowercased() })
let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.destination.lowercased() })
if destinationColumns != foreignKeyColumns {
return false
}
}
return true
//
// But maybe the tables are views. In this case, don't throw
// "no such table" error, because this is confusing for the user,
// as discovered in <https://github.com/groue/GRDB.swift/discussions/1481>.
// Instead, we'll crash with a clear message.
guard let originType = try tableType(db, for: originTable) else {
throw DatabaseError.noSuchTable(originTable)
}
// Matching foreign key(s) found
if let foreignKey = foreignKeys.first {
if foreignKeys.count == 1 {
// Non-ambiguous
return foreignKey.mapping
} else {
// Ambiguous: can't choose
fatalError("Ambiguous foreign key from \(originTable) to \(destinationTable)")
if originType.isView {
if originColumns == nil {
fatalError("""
Could not infer foreign key from '\(originTable)' \
to '\(destinationTable)'. To fix this error, provide an \
explicit `ForeignKey` in the association definition.
""")
}
} else {
let foreignKeys = try db.foreignKeys(on: originTable).filter { foreignKey in
if destinationTable.lowercased() != foreignKey.destinationTable.lowercased() {
return false
}
if let originColumns {
let originColumns = Set(originColumns.lazy.map { $0.lowercased() })
let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.origin.lowercased() })
if originColumns != foreignKeyColumns {
return false
}
}
if let destinationColumns {
// TODO: test
let destinationColumns = Set(destinationColumns.lazy.map { $0.lowercased() })
let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.destination.lowercased() })
if destinationColumns != foreignKeyColumns {
return false
}
}
return true
}
// Matching foreign key(s) found
if let foreignKey = foreignKeys.first {
if foreignKeys.count == 1 {
// Non-ambiguous
return foreignKey.mapping
} else {
// Ambiguous: can't choose
fatalError("""
Ambiguous foreign key from '\(originTable)' to \
'\(destinationTable)'. To fix this error, provide an \
explicit `ForeignKey` in the association definition.
""")
}
}
}
// No matching foreign key found: use the destination primary key
if let originColumns {
guard let destinationType = try tableType(db, for: destinationTable) else {
throw DatabaseError.noSuchTable(destinationTable)
}
if destinationType.isView {
fatalError("""
Could not infer foreign key from '\(originTable)' \
to '\(destinationTable)'. To fix this error, provide an \
explicit `ForeignKey` in the association definition, \
with both origin and destination columns.
""")
}
let destinationColumns = try db.primaryKey(destinationTable).columns
if originColumns.count == destinationColumns.count {
let mapping = zip(originColumns, destinationColumns).map {
@@ -76,7 +111,28 @@ struct SQLForeignKeyRequest {
}
}
fatalError("Could not infer foreign key from \(originTable) to \(destinationTable)")
fatalError("""
Could not infer foreign key from '\(originTable)' to \
'\(destinationTable)'. To fix this error, provide an \
explicit `ForeignKey` in the association definition.
""")
}
private struct TableType {
var isView: Bool
}
private func tableType(_ db: Database, for name: String) throws -> TableType? {
for schemaID in try db.schemaIdentifiers() {
if try db.schema(schemaID).containsObjectNamed(name, ofType: .table) {
return TableType(isView: false)
}
if try db.schema(schemaID).containsObjectNamed(name, ofType: .view) {
return TableType(isView: true)
}
}
return nil
}
}
+217 -6
View File
@@ -10,6 +10,40 @@ public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression {
.function("ABS", [value.sqlExpression])
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `AVG` SQL function.
///
/// For example:
///
/// ```swift
/// // AVG(length)
/// average(Column("length"))
/// ```
public func average(
_ value: some SQLSpecificExpressible,
filter: (any SQLSpecificExpressible)? = nil)
-> SQLExpression {
.aggregateFunction("AVG", [value.sqlExpression], filter: filter?.sqlExpression)
}
#else
/// The `AVG` SQL function.
///
/// For example:
///
/// ```swift
/// // AVG(length) FILTER (WHERE length > 0)
/// average(Column("length"), filter: Column("length") > 0)
/// ```
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
public func average(
_ value: some SQLSpecificExpressible,
filter: some SQLSpecificExpressible)
-> SQLExpression {
.aggregateFunction(
"AVG", [value.sqlExpression],
filter: filter.sqlExpression)
}
/// The `AVG` SQL function.
///
/// For example:
@@ -19,7 +53,22 @@ public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression {
/// average(Column("length"))
/// ```
public func average(_ value: some SQLSpecificExpressible) -> SQLExpression {
.function("AVG", [value.sqlExpression])
.aggregateFunction("AVG", [value.sqlExpression])
}
#endif
/// The `CAST` SQL function.
///
/// For example:
///
/// ```swift
/// // CAST(value AS REAL)
/// cast(Column("value"), as: .real)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_expr.html#castexpr>
public func cast(_ expression: some SQLSpecificExpressible, as storageClass: Database.StorageClass) -> SQLExpression {
.cast(expression.sqlExpression, as: storageClass)
}
/// The `COUNT` SQL function.
@@ -72,6 +121,38 @@ public func length(_ value: some SQLSpecificExpressible) -> SQLExpression {
.function("LENGTH", [value.sqlExpression])
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `MAX` SQL function.
///
/// For example:
///
/// ```swift
/// // MAX(score)
/// max(Column("score"))
/// ```
public func max(
_ value: some SQLSpecificExpressible,
filter: (any SQLSpecificExpressible)? = nil)
-> SQLExpression {
.aggregateFunction("MAX", [value.sqlExpression], filter: filter?.sqlExpression)
}
#else
/// The `MAX` SQL function.
///
/// For example:
///
/// ```swift
/// // MAX(score) FILTER (WHERE score < 0)
/// max(Column("score"), filter: Column("score") < 0)
/// ```
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
public func max(
_ value: some SQLSpecificExpressible,
filter: some SQLSpecificExpressible)
-> SQLExpression {
.aggregateFunction("MAX", [value.sqlExpression], filter: filter.sqlExpression)
}
/// The `MAX` SQL function.
///
/// For example:
@@ -81,7 +162,40 @@ public func length(_ value: some SQLSpecificExpressible) -> SQLExpression {
/// max(Column("score"))
/// ```
public func max(_ value: some SQLSpecificExpressible) -> SQLExpression {
.function("MAX", [value.sqlExpression])
.aggregateFunction("MAX", [value.sqlExpression])
}
#endif
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `MIN` SQL function.
///
/// For example:
///
/// ```swift
/// // MIN(score)
/// min(Column("score"))
/// ```
public func min(
_ value: some SQLSpecificExpressible,
filter: (any SQLSpecificExpressible)? = nil)
-> SQLExpression {
.aggregateFunction("MIN", [value.sqlExpression], filter: filter?.sqlExpression)
}
#else
/// The `MIN` SQL function.
///
/// For example:
///
/// ```swift
/// // MIN(score) FILTER (WHERE score > 0)
/// min(Column("score"), filter: Column("score") > 0)
/// ```
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
public func min(
_ value: some SQLSpecificExpressible,
filter: some SQLSpecificExpressible)
-> SQLExpression {
.aggregateFunction("MIN", [value.sqlExpression], filter: filter.sqlExpression)
}
/// The `MIN` SQL function.
@@ -93,7 +207,55 @@ public func max(_ value: some SQLSpecificExpressible) -> SQLExpression {
/// min(Column("score"))
/// ```
public func min(_ value: some SQLSpecificExpressible) -> SQLExpression {
.function("MIN", [value.sqlExpression])
.aggregateFunction("MIN", [value.sqlExpression])
}
#endif
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `SUM` SQL function.
///
/// For example:
///
/// ```swift
/// // SUM(amount)
/// sum(Column("amount"))
/// ```
///
/// See also ``total(_:)``.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
public func sum(
_ value: some SQLSpecificExpressible,
orderBy ordering: (any SQLOrderingTerm)? = nil,
filter: (any SQLSpecificExpressible)? = nil)
-> SQLExpression
{
.aggregateFunction(
"SUM", [value.sqlExpression],
ordering: ordering?.sqlOrdering,
filter: filter?.sqlExpression)
}
#else
/// The `SUM` SQL function.
///
/// For example:
///
/// ```swift
/// // SUM(amount) FILTER (WHERE amount > 0)
/// sum(Column("amount"), filter: Column("amount") > 0)
/// ```
///
/// See also ``total(_:)``.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
public func sum(
_ value: some SQLSpecificExpressible,
filter: some SQLSpecificExpressible)
-> SQLExpression {
.aggregateFunction(
"SUM", [value.sqlExpression],
filter: filter.sqlExpression)
}
/// The `SUM` SQL function.
@@ -109,7 +271,55 @@ public func min(_ value: some SQLSpecificExpressible) -> SQLExpression {
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression {
.function("SUM", [value.sqlExpression])
.aggregateFunction("SUM", [value.sqlExpression])
}
#endif
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// The `TOTAL` SQL function.
///
/// For example:
///
/// ```swift
/// // TOTAL(amount)
/// total(Column("amount"))
/// ```
///
/// See also ``sum(_:)``.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
public func total(
_ value: some SQLSpecificExpressible,
orderBy ordering: (any SQLOrderingTerm)? = nil,
filter: (any SQLSpecificExpressible)? = nil)
-> SQLExpression
{
.aggregateFunction(
"TOTAL", [value.sqlExpression],
ordering: ordering?.sqlOrdering,
filter: filter?.sqlExpression)
}
#else
/// The `TOTAL` SQL function.
///
/// For example:
///
/// ```swift
/// // TOTAL(amount) FILTER (WHERE amount > 0)
/// total(Column("amount"), filter: Column("amount") > 0)
/// ```
///
/// See also ``total(_:)``.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
public func total(
_ value: some SQLSpecificExpressible,
filter: some SQLSpecificExpressible)
-> SQLExpression {
.aggregateFunction(
"TOTAL", [value.sqlExpression],
filter: filter.sqlExpression)
}
/// The `TOTAL` SQL function.
@@ -125,8 +335,9 @@ public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression {
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
public func total(_ value: some SQLSpecificExpressible) -> SQLExpression {
.function("TOTAL", [value.sqlExpression])
.aggregateFunction("TOTAL", [value.sqlExpression])
}
#endif
// MARK: - String functions
@@ -211,7 +422,7 @@ extension SQLSpecificExpressible {
/// A date modifier for SQLite date functions.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_datefunc.html>
public enum SQLDateModifier: SQLSpecificExpressible {
public enum SQLDateModifier: SQLSpecificExpressible, Sendable {
/// Adds the specified amount of seconds
case second(Double)
+14 -7
View File
@@ -171,7 +171,7 @@ struct SQLRelation {
var source: SQLSource
var selectionPromise: DatabasePromise<[SQLSelection]>
var filterPromise: DatabasePromise<SQLExpression>?
var ordering: SQLRelation.Ordering = SQLRelation.Ordering()
var ordering = SQLRelation.Ordering()
var ctes: OrderedDictionary<String, SQLCTE> = [:] // See also `allCTEs`
var children: OrderedDictionary<String, Child> = [:]
@@ -283,13 +283,20 @@ extension SQLRelation: Refinable {
}
func withStableOrder() -> Self {
with {
// Order by primary key. Don't order by rowid because those are
// not stable: rowids can change after a vacuum.
$0.ordering = $0.ordering.appending(Ordering(orderings: { db in
try db.primaryKey(source.tableName).columns.map { SQLExpression.column($0).sqlOrdering }
with { relation in
relation.ordering = relation.ordering.appending(Ordering(orderings: { [relation] db in
if try db.tableExists(source.tableName) {
// 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:
// ORDER BY 1, 2, 3, ...
let columnCount = try SQLQueryGenerator(relation: relation).columnCount(db)
return (1...columnCount).map { SQL(sql: $0.description).sqlOrdering }
}
}))
$0.children = children.mapValues { child in
relation.children = children.mapValues { child in
child.with {
$0.relation = $0.relation.withStableOrder()
}
+1 -1
View File
@@ -324,7 +324,7 @@ extension SQLSelection: SQLSelectable {
/// let players = try Player.select(AllColumns()).fetchAll(db)
/// }
/// ```
public struct AllColumns {
public struct AllColumns: Sendable {
/// The `*` selection.
public init() { }
}
+1 -1
View File
@@ -138,7 +138,7 @@
/// ### Database Observation Support
///
/// - ``databaseRegion(_:)``
public struct Table<RowDecoder> {
public struct Table<RowDecoder>: Sendable {
/// The table name.
public var tableName: String
Loaded 100 of 166 files, more files were not shown because too many files have changed in this diff. Show more