Compare commits

..
297 Commits
Author SHA1 Message Date
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
Gwendal Roué fd2e552cfb Merge branch 'development' 2023-10-15 11:20:12 +02:00
Gwendal Roué 13bf0686ef v6.20.2 2023-10-15 11:10:02 +02:00
Gwendal Roué 1a9e306c78 Merge pull request #1442 from groue/dev/fix-macos-json-availability
Extend the macOS availability of JSON functions
2023-10-15 11:02:49 +02:00
Gwendal Roué 565335ea0d Update documentation 2023-10-15 09:06:28 +02:00
Gwendal Roué aabdffabc2 All JSON functions are available on macOS 10.15, but -> and ->>
Thank you @martindufort for the detailed report: https://gist.github.com/groue/046ebddb4a410304094c022d756081c8
2023-10-15 09:06:28 +02:00
Gwendal Roué 85792b8293 One availability per JSON function 2023-10-15 08:18:36 +02:00
Gwendal Roué c4c13b6f53 Doc updates for GRDBSnapshotTesting 2023-10-14 11:22:48 +02:00
Gwendal Roué d597fd56e9 v6.20.1 2023-10-13 07:42:44 +02:00
Gwendal Roué 94a7a59cc9 Remove debug print 2023-10-13 07:40:02 +02:00
Gwendal Roué f6f93469fb Merge branch 'development' 2023-10-13 07:18:32 +02:00
Gwendal Roué 120241b069 v6.20.0 2023-10-12 22:37:01 +02:00
Gwendal Roué 856d9cbe53 Merge pull request #1439 from groue/dev/dump
Dump requests
2023-10-12 22:34:20 +02:00
Gwendal Roué a8331d7335 CHANGELOG 2023-10-12 09:17:50 +02:00
Gwendal Roué dc1f9450c0 Expose DatabaseValue.init(sqliteStatement:index:)
This helps users implement custom dump formats
2023-10-12 09:17:50 +02:00
Gwendal Roué 7a7ee554c7 OrderedRequest.withStableOrder() 2023-10-12 09:17:50 +02:00
Gwendal Roué aadb887b34 Report test results from Github actions
https://github.com/kishikawakatsumi/xcresulttool/discussions/630
2023-10-12 09:17:50 +02:00
Gwendal Roué 69ae4c4e96 Dump 2023-10-12 09:17:50 +02:00
Gwendal Roué f4ac0ab119 Make it possible to observe the supplementary fetches 2023-10-08 20:41:05 +02:00
Gwendal Roué 8d4cc05021 Add missing tests for GRDB+SQLCipher 2023-10-08 20:20:07 +02:00
Gwendal Roué 16d6c92722 Add missing test file to GRDBCustom 2023-10-08 20:14:21 +02:00
Gwendal Roué c7047c4b33 Trim SQL in DatabaseError descriptoin 2023-10-08 20:07:59 +02:00
Gwendal Roué e22bf8fe0a DocC organization 2023-10-08 20:05:22 +02:00
Gwendal Roué e994fca2b5 Fix documentation typo 2023-10-07 11:36:31 +02:00
Gwendal Roué c599f6423e Fix link 2023-10-04 23:00:02 +02:00
Gwendal Roué 458b7211df Merge branch 'development' 2023-10-04 22:06:37 +02:00
Gwendal Roué 703e3c2b68 v6.19.0 2023-10-04 22:06:27 +02:00
Gwendal Roué 0eb973b6db Record types with an auto-incremented id should avoid the Identifiable protocol. 2023-10-04 22:02:18 +02:00
Gwendal Roué cbcc057222 Merge pull request #1436 from groue/experimental/JSONColumn
JSON functions
2023-10-04 21:22:43 +02:00
Gwendal Roué d64de2bbdb CHANGELOG 2023-10-04 19:57:45 +02:00
Gwendal Roué 1f0b52a012 JSON documentation 2023-10-04 19:57:45 +02:00
Gwendal Roué 908f8b242a Prepare documentation for JSON 2023-10-04 19:55:12 +02:00
Gwendal Roué 9faea276d8 JSON tests 2023-10-04 19:55:12 +02:00
Gwendal Roué 5a42d78e06 Data decoding and encoding strategies
Users must be able to store JSON data as text in the database.
2023-10-04 19:55:12 +02:00
Gwendal Roué 546e8aa77c JSONColumn and SQLJSONExpressible 2023-10-04 19:55:12 +02:00
Gwendal Roué ed01d40ba9 JSON functions 2023-10-04 19:55:12 +02:00
Gwendal Roué 97e6f88b31 Add new .jsonText column type 2023-10-04 19:55:12 +02:00
Gwendal Roué 718102f743 Create indexes on expressions 2023-10-02 07:49:59 +02:00
Gwendal Roué 8cc52983b7 Introduce SQLFunctionFlags 2023-10-01 15:39:47 +02:00
Gwendal Roué b896923fd4 TODO GRDB7: remove painful optionals due to IGNORE 2023-10-01 15:37:27 +02:00
Gwendal Roué 4abcbdf452 CHANGELOG 2023-09-16 17:53:50 +02:00
Gwendal Roué 6706de0103 Workaround for https://github.com/CocoaPods/CocoaPods/issues/12012 2023-09-16 17:52:40 +02:00
Gwendal Roué cc534fd19c Merge pull request #1429 from JhonnyBillM/dev/1428-EXTEND-VALUE-CONVERTIBLE-JSON-FORMAT-CUSTOMIZATION
Extend `DatabaseValueConvertible` JSON parsing format customization
2023-09-16 17:51:12 +02:00
Gwendal Roué 65dd5f1da8 Merge pull request #1430 from groue/dependabot/github_actions/actions/checkout-4
Bump actions/checkout from 3 to 4
2023-09-16 15:25:52 +02:00
Gwendal Roué 76dbcfe700 Fix documentation wording 2023-09-16 14:14:30 +02:00
Gwendal Roué 7944979d56 Add new methods to DocC 2023-09-16 14:14:20 +02:00
Gwendal Roué 7f6ab59250 Markdown files are soft-wrapped 2023-09-16 14:10:17 +02:00
Gwendal Roué 746f65a979 JSON encoder is always user-provided
Now all created JSONEncoder or JSONDecoder are user-controlled.
2023-09-16 14:07:37 +02:00
Gwendal Roué 9188251780 Add missing import required by SPM 2023-09-16 14:03:38 +02:00
Gwendal Roué 1e995b659d Hard-wrap documentation comments 2023-09-16 14:03:26 +02:00
dependabot[bot] e560993b44 Bump actions/checkout from 3 to 4
Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v3...v4)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-11 06:25:17 +00:00
Jhonny Bill Mena eec476b9ba ADD - unit tests for custom JSON Encoder and Decoder in DatabaseValueConvertible 2023-09-10 23:54:50 -04:00
Jhonny Bill Mena 3f96a965b9 ADD - databaseJSONDecoder and databaseJSONEncoder methods
ADD - optional jsonEncoder parameter to DatabaseValueEncoder

ADD - docs around new JSON customization methods
2023-09-10 23:54:50 -04:00
Gwendal Roué ce63f697ed Merge branch 'development' 2023-09-01 12:36:14 +02:00
Gwendal Roué 92f5b2a9dd v6.18.0 2023-09-01 11:39:48 +02:00
Gwendal Roué 5f103df04d Update CONTRIBUTING.md for DocC 2023-08-31 09:45:37 +02:00
Gwendal Roué 7cbcbe12f0 Expose path on DatabaseReader 2023-08-31 09:42:13 +02:00
Gwendal Roué c12fff16d3 CHANGELOG 2023-08-28 15:06:23 +01:00
Gwendal Roué e40569844f Merge branch 'development' 2023-08-26 10:41:10 +01:00
Gwendal Roué 3ac7598e9b v6.17.0 2023-08-26 09:47:38 +01:00
Gwendal Roué fd847d5a25 CHANGELOG 2023-08-26 09:41:39 +01:00
Gwendal Roué 6fec245d2f Merge pull request #1421 from groue/dev/journalModeSetup
Make it possible to open a DatabaseQueue in the WAL mode
2023-08-26 09:40:18 +01:00
Gwendal Roué 9e5cb95e1f Documentation for Configuration.journalMode 2023-08-25 10:11:41 +01:00
Gwendal Roué 13bc9ae56c Tests for Configuration.journalMode 2023-08-25 09:10:43 +01:00
Gwendal Roué e79b4e25db Apply Configuration.journalMode 2023-08-25 09:10:33 +01:00
Gwendal Roué f76093a0c7 Database.setUpWALMode() 2023-08-25 09:10:26 +01:00
Gwendal Roué 45b248b4ed Configuration.journalMode 2023-08-25 09:10:26 +01:00
Gwendal Roué 97c04a7f26 Shorten line length 2023-07-29 11:42:02 +02:00
Gwendal Roué 9ff58c32e7 Use CChar instead of Int8 when we deal with C strings 2023-07-29 11:13:41 +02:00
Gwendal Roué 0b2b26fd11 A statement can delete even if it's not a DELETE statement (through triggers) 2023-07-29 11:08:55 +02:00
Gwendal Roué 6f18de6a94 Fix typo 2023-07-29 11:08:02 +02:00
Gwendal Roué 28c6ea96b4 Fix redundant_self_in_closure Swiftlint warning 2023-07-29 10:06:33 +02:00
Gwendal Roué 206bf209af Fix unneeded_synthesized_initializer Swiftlint warning 2023-07-29 10:00:42 +02:00
Gwendal Roué e83f3eb25e Merge branch 'development' 2023-07-09 18:32:52 +02:00
Gwendal Roué e16d4accb3 v6.16.0 2023-07-09 18:08:27 +02:00
Gwendal Roué 9ff4060b10 Merge pull request #1405 from groue/dev/belongsToColumn
Simplify the declaration of BelongsTo associations in the database schema
2023-07-09 17:30:57 +02:00
Gwendal Roué 4ac434c83c CHANGELOG 2023-07-09 17:22:41 +02:00
Gwendal Roué 913168df2d Upgrade tests with belongsTo 2023-07-09 17:22:38 +02:00
Gwendal Roué f8c99f96bc Upgrade playgrounds with belongsTo 2023-07-09 17:22:38 +02:00
Gwendal Roué 466ecd5ba5 Documentation 2023-07-09 17:22:38 +02:00
Gwendal Roué 7a0a354d22 Implement ForeignKeyDefinition 2023-07-09 17:22:38 +02:00
Gwendal Roué 349253e196 Failing tests for ForeignKeyDefinition 2023-07-09 17:16:08 +02:00
Gwendal Roué dd85e699e2 Help handling of columns with no declared type 2023-07-09 17:16:08 +02:00
Gwendal Roué c647840485 PrimaryKeyInfo exposes column types 2023-07-09 17:16:08 +02:00
Gwendal Roué 3375282252 Update outdated documentation about views 2023-07-09 17:13:22 +02:00
Gwendal Roué 82d3af48c3 CHANGELOG 2023-07-09 17:13:22 +02:00
Gwendal Roué bebb751b3c Create and drop view 2023-07-09 17:13:22 +02:00
Gwendal Roué 08fbd82ead Rename StatementArgumentsSink.forRawSQL to literalValues 2023-07-09 17:13:22 +02:00
Gwendal Roué 89dd426403 CHANGELOG 2023-07-09 15:16:06 +02:00
Gwendal Roué 3206d04f0e Merge pull request #1401 from kustra/dev/linux-compile-fixes
Linux compilation fixes
2023-07-09 15:12:41 +02:00
Gwendal Roué ee0d3e43e0 iOS 17: Update date formatter tests so that it does not depend on the space before AM/PM
iOS 17 has changed that space
2023-07-09 14:37:45 +02:00
László Kustra f113963d31 Remove obsolete SQLite trace logic, as min SQLite version is 3.19.3 2023-07-07 11:05:17 +02:00
Gwendal Roué 7d48703986 CHANGELOG 2023-07-02 15:43:50 +02:00
Gwendal Roué f06e117d66 Merge pull request #1403 from groue/dev/ci-macOS13
GitHub CI: test Xcode 14.3.1, macOS 13
2023-07-02 15:43:29 +02:00
Gwendal Roué 5fca5fdabf Force MACOSX_DEPLOYMENT_TARGET on SQLCipher CocoaPods tests
Workaround for https://github.com/CocoaPods/CocoaPods/issues/11839
2023-07-02 14:18:07 +02:00
Gwendal Roué 2bd080799f Test universal xcframework 2023-07-02 14:18:07 +02:00
Gwendal Roué 1577825585 GitHub CI: test Xcode 14.3.1, macOS 13 2023-07-02 14:18:07 +02:00
Gwendal Roué 9b7ba606d8 Merge pull request #1402 from groue/dev/sqlite-3.42.0
Upgrade custom SQLite builds to 3.42.0
2023-07-02 14:17:18 +02:00
Gwendal Roué c9d8ce57a7 Trigger CI on custom SQLite upgrade 2023-07-02 12:44:18 +02:00
Gwendal Roué 2bb904775f CHANGELOG 2023-07-02 12:38:41 +02:00
Gwendal Roué 66826288d6 Upgrade custom SQLite builds to 3.42.0 2023-07-02 12:32:56 +02:00
Gwendal Roué 59c41c97af Clarify the prevention of database access from TransactionObserver callbacks 2023-07-02 10:58:09 +02:00
László Kustra 47d8ef4358 Fix the Linux version of sqlite3_trace for SQLite 3.19.3 2023-06-29 16:23:36 +02:00
László Kustra 25b49cba01 Add autoreleasepool shim for Linux 2023-06-29 16:23:36 +02:00
László Kustra 788887a2b8 Remove selector-based NotificationCenter calls on Linux 2023-06-29 16:23:36 +02:00
László Kustra 4057e3be07 Use cross-platform ProcessInfo instance property 2023-06-29 16:23:36 +02:00
267 changed files with 19651 additions and 3439 deletions

No files matched your search

+44 -28
View File
@@ -13,6 +13,7 @@ on:
- '.github/workflows/**'
- 'Makefile'
- 'Package.swift'
- 'SQLiteCustom/src'
pull_request:
paths:
- 'GRDB/**'
@@ -20,6 +21,7 @@ on:
- '.github/workflows/**'
- 'Makefile'
- 'Package.swift'
- 'SQLiteCustom/src'
concurrency:
group: ${{ github.ref_name }}
@@ -38,24 +40,32 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
destination: "platform=macOS"
name: "macOS"
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
destination: "OS=16.4,name=iPhone 14 Pro"
name: "iOS"
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
destination: "OS=16.4,name=Apple TV"
name: "tvOS"
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
runsOn: macOS-13
destination: "platform=macOS"
name: "macOS"
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
runsOn: macOS-13
destination: "OS=16.2,name=iPhone 14"
name: "iOS"
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
destination: "OS=16.1,name=Apple TV"
name: "tvOS"
- xcode: "Xcode_14.1.app"
runsOn: macOS-12
runsOn: macOS-13
destination: "platform=macOS"
name: "macOS"
- xcode: "Xcode_14.1.app"
runsOn: macOS-12
runsOn: macOS-13
destination: "OS=16.1,name=iPhone 14"
name: "iOS"
- xcode: "Xcode_14.0.1.app"
@@ -67,7 +77,7 @@ jobs:
destination: "OS=16.0,name=iPhone 14"
name: "iOS"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project GRDB.xcodeproj -scheme GRDB -destination "${{ matrix.destination }}" OTHER_SWIFT_FLAGS='$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' GCC_PREPROCESSOR_DEFINITIONS='$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' clean test
SPM:
@@ -80,17 +90,20 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
name: "Xcode 14.3.1"
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
runsOn: macOS-13
name: "Xcode 14.2"
- xcode: "Xcode_14.1.app"
runsOn: macOS-12
runsOn: macOS-13
name: "Xcode 14.1"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: make test_SPM test_install_SPM
SQLCipher3:
@@ -103,11 +116,14 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.2.app"
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
name: "Xcode 14.3.1"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
name: "Xcode 14.2"
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher3Encrypted
SQLCipher4:
@@ -120,14 +136,14 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
name: "Xcode 14.2"
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
name: "Xcode 14.3.1"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher4Encrypted
CustomSQLite:
@@ -140,14 +156,14 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
name: "Xcode 14.2"
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
name: "Xcode 14.3.1"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: make test_framework_GRDBCustomSQLiteOSX
XCFramework:
@@ -160,14 +176,14 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
name: "Xcode 14.2"
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
name: "Xcode 14.3.1"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: make test_archive_GRDBOSX_xcframework
run: make test_universal_xcframework
+179
View File
@@ -7,6 +7,20 @@ 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)
- `6.17.x` Releases - [6.17.0](#6170)
- `6.16.x` Releases - [6.16.0](#6160)
- `6.15.x` Releases - [6.15.0](#6150) - [6.15.1](#6151)
- `6.14.x` Releases - [6.14.0](#6140)
- `6.13.x` Releases - [6.13.0](#6130)
@@ -113,6 +127,171 @@ 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)
- **Fixed**: [#1442](https://github.com/groue/GRDB.swift/pull/1442) by [@groue](https://github.com/groue): Extend the macOS availability of JSON functions
## 6.20.1
Released October 13, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.20.0...v6.20.1)
- **Fixed**: Removed a debug print
## 6.20.0
Released October 13, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.19.0...v6.20.0)
- **New**: [#1439](https://github.com/groue/GRDB.swift/pull/1439) by [@groue](https://github.com/groue): Dump requests
- **New**: `QueryInterfaceRequest.withStableOrder()` returns a request with well-defined order, suitable for tests.
## 6.19.0
Released October 4, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.18.0...v6.19.0)
- **New**: [#1429](https://github.com/groue/GRDB.swift/pull/1429) by [@JhonnyBillM](https://github.com/JhonnyBillM): Allow `DatabaseValueConvertible` types to customize their database JSON format
- **New**: [#1436](https://github.com/groue/GRDB.swift/pull/1436) by [@myyra](https://github.com/myyra) and [@groue](https://github.com/groue): JSON functions
- **New**: `Database` has learned to create indexes on expressions, and specify specific collations on indexed columns, with the `create(index:on:expressions:options:condition:)` method.
- **New**: Codable records can specify coding strategies for their `Data` properties. See [#1436](https://github.com/groue/GRDB.swift/pull/1436) for more information.
- **Documentation Update**: A new [JSON Support](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/json) article provides an overview of JSON handling.
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) now recommend that record types with an auto-incremented id avoid conforming to the `Identifiable` protocol.
## 6.18.0
Released September 1, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.17.0...v6.18.0)
- **New**: Expose the database path from `DatabaseReader`.
## 6.17.0
Released August 26, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.16.0...v6.17.0)
- **New**: [#1421](https://github.com/groue/GRDB.swift/pull/1421) by [@groue](https://github.com/groue): Make it possible to open a DatabaseQueue in the WAL mode
## 6.16.0
Released July 9, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.15.1...v6.16.0)
- **New**: [#1397](https://github.com/groue/GRDB.swift/pull/1397) by [@groue](https://github.com/groue): Swift API for creating database views
- **New**: [#1401](https://github.com/groue/GRDB.swift/pull/1401) by [@kustra](https://github.com/kustra): Linux compilation fixes
- **New**: [#1402](https://github.com/groue/GRDB.swift/pull/1402) by [@groue](https://github.com/groue): Upgrade custom SQLite builds to 3.42.0
- **New**: [#1403](https://github.com/groue/GRDB.swift/pull/1403) by [@groue](https://github.com/groue): GitHub CI: test Xcode 14.3.1, macOS 13
- **New**: :star: [#1405](https://github.com/groue/GRDB.swift/pull/1405) Simplify the declaration of BelongsTo associations in the database schema
- **Documentation Update**: The documentation was updated for the new recommended way to declare associations in the database schema, with the `belongsTo()` method introduced by [#1405](https://github.com/groue/GRDB.swift/pull/1405):
- [`belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tabledefinition/belongsto(_:intable:ondelete:onupdate:deferred:indexed:))
- [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema)
- [Migrations](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations)
- [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices)
- [Associations](Documentation/AssociationsBasics.md)
- [`BelongsToAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/belongstoassociation)
- [`HasManyAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasmanyassociation)
- [`HasOneAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasoneassociation)
## 6.15.1
Released June 17, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v6.15.0...v6.15.1)
+2 -2
View File
@@ -61,7 +61,7 @@ How you can Contribute
- Get familiar with the [Swift API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/).
- Spaces, not tabs.
- Whitespace-only lines are not trimmed.
- Documentation comments are hard-wrapped at column 80 (Xcode > Preferences > Text Editing > Display > [X] Page guide at column: 80).
- Documentation comments are hard-wrapped at column 76 (Xcode > Preferences > Text Editing > Display > [X] Page guide at column: 76).
- No Swiftlint warning after a build.
@@ -69,7 +69,7 @@ How you can Contribute
GRDB documentation is provided as a DocC reference, and guides ([README.md](README.md) and the [Documentation](Documentation) folder).
Please keep the reference and the guides up-to-date. Use Xcode > Product > Build Documentation in order to control the quality of your reference documentation.
Please keep the reference and the guides up-to-date. To control the quality of your DocC reference documentation, close the workspace, open `Package.swift` in Xcode, and use Product > Build Documentation.
GRDB is "documentation-driven", which means that nothing ships until it is supported by documentation that makes sense. Documentation makes sense when someone who is not you is able to figure out what is the purpose of your contribution, how to use it, and what are its eventual caveats and corner cases. When the documentation is hard to write, or reveals too many caveats, it is the sign that the api needs to be fixed.
+25 -21
View File
@@ -429,15 +429,13 @@ The matching [migration] would look like:
migrator.registerMigration("Employees") { db in
try db.create(table: "employee") { t in
t.autoIncrementedPrimaryKey("id")
t.column("managerId", .integer)
.indexed()
.references("employee", onDelete: .restrict)
t.belongsTo("manager", inTable: "employee", onDelete: .setNull)
t.column("name", .text)
}
}
```
Note that both sides of the self-join use a customized **[association key](#the-structure-of-a-joined-request)**. This helps consuming this association. For example:
Note that the associations on both sides of the self-join use a customized **[association key](#the-structure-of-a-joined-request)**. This helps consuming this association. For example:
```swift
struct EmployeeInfo: FetchableRecord, Decodable {
@@ -536,20 +534,16 @@ migrator.registerMigration("Books and Authors") { db in
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("authorId", .integer) // (2)
t.belongsTo("author", onDelete: .cascade) // (2)
.notNull() // (3)
.indexed() // (4)
.references("author", onDelete: .cascade) // (5)
t.column("title", .text)
}
}
```
1. The `author` table has a primary key.
2. The `book.authorId` column is used to link a book to the author it belongs to.
2. The `book.authorId` column is used to link a book to the author it belongs to. This column is indexed in order to ease the selection of an author's books. A foreign key is defined from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
3. Make the `book.authorId` column not null if you want SQLite to guarantee that all books have an author.
4. Create an index on the `book.authorId` column in order to ease the selection of an author's books.
5. Create a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
The example above uses auto-incremented primary keys. But generally speaking, all primary keys are supported, including composite primary keys that span several columns.
@@ -595,20 +589,16 @@ migrator.registerMigration("Books and Authors") { db in
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("authorId", .integer) // (2)
t.belongsTo("author", onDelete: .cascade) // (2)
.notNull() // (3)
.indexed() // (4)
.references("author", onDelete: .cascade) // (5)
t.column("title", .text)
}
}
```
1. The `author` table has a primary key.
2. The `book.authorId` column is used to link a book to the author it belongs to.
2. The `book.authorId` column is used to link a book to the author it belongs to. This column is indexed in order to ease the selection of an author's books. A foreign key is defined from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
3. Make the `book.authorId` column not null if you want SQLite to guarantee that all books have an author.
4. Create an index on the `book.authorId` column in order to ease the selection of an author's books.
5. Create a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
The example above uses auto-incremented primary keys. But generally speaking, all primary keys are supported, including composite primary keys that span several columns.
@@ -654,10 +644,9 @@ migrator.registerMigration("Countries") { db in
}
try db.create(table: "demographics") { t in
t.autoIncrementedPrimaryKey("id")
t.column("countryCode", .text) // (2)
t.belongsTo("country", onDelete: .cascade) // (2)
.notNull() // (3)
.unique() // (4)
.references("country", onDelete: .cascade) // (5)
t.column("population", .integer)
t.column("density", .double)
}
@@ -665,10 +654,9 @@ migrator.registerMigration("Countries") { db in
```
1. The `country` table has a primary key.
2. The `demographics.countryCode` column is used to link a demographic profile to the country it belongs to.
2. The `demographics.countryCode` column is used to link a demographic profile to the country it belongs to. This column is indexed in order to ease the selection of the demographics of a country. A foreign key is defined from `demographics.countryCode` column to `country.code`, so that SQLite guarantees that no profile refers to a missing country. The `onDelete: .cascade` option has SQLite automatically delete a profile when its country is deleted. See [Foreign Key Actions] for more information.
3. Make the `demographics.countryCode` column not null if you want SQLite to guarantee that all profiles are linked to a country.
4. Create a unique index on the `demographics.countryCode` column in order to guarantee the unicity of any country's profile.
5. Create a foreign key from `demographics.countryCode` column to `country.code`, so that SQLite guarantees that no profile refers to a missing country. The `onDelete: .cascade` option has SQLite automatically delete a profile when its country is deleted. See [Foreign Key Actions] for more information.
The example above uses a string primary key for the "country" table. But generally speaking, all primary keys are supported, including composite primary keys that span several columns.
@@ -720,6 +708,22 @@ Sometimes the database schema does not define any foreign key. And sometimes, th
![AmbiguousForeignKeys](https://cdn.rawgit.com/groue/GRDB.swift/master/Documentation/Images/Associations2/AmbiguousForeignKeys.svg)
```swift
// The migration that has created the above schema
migrator.registerMigration("Library") { db in
try db.create(table: "person") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("author", inTable: "person")
t.belongsTo("translator", inTable: "person")
t.column("title", .text)
}
}
```
When this happens, associations can't be automatically inferred from the database schema. GRDB will complain with a fatal error such as "Ambiguous foreign key from book to person", or "Could not infer foreign key from book to person".
Your help is needed. You have to instruct GRDB which foreign key to use:
@@ -2657,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.39.3](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]
```
@@ -29,10 +29,7 @@ migrator.registerMigration("createLibrary") { db in
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("title", .text).notNull()
t.column("authorId", .integer)
.notNull()
.indexed()
.references("author", onDelete: .cascade)
t.belongsTo("author", onDelete: .cascade).notNull()
}
}
@@ -23,7 +23,7 @@ migrator.registerMigration("createPet") { db in
try db.create(table: "pet") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.column("ownerId", .integer).references("person", onDelete: .cascade)
t.belongsTo("owner", inTable: "person", onDelete: .cascade)
}
}
try! migrator.migrate(dbQueue)
+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.15.1'
s.version = '6.29.3'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+166 -2
View File
@@ -13,6 +13,10 @@
56012B9F257404DF00B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; };
560233C42724234F00529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C32724234F00529DF3 /* SharedValueObservation.swift */; };
560233C92724338800529DF3 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C82724338800529DF3 /* SharedValueObservationTests.swift */; };
5603CEBA2AC862EC00CF097D /* SQLJSONFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */; };
5603CEBB2AC862EC00CF097D /* SQLJSONExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */; };
5603CEBC2AC862EC00CF097D /* JSONColumn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB82AC862EC00CF097D /* JSONColumn.swift */; };
5603CED42AC8642F00CF097D /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEC92AC8631600CF097D /* JSONExpressionsTests.swift */; };
560432A0228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; };
560432A3228F1668009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */; };
5604484925DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */; };
@@ -54,6 +58,9 @@
561CFA7823735016000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */; };
561CFA982376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; };
561CFA9C2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA9B2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift */; };
561F38D82AC88A550051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */; };
561F38EF2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; };
561F38F42AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; };
562205F11E420E47005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */; };
562205F21E420E47005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */; };
562205F31E420E47005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */; };
@@ -68,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 */; };
@@ -94,6 +103,7 @@
563B8FB524A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */; };
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */; };
563C67B324628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; };
563CBBE12A595131008905CE /* SQLIndexGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563CBBE02A595131008905CE /* SQLIndexGenerator.swift */; };
563DE4F3231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */; };
563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF414215F87EB007DAACD /* OrderedDictionary.swift */; };
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF42C2161180D007DAACD /* AssociationAggregate.swift */; };
@@ -115,6 +125,7 @@
56419C6D24A519A2004967E1 /* ValueObservationPublisherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */; };
56419C7824A51A38004967E1 /* Recorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A5E24A51601004967E1 /* Recorder.swift */; };
56419C7924A51A38004967E1 /* RecordingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A5F24A51601004967E1 /* RecordingError.swift */; };
5642A3182AD66DFE0065F717 /* LineDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5642A3172AD66DFE0065F717 /* LineDumpFormat.swift */; };
564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
564CE43121AA901800652B19 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */; };
564CE4E921B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; };
@@ -146,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 */; };
@@ -194,14 +206,24 @@
5676FBA622F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */; };
56781B0B243F86E600650A83 /* Refinable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56781B0A243F86E600650A83 /* Refinable.swift */; };
5679533327E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */; };
567B5BE72AD3284100629622 /* DatabaseReader+dump.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE02AD3284100629622 /* DatabaseReader+dump.swift */; };
567B5BE82AD3284100629622 /* DumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE12AD3284100629622 /* DumpFormat.swift */; };
567B5BE92AD3284100629622 /* QuoteDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE32AD3284100629622 /* QuoteDumpFormat.swift */; };
567B5BEA2AD3284100629622 /* JSONDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE42AD3284100629622 /* JSONDumpFormat.swift */; };
567B5BEB2AD3284100629622 /* DebugDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE52AD3284100629622 /* DebugDumpFormat.swift */; };
567B5BEC2AD3284100629622 /* Database+Dump.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE62AD3284100629622 /* Database+Dump.swift */; };
567B5C532AD32FF100629622 /* DatabaseDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BDC2AD3283500629622 /* DatabaseDumpTests.swift */; };
567B5C542AD32FF100629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BDB2AD3283500629622 /* DatabaseReaderDumpTests.swift */; };
567DAF1C1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
567DAF351EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */; };
56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */; };
5685C1932AD52EE600DA4B7A /* ListDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */; };
56894F752606576600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F742606576600268F4D /* FoundationDecimalTests.swift */; };
56894FB72606589700268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.swift */; };
568C3F7A2A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F792A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift */; };
568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLQueryGenerator.swift */; };
568EB71929211E0800E59445 /* DatabaseSnapshotPool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */; };
568EB71E2921234800E59445 /* DatabaseSnapshotPoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */; };
@@ -254,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 */; };
@@ -379,6 +402,14 @@
56F34FC224B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */; };
56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
56F61DD5283D344E00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DD4283D344E00AF9884 /* getThreadsCount.c */; };
56F89DF72A57EAA9002FE2AA /* ColumnDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DF62A57EAA9002FE2AA /* ColumnDefinition.swift */; };
56F89DFC2A57EAEA002FE2AA /* ForeignKeyDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DFB2A57EAEA002FE2AA /* ForeignKeyDefinition.swift */; };
56F89DFE2A57EB19002FE2AA /* IndexDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DFD2A57EB19002FE2AA /* IndexDefinition.swift */; };
56F89E002A57EB5C002FE2AA /* TableAlteration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DFF2A57EB5C002FE2AA /* TableAlteration.swift */; };
56F89E022A57EB87002FE2AA /* Database+SchemaDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E012A57EB87002FE2AA /* Database+SchemaDefinition.swift */; };
56F89E0C2A57EC16002FE2AA /* SQLTableGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E0B2A57EC16002FE2AA /* SQLTableGenerator.swift */; };
56F89E0E2A57EC2B002FE2AA /* SQLColumnGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E0D2A57EC2B002FE2AA /* SQLColumnGenerator.swift */; };
56F89E152A585C0B002FE2AA /* SQLTableAlterationGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */; };
56FA0C3028B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */; };
56FA0C3928B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */; };
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
@@ -408,6 +439,10 @@
56012B742574048B00B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = "<group>"; };
560233C32724234F00529DF3 /* SharedValueObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservation.swift; sourceTree = "<group>"; };
560233C82724338800529DF3 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = "<group>"; };
5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONFunctions.swift; sourceTree = "<group>"; };
5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONExpressible.swift; sourceTree = "<group>"; };
5603CEB82AC862EC00CF097D /* JSONColumn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumn.swift; sourceTree = "<group>"; };
5603CEC92AC8631600CF097D /* JSONExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONExpressionsTests.swift; sourceTree = "<group>"; };
56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = "<group>"; };
560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = "<group>"; };
5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = "<group>"; };
@@ -448,6 +483,9 @@
561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = "<group>"; };
561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = "<group>"; };
561CFA9B2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = "<group>"; };
561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = "<group>"; };
561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = "<group>"; };
561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = "<group>"; };
562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = "<group>"; };
5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = "<group>"; };
5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = "<group>"; };
@@ -455,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>"; };
@@ -493,6 +533,7 @@
563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReceiveValuesOn.swift; sourceTree = "<group>"; };
563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OnDemandFuture.swift; sourceTree = "<group>"; };
563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = "<group>"; };
563CBBE02A595131008905CE /* SQLIndexGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIndexGenerator.swift; sourceTree = "<group>"; };
563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = "<group>"; };
563EF414215F87EB007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = "<group>"; };
563EF42C2161180D007DAACD /* AssociationAggregate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationAggregate.swift; sourceTree = "<group>"; };
@@ -514,6 +555,7 @@
56419A6C24A51601004967E1 /* Support.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Support.swift; sourceTree = "<group>"; };
56419A6D24A51601004967E1 /* DatabaseRegionObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationPublisherTests.swift; sourceTree = "<group>"; };
56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationPublisherTests.swift; sourceTree = "<group>"; };
5642A3172AD66DFE0065F717 /* LineDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LineDumpFormat.swift; sourceTree = "<group>"; };
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = "<group>"; };
@@ -612,15 +654,25 @@
56781B0A243F86E600650A83 /* Refinable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Refinable.swift; sourceTree = "<group>"; };
5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueWriteOnlyObserver.swift; sourceTree = "<group>"; };
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = "<group>"; };
567B5BDB2AD3283500629622 /* DatabaseReaderDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderDumpTests.swift; sourceTree = "<group>"; };
567B5BDC2AD3283500629622 /* DatabaseDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDumpTests.swift; sourceTree = "<group>"; };
567B5BE02AD3284100629622 /* DatabaseReader+dump.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseReader+dump.swift"; sourceTree = "<group>"; };
567B5BE12AD3284100629622 /* DumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DumpFormat.swift; sourceTree = "<group>"; };
567B5BE32AD3284100629622 /* QuoteDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QuoteDumpFormat.swift; sourceTree = "<group>"; };
567B5BE42AD3284100629622 /* JSONDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONDumpFormat.swift; sourceTree = "<group>"; };
567B5BE52AD3284100629622 /* DebugDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DebugDumpFormat.swift; sourceTree = "<group>"; };
567B5BE62AD3284100629622 /* Database+Dump.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Database+Dump.swift"; sourceTree = "<group>"; };
567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = "<group>"; };
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
56848972242DE36F002F9702 /* ValueObservationScheduler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationScheduler.swift; sourceTree = "<group>"; };
5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ListDumpFormat.swift; sourceTree = "<group>"; };
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
56894F742606576600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = "<group>"; };
56894F94260657D600268F4D /* Decimal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = "<group>"; };
568C3F792A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = "<group>"; };
568D13182207213E00674B58 /* SQLQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQueryGenerator.swift; sourceTree = "<group>"; };
568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPool.swift; sourceTree = "<group>"; };
568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = "<group>"; };
@@ -719,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>"; };
@@ -785,6 +838,14 @@
56F61DD0283D344D00AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "GRDBTests-Bridging-Header.h"; path = "GRDBTests/GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
56F61DD3283D344E00AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = "<group>"; };
56F61DD4283D344E00AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
56F89DF62A57EAA9002FE2AA /* ColumnDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnDefinition.swift; sourceTree = "<group>"; };
56F89DFB2A57EAEA002FE2AA /* ForeignKeyDefinition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinition.swift; sourceTree = "<group>"; };
56F89DFD2A57EB19002FE2AA /* IndexDefinition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IndexDefinition.swift; sourceTree = "<group>"; };
56F89DFF2A57EB5C002FE2AA /* TableAlteration.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableAlteration.swift; sourceTree = "<group>"; };
56F89E012A57EB87002FE2AA /* Database+SchemaDefinition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+SchemaDefinition.swift"; sourceTree = "<group>"; };
56F89E0B2A57EC16002FE2AA /* SQLTableGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLTableGenerator.swift; sourceTree = "<group>"; };
56F89E0D2A57EC2B002FE2AA /* SQLColumnGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLColumnGenerator.swift; sourceTree = "<group>"; };
56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLTableAlterationGenerator.swift; sourceTree = "<group>"; };
56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Upsert.swift"; sourceTree = "<group>"; };
56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Upsert.swift"; sourceTree = "<group>"; };
56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
@@ -794,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>"; };
@@ -822,6 +884,25 @@
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
5603CEB52AC862EC00CF097D /* JSON */ = {
isa = PBXGroup;
children = (
5603CEB82AC862EC00CF097D /* JSONColumn.swift */,
5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */,
5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */,
);
path = JSON;
sourceTree = "<group>";
};
5603CEC82AC8630300CF097D /* JSON */ = {
isa = PBXGroup;
children = (
561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */,
5603CEC92AC8631600CF097D /* JSONExpressionsTests.swift */,
);
name = JSON;
sourceTree = "<group>";
};
5605F1471C672E4000235C62 /* Support */ = {
isa = PBXGroup;
children = (
@@ -901,6 +982,7 @@
isa = PBXGroup;
children = (
D263F40926C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift */,
561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */,
5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */,
56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */,
566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */,
@@ -928,12 +1010,14 @@
56176C581EACC2D8000F3F2B /* GRDBTests */ = {
isa = PBXGroup;
children = (
56677C14241D14450050755D /* FailureTestCase.swift */,
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
562EA81E1F17B26F00FA528C /* Compilation */,
56A238111B9C74A90082EB20 /* Core */,
56677C14241D14450050755D /* FailureTestCase.swift */,
567B5BDA2AD3281B00629622 /* Dump */,
5698AC3E1DA2BEBB0056AF8C /* FTS */,
56176CA01EACEE2A000F3F2B /* GRDBCipher */,
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
5603CEC82AC8630300CF097D /* JSON */,
56A238231B9C74A90082EB20 /* Migrations */,
569978D31B539038005EBEED /* Private */,
56300B5C1C53C38F005A543B /* QueryInterface */,
@@ -1009,6 +1093,7 @@
56012B542573EED000B4925B /* CommonTableExpressionTests.swift */,
56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */,
56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */,
568C3F792A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift */,
56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */,
5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */,
563EF45221631E21007DAACD /* QueryInterfacePromiseTests.swift */,
@@ -1048,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;
@@ -1172,6 +1259,11 @@
5656A8142295AF75001FF3FF /* Schema */ = {
isa = PBXGroup;
children = (
56F89DF62A57EAA9002FE2AA /* ColumnDefinition.swift */,
56F89E012A57EB87002FE2AA /* Database+SchemaDefinition.swift */,
56F89DFB2A57EAEA002FE2AA /* ForeignKeyDefinition.swift */,
56F89DFD2A57EB19002FE2AA /* IndexDefinition.swift */,
56F89DFF2A57EB5C002FE2AA /* TableAlteration.swift */,
566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */,
5698AC771DA37DCB0056AF8C /* VirtualTableModule.swift */,
);
@@ -1181,8 +1273,12 @@
5656A8162295AFD6001FF3FF /* SQLGeneration */ = {
isa = PBXGroup;
children = (
56F89E0D2A57EC2B002FE2AA /* SQLColumnGenerator.swift */,
5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */,
563CBBE02A595131008905CE /* SQLIndexGenerator.swift */,
568D13182207213E00674B58 /* SQLQueryGenerator.swift */,
56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */,
56F89E0B2A57EC16002FE2AA /* SQLTableGenerator.swift */,
);
path = SQLGeneration;
sourceTree = "<group>";
@@ -1248,6 +1344,7 @@
5674A7251F30A8EF0095F066 /* FetchableRecord */ = {
isa = PBXGroup;
children = (
561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */,
5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */,
5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */,
565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */,
@@ -1255,6 +1352,38 @@
name = FetchableRecord;
sourceTree = "<group>";
};
567B5BDA2AD3281B00629622 /* Dump */ = {
isa = PBXGroup;
children = (
567B5BDC2AD3283500629622 /* DatabaseDumpTests.swift */,
567B5BDB2AD3283500629622 /* DatabaseReaderDumpTests.swift */,
);
name = Dump;
sourceTree = "<group>";
};
567B5BDF2AD3284100629622 /* Dump */ = {
isa = PBXGroup;
children = (
567B5BE62AD3284100629622 /* Database+Dump.swift */,
567B5BE02AD3284100629622 /* DatabaseReader+dump.swift */,
567B5BE12AD3284100629622 /* DumpFormat.swift */,
567B5BE22AD3284100629622 /* DumpFormats */,
);
path = Dump;
sourceTree = "<group>";
};
567B5BE22AD3284100629622 /* DumpFormats */ = {
isa = PBXGroup;
children = (
567B5BE32AD3284100629622 /* QuoteDumpFormat.swift */,
567B5BE42AD3284100629622 /* JSONDumpFormat.swift */,
5642A3172AD66DFE0065F717 /* LineDumpFormat.swift */,
5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */,
567B5BE52AD3284100629622 /* DebugDumpFormat.swift */,
);
path = DumpFormats;
sourceTree = "<group>";
};
569530FA1C9067CC00CF1A2B /* Crash */ = {
isa = PBXGroup;
children = (
@@ -1425,6 +1554,7 @@
children = (
564E73DE203D50B9000C443C /* JoinSupportTests.swift */,
5616B4FA28B5F5220052017E /* SingletonRecordTest.swift */,
56B6AB052BD3DCAC009A0B71 /* SingletonUserDefaultsTest.swift */,
5674A7251F30A8EF0095F066 /* FetchableRecord */,
560B3FA41C19DFF800C58EC7 /* PersistableRecord */,
56176C9E1EACEDF9000F3F2B /* Record */,
@@ -1612,8 +1742,11 @@
children = (
56A2FA3524424D2A00E97D23 /* Export.swift */,
566DDE0C288D763C0000DCFB /* Fixits.swift */,
648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */,
56A2386F1B9C75030082EB20 /* Core */,
567B5BDF2AD3284100629622 /* Dump */,
5698AC291D9E5A480056AF8C /* FTS */,
5603CEB52AC862EC00CF097D /* JSON */,
56A238911B9C750B0082EB20 /* Migration */,
56300B6D1C53F592005A543B /* QueryInterface */,
56A2389F1B9C753B0082EB20 /* Record */,
@@ -1746,6 +1879,7 @@
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
565498612B8B815500585804 /* PrivacyInfo.xcprivacy in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -1798,6 +1932,7 @@
56DA7CF7260FA9D400A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */,
56D496691D813086008276D7 /* QueryInterfaceExpressionsTests.swift in Sources */,
562393691DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */,
567B5C532AD32FF100629622 /* DatabaseDumpTests.swift in Sources */,
562205F21E420E47005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */,
56D496B01D813385008276D7 /* DatabaseErrorTests.swift in Sources */,
56176C5C1EACCCC7000F3F2B /* FTS5TableBuilderTests.swift in Sources */,
@@ -1809,6 +1944,7 @@
56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */,
560714E3227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */,
56D496841D813147008276D7 /* SelectStatementTests.swift in Sources */,
561F38D82AC88A550051EEE9 /* JSONColumnTests.swift in Sources */,
56D496B11D8133BC008276D7 /* DatabaseQueueReadOnlyTests.swift in Sources */,
56D4968C1D81316E008276D7 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
56419C6D24A519A2004967E1 /* ValueObservationPublisherTests.swift in Sources */,
@@ -1823,6 +1959,7 @@
56D496BF1D8135D4008276D7 /* TableDefinitionTests.swift in Sources */,
5674A7171F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */,
56D496801D813131008276D7 /* StatementColumnConvertibleFetchTests.swift in Sources */,
5603CED42AC8642F00CF097D /* JSONExpressionsTests.swift in Sources */,
563B0705218627F800B38F35 /* ValueObservationRowTests.swift in Sources */,
56D4966E1D81309E008276D7 /* RecordPrimaryKeyMultipleTests.swift in Sources */,
56D496891D81316E008276D7 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
@@ -1882,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 */,
@@ -1900,6 +2038,7 @@
56D496B81D813465008276D7 /* DataMemoryTests.swift in Sources */,
563B06CA2185D2E500B38F35 /* ValueObservationFetchTests.swift in Sources */,
56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */,
561F38F42AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */,
56D496961D81317B008276D7 /* PersistableRecordTests.swift in Sources */,
5616B4FB28B5F5220052017E /* SingletonRecordTest.swift in Sources */,
56419C5724A51998004967E1 /* Inverted.swift in Sources */,
@@ -1910,6 +2049,7 @@
56057C552291B16A00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */,
56FEB8F8248403000081AF83 /* DatabaseTraceTests.swift in Sources */,
56419C5124A51998004967E1 /* Finished.swift in Sources */,
561F38EF2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */,
56176C5E1EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */,
564D4F7E261C6DC200F55856 /* CaseInsensitiveIdentifierTests.swift in Sources */,
56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */,
@@ -1926,6 +2066,7 @@
562393601DEE06D300A6B01F /* CursorTests.swift in Sources */,
5653EAE420944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */,
56D4968F1D81316E008276D7 /* RowFromDictionaryTests.swift in Sources */,
567B5C542AD32FF100629622 /* DatabaseReaderDumpTests.swift in Sources */,
56915782231BF28B00E1D237 /* PoolTests.swift in Sources */,
56419C6C24A519A2004967E1 /* DatabaseRegionObservationPublisherTests.swift in Sources */,
56D4968E1D81316E008276D7 /* RowCopiedFromStatementTests.swift in Sources */,
@@ -1948,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 */,
@@ -1963,6 +2106,7 @@
56D496C11D81373A008276D7 /* DatabaseQueueBackupTests.swift in Sources */,
562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */,
56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */,
568C3F7A2A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift in Sources */,
56D496701D81309E008276D7 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
5622060C1E420EB3005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */,
56E5D8041B4D424400430942 /* GRDBTestCase.swift in Sources */,
@@ -2018,6 +2162,7 @@
files = (
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */,
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
5685C1932AD52EE600DA4B7A /* ListDumpFormat.swift in Sources */,
56158780288D875E00A67323 /* Optional.swift in Sources */,
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */,
5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
@@ -2051,6 +2196,7 @@
563082E42430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */,
564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
5698AD351DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
56F89DFE2A57EB19002FE2AA /* IndexDefinition.swift in Sources */,
566B91131FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
5605F1591C672E4000235C62 /* CGFloat.swift in Sources */,
5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
@@ -2065,11 +2211,13 @@
563B8FB524A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */,
564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
567B5BE72AD3284100629622 /* DatabaseReader+dump.swift in Sources */,
5659F4981EA8D989004A4992 /* Pool.swift in Sources */,
56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */,
5674A6F41F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */,
5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */,
56D110DD28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */,
56F89E022A57EB87002FE2AA /* Database+SchemaDefinition.swift in Sources */,
567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */,
5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */,
563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */,
@@ -2083,6 +2231,8 @@
4E13D2F32769B87F0037588C /* DatabaseBackupProgress.swift in Sources */,
560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
563B8FAC24A1CE43007A48C9 /* DatabasePublishers.swift in Sources */,
56F89E0C2A57EC16002FE2AA /* SQLTableGenerator.swift in Sources */,
56F89DFC2A57EAEA002FE2AA /* ForeignKeyDefinition.swift in Sources */,
56FA0C3028B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */,
5605F1691C672E4000235C62 /* NSString.swift in Sources */,
560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
@@ -2090,6 +2240,7 @@
56CEB5011EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
56D110C928AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */,
56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
567B5BEA2AD3284100629622 /* JSONDumpFormat.swift in Sources */,
56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */,
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */,
56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
@@ -2098,10 +2249,12 @@
56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */,
5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
56A238A41B9C753B0082EB20 /* Record.swift in Sources */,
567B5BE92AD3284100629622 /* QuoteDumpFormat.swift in Sources */,
56CEB5451EAA359A00BFAF62 /* Column.swift in Sources */,
5657AB0F1D10899D006283EF /* URL.swift in Sources */,
560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */,
56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */,
56F89E152A585C0B002FE2AA /* SQLTableAlterationGenerator.swift in Sources */,
56AFEF2F29969F6E00CA1E51 /* TransactionClock.swift in Sources */,
5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */,
56D91AA92205F2F100770D8D /* DatabasePromise.swift in Sources */,
@@ -2115,8 +2268,11 @@
56D110C428AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */,
5690C3401D23E82A00E59934 /* Data.swift in Sources */,
5659F4881EA8D94E004A4992 /* Utils.swift in Sources */,
567B5BE82AD3284100629622 /* DumpFormat.swift in Sources */,
566BE71E2342542F00A8254B /* LockedBox.swift in Sources */,
56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
5603CEBB2AC862EC00CF097D /* SQLJSONExpressible.swift in Sources */,
56F89DF72A57EAA9002FE2AA /* ColumnDefinition.swift in Sources */,
5611620825757583007AAF99 /* JoinAssociation.swift in Sources */,
5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */,
560233C42724234F00529DF3 /* SharedValueObservation.swift in Sources */,
@@ -2124,8 +2280,10 @@
568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */,
5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */,
56894FB72606589700268F4D /* Decimal.swift in Sources */,
56F89E002A57EB5C002FE2AA /* TableAlteration.swift in Sources */,
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */,
56F89E0E2A57EC2B002FE2AA /* SQLColumnGenerator.swift in Sources */,
563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */,
564CE43121AA901800652B19 /* ValueConcurrentObserver.swift in Sources */,
5605F1651C672E4000235C62 /* NSNull.swift in Sources */,
@@ -2142,10 +2300,14 @@
56D110BF28AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */,
566B9C2025C6CC24004542CF /* RowDecodingError.swift in Sources */,
5698AD211DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
5603CEBC2AC862EC00CF097D /* JSONColumn.swift in Sources */,
56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */,
5642A3182AD66DFE0065F717 /* LineDumpFormat.swift in Sources */,
5605F1671C672E4000235C62 /* NSNumber.swift in Sources */,
56E9FADA221053DD00C703A8 /* SQL.swift in Sources */,
5603CEBA2AC862EC00CF097D /* SQLJSONFunctions.swift in Sources */,
56717271261C68E900423B6F /* CaseInsensitiveIdentifier.swift in Sources */,
563CBBE12A595131008905CE /* SQLIndexGenerator.swift in Sources */,
C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */,
56781B0B243F86E600650A83 /* Refinable.swift in Sources */,
56A238871B9C75030082EB20 /* Row.swift in Sources */,
@@ -2158,7 +2320,9 @@
5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
5657AAB91D107001006283EF /* NSData.swift in Sources */,
560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */,
567B5BEC2AD3284100629622 /* Database+Dump.swift in Sources */,
56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
567B5BEB2AD3284100629622 /* DebugDumpFormat.swift in Sources */,
56B9649D1DA51B4C0002DA19 /* FTS5.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
+40
View File
@@ -288,6 +288,46 @@ public struct Configuration {
/// of a read access.
public var allowsUnsafeTransactions = false
// MARK: - Journal Mode
/// Defines how the journal mode is configured when the database
/// connection is opened.
///
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_journal_mode>
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
/// ``wal`` case).
case `default`
/// The journal mode is set to WAL (plus extra configurations that
/// make life easier with WAL databases).
case wal
}
/// Defines how the journal mode is configured when the database
/// connection is opened.
///
/// This configuration is ignored when ``readonly`` is true.
///
/// The default value has ``DatabaseQueue`` perform no specific
/// configuration of the journal mode, and ``DatabasePool`` configure
/// the database for the WAL mode.
///
/// Applications that need to open a WAL database with a
/// ``DatabaseQueue`` should set the `journalMode` to `wal`:
///
/// ```swift
/// // Open a WAL database with DatabaseQueue
/// var config = Configuration()
/// config.journalMode = .wal
/// let dbQueue = try DatabaseQueue(path: "...", configuration: config)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_journal_mode>
public var journalMode = JournalModeConfiguration.default
// MARK: - Concurrency
/// Defines the how `SQLITE_BUSY` errors are handled.
+167 -188
View File
@@ -14,14 +14,9 @@
extension RangeReplaceableCollection {
/// Creates a collection containing the elements of a cursor.
///
/// For example, you can turn a cursor of strings into an array
/// of strings:
///
/// ```swift
/// // Create a [String]
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Array(cursor)
/// ```
/// // [String]
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Array(cursor)
///
/// - parameter cursor: The cursor whose elements feed the collection.
public init(_ cursor: some Cursor<Element>) throws {
@@ -31,14 +26,9 @@ extension RangeReplaceableCollection {
/// Creates a collection containing the elements of a cursor.
///
/// For example, you can turn a cursor of strings into an array
/// of strings:
///
/// ```swift
/// // Create a [String]
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Array(cursor, minimumCapacity: 100)
/// ```
/// // [String]
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Array(cursor, minimumCapacity: 100)
///
/// - parameter cursor: The cursor whose elements feed the collection.
/// - parameter minimumCapacity: Prepares the returned collection to store
@@ -51,8 +41,8 @@ extension RangeReplaceableCollection {
/// Adds the elements of a cursor to the end of this collection.
///
/// - Important: If an error is thrown, an unspecified amount of
/// elements have been added to the collection.
/// In case of error, an unspecified amount of elements have been added to
/// the collection.
///
/// - parameter newElements: The elements to append to the collection.
public mutating func append(contentsOf newElements: some Cursor<Element>) throws {
@@ -68,13 +58,9 @@ extension Dictionary {
/// given closure and whose values are arrays of the elements that returned
/// each key.
///
/// For example:
///
/// ```swift
/// // Create a [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db)
/// let dictionary = try Dictionary(grouping: cursor, by: { $0.teamID })
/// ```
/// // [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db)
/// let dictionary = try Dictionary(grouping: cursor, by: { $0.teamID })
///
/// - parameter cursor: A cursor of values to group into a dictionary.
/// - parameter keyForValue: A closure that returns a key for each element
@@ -95,16 +81,12 @@ extension Dictionary {
/// given closure and whose values are arrays of the elements that returned
/// each key.
///
/// For example:
///
/// ```swift
/// // Create a [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db)
/// let dictionary = try Dictionary(
/// minimumCapacity: 100,
/// grouping: cursor,
/// by: { $0.teamID })
/// ```
/// // [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db)
/// let dictionary = try Dictionary(
/// minimumCapacity: 100,
/// grouping: cursor,
/// by: { $0.teamID })
///
/// - parameter minimumCapacity: The minimum number of key-value pairs that
/// the newly created dictionary should be able to store without
@@ -130,13 +112,9 @@ extension Dictionary {
/// of key-value tuples with unique keys. Passing a cursor with duplicate
/// keys to this initializer results in a fatal error.
///
/// For example:
///
/// ```swift
/// // Create a [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
/// let playerByID = try Dictionary(uniqueKeysWithValues: cursor)
/// ```
/// // [Int64: Player]
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
/// let playerByID = try Dictionary(uniqueKeysWithValues: cursor)
///
/// - parameter keysAndValues: A cursor of key-value pairs to use for the
/// new dictionary. Every key in `keysAndValues` must be unique.
@@ -159,15 +137,11 @@ extension Dictionary {
/// of key-value tuples with unique keys. Passing a cursor with duplicate
/// keys to this initializer results in a fatal error.
///
/// For example:
///
/// ```swift
/// // Create a [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
/// let playerByID = try Dictionary(
/// minimumCapacity: 100,
/// uniqueKeysWithValues: cursor)
/// ```
/// // [Int64: Player]
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
/// let playerByID = try Dictionary(
/// minimumCapacity: 100,
/// uniqueKeysWithValues: cursor)
///
/// - parameter minimumCapacity: The minimum number of key-value pairs that
/// the newly created dictionary should be able to store without
@@ -191,13 +165,9 @@ extension Dictionary {
extension Set {
/// Creates a set containing the elements of a cursor.
///
/// For example, you can turn a cursor of strings into a set of strings:
///
/// ```swift
/// // Create a Set<String>
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Set(cursor)
/// ```
/// // Set<String>
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Set(cursor)
///
/// - parameter cursor: A cursor of values to gather into a set.
public init(_ cursor: some Cursor<Element>) throws {
@@ -210,13 +180,9 @@ extension Set {
/// Creates a set containing the elements of a cursor.
///
/// For example, you can turn a cursor of strings into a set of strings:
///
/// ```swift
/// // Create a Set<String>
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Set(cursor, minimumCapacity: 100)
/// ```
/// // Set<String>
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Set(cursor, minimumCapacity: 100)
///
/// - parameter cursor: A cursor of values to gather into a set.
/// - parameter minimumCapacity: The minimum number of elements that the
@@ -229,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 {
@@ -274,75 +290,6 @@ extension Sequence {
///
/// ## Topics
///
/// ### Iterating Over a Cursor’s Elements
///
/// - ``next()``
/// - ``forEach(_:)-4ib2m``
/// - ``enumerated()``
/// - ``isEmpty``
///
/// ### Finding Elements
///
/// - ``contains(_:)``
/// - ``contains(where:)``
/// - ``first(where:)``
/// - ``min()``
/// - ``min(by:)``
/// - ``max()``
/// - ``max(by:)``
///
/// ### Selecting Elements
///
/// - ``prefix(_:)``
/// - ``prefix(while:)``
/// - ``suffix(_:)``
///
/// ### Excluding Elements
///
/// - ``dropFirst()``
/// - ``dropFirst(_:)``
/// - ``dropLast()``
/// - ``dropLast(_:)``
/// - ``drop(while:)``
/// - ``filter(_:)``
///
/// ### Transforming a Cursor
///
/// - ``map(_:)``
/// - ``compactMap(_:)``
/// - ``flatMap(_:)-5ci2v``
/// - ``flatMap(_:)-8jxlj``
/// - ``reduce(_:_:)``
/// - ``reduce(into:_:)``
///
/// ### Transforming a Sequence into a Cursor
///
/// - ``Swift/Sequence/flatMap(_:)``
///
/// ### Joining Elements
///
/// - ``joined()-5r5ja``
/// - ``joined()-7bnrx``
/// - ``joined(separator:)``
///
/// ### Filling RangeReplaceableCollection with the contents of a Cursor
///
/// - ``Swift/RangeReplaceableCollection/init(_:)``
/// - ``Swift/RangeReplaceableCollection/init(_:minimumCapacity:)``
/// - ``Swift/RangeReplaceableCollection/append(contentsOf:)``
///
/// ### Creating a Dictionary from the contents of a Cursor
///
/// - ``Swift/Dictionary/init(grouping:by:)``
/// - ``Swift/Dictionary/init(minimumCapacity:grouping:by:)``
/// - ``Swift/Dictionary/init(uniqueKeysWithValues:)``
/// - ``Swift/Dictionary/init(minimumCapacity:uniqueKeysWithValues:)``
///
/// ### Creating a Set from the contents of a Cursor
///
/// - ``Swift/Set/init(_:)``
/// - ``Swift/Set/init(_:minimumCapacity:)``
///
/// ### Supporting Types
///
/// - ``AnyCursor``
@@ -372,7 +319,7 @@ extension Cursor {
/// Returns a Boolean value indicating whether the cursor does not contain
/// any element.
///
/// - important: This property consumes an element.
/// - important: This property may consume elements.
public var isEmpty: Bool {
get throws { try next() == nil }
}
@@ -397,17 +344,13 @@ extension Cursor {
/// Returns a cursor of pairs (n, x), where n represents a consecutive
/// integer starting at zero, and x represents an element of the cursor.
///
/// ```swift
/// let cursor = try String.fetchCursor(db, sql: """
/// SELECT 'foo' UNION ALL SELECT 'bar'
/// """)
/// let c = cursor.enumerated()
/// while let (n, x) = c.next() {
/// print("\(n): \(x)")
/// }
/// // Prints: "0: foo"
/// // Prints: "1: bar"
/// ```
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let c = cursor.enumerated()
/// while let (n, x) = c.next() {
/// print("\(n): \(x)")
/// }
/// // Prints: "0: foo"
/// // Prints: "1: bar"
public func enumerated() -> EnumeratedCursor<Self> {
EnumeratedCursor(self)
}
@@ -453,13 +396,11 @@ extension Cursor {
/// If the number of elements to drop exceeds the number of elements in
/// the cursor, the result is an empty cursor.
///
/// ```swift
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropFirst(2))
/// // Prints "[3, 4, 5]"
/// try print(numbers.dropFirst(10))
/// // Prints "[]"
/// ```
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropFirst(2))
/// // Prints "[3, 4, 5]"
/// try print(numbers.dropFirst(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop from the beginning of
/// the cursor. `n` must be greater than or equal to zero.
@@ -473,11 +414,9 @@ extension Cursor {
///
/// The following example drops the first element from a cursor of integers.
///
/// ```swift
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropFirst())
/// // Prints "[2, 3, 4, 5]"
/// ```
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropFirst())
/// // Prints "[2, 3, 4, 5]"
///
/// If the cursor has no elements, the result is an empty cursor.
///
@@ -492,13 +431,11 @@ extension Cursor {
/// The cursor must be finite. If the number of elements to drop exceeds
/// the number of elements in the cursor, the result is an empty array.
///
/// ```swift
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropLast(2))
/// // Prints "[1, 2, 3]"
/// try print(numbers.dropLast(10))
/// // Prints "[]"
/// ```
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropLast(2))
/// // Prints "[1, 2, 3]"
/// try print(numbers.dropLast(10))
/// // Prints "[]"
///
/// - Parameter n: The number of elements to drop off the end of the
/// cursor. `n` must be greater than or equal to zero.
@@ -527,11 +464,9 @@ extension Cursor {
///
/// The following example drops the last element from a cursor of integers.
///
/// ```swift
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropLast())
/// // Prints "[1, 2, 3, 4]"
/// ```
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.dropLast())
/// // Prints "[1, 2, 3, 4]"
///
/// If the cursor has no elements, the result is an empty cursor.
///
@@ -617,13 +552,11 @@ extension Cursor {
/// If the maximum length exceeds the number of elements in the cursor,
/// the result contains all the elements in the cursor.
///
/// ```swift
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.prefix(2))
/// // Prints "[1, 2]"
/// try print(numbers.prefix(10))
/// // Prints "[1, 2, 3, 4, 5]"
/// ```
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.prefix(2))
/// // Prints "[1, 2]"
/// try print(numbers.prefix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
@@ -679,13 +612,11 @@ extension Cursor {
/// elements in the cursor, the result contains all the elements in the
/// cursor.
///
/// ```swift
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.suffix(2))
/// // Prints "[4, 5]"
/// try print(numbers.suffix(10))
/// // Prints "[1, 2, 3, 4, 5]"
/// ```
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
/// try print(numbers.suffix(2))
/// // Prints "[4, 5]"
/// try print(numbers.suffix(10))
/// // Prints "[1, 2, 3, 4, 5]"
///
/// - Parameter maxLength: The maximum number of elements to return. The
/// value of `maxLength` must be greater than or equal to zero.
@@ -739,16 +670,24 @@ extension Cursor where Element: Equatable {
extension Cursor where Element: Comparable {
/// Returns the maximum element in the cursor.
///
/// - Returns: The cursor's maximum element. If the cursor has no
/// elements, returns `nil`.
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
/// if its first argument should be ordered before its second
/// argument; otherwise, `false`.
/// - Returns: The cursor's maximum element, according to
/// `areInIncreasingOrder`. If the cursor has no elements, returns
/// `nil`.
public func max() throws -> Element? {
try max(by: <)
}
/// Returns the minimum element in the cursor.
///
/// - Returns: The cursor's minimum element. If the cursor has no
/// elements, returns `nil`.
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
/// if its first argument should be ordered before its second
/// argument; otherwise, `false`.
/// - Returns: The cursor's minimum element, according to
/// `areInIncreasingOrder`. If the cursor has no elements, returns
/// `nil`.
public func min() throws -> Element? {
try min(by: <)
}
@@ -844,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> {
@@ -858,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 {
@@ -884,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 {
@@ -929,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 }
@@ -986,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 {
@@ -1012,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 }
@@ -1038,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 }
@@ -1065,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() {
+238 -65
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
@@ -354,13 +428,13 @@ extension Database {
// FIXME: We ignore the exception, and consider all INTEGER primary
// keys as aliases for the rowid:
if pkColumn.type.uppercased() == "INTEGER" {
primaryKey = .rowID(pkColumn.name)
primaryKey = .rowID(pkColumn)
} else {
primaryKey = try .regular([pkColumn.name], tableHasRowID: tableHasRowID(table))
primaryKey = try .regular([pkColumn], tableHasRowID: tableHasRowID(table))
}
default:
// Multi-columns primary key
primaryKey = try .regular(pkColumns.map(\.name), tableHasRowID: tableHasRowID(table))
primaryKey = try .regular(pkColumns, tableHasRowID: tableHasRowID(table))
}
schemaCache[table.schemaID].set(primaryKey: .value(primaryKey), forTable: table.name)
@@ -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?
@@ -858,8 +1008,22 @@ public struct ColumnInfo: FetchableRecord {
///
/// The casing of this string depends on the SQLite version: make sure you
/// process this string in a case-insensitive way.
///
/// The type is the empty string when the column has no declared type.
public let type: String
/// The column data type (nil when the column has no declared type).
///
/// The casing of the raw value depends on the SQLite version: make sure
/// you process the result in a case-insensitive way.
var columnType: Database.ColumnType? {
if type.isEmpty {
return nil
} else {
return Database.ColumnType(rawValue: type)
}
}
/// A boolean value indicating if the column is constrained to be not null.
public let isNotNull: Bool
@@ -912,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) {
@@ -955,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:
///
@@ -994,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
@@ -1009,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.
@@ -1099,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:
@@ -1143,29 +1307,29 @@ extension ForeignKeyViolation: CustomStringConvertible {
/// pk.rowIDColumn // nil
/// pk.isRowID // false
/// ```
public struct PrimaryKeyInfo {
public struct PrimaryKeyInfo: Sendable {
private enum Impl {
/// The hidden rowID.
case hiddenRowID
/// An INTEGER PRIMARY KEY column that aliases the Row ID.
/// Associated string is the column name.
case rowID(String)
case rowID(ColumnInfo)
/// Any primary key, but INTEGER PRIMARY KEY.
/// Associated strings are column names.
case regular(columns: [String], tableHasRowID: Bool)
case regular(columnInfos: [ColumnInfo], tableHasRowID: Bool)
}
private let impl: Impl
static func rowID(_ column: String) -> PrimaryKeyInfo {
PrimaryKeyInfo(impl: .rowID(column))
static func rowID(_ columnInfo: ColumnInfo) -> PrimaryKeyInfo {
PrimaryKeyInfo(impl: .rowID(columnInfo))
}
static func regular(_ columns: [String], tableHasRowID: Bool) -> PrimaryKeyInfo {
assert(!columns.isEmpty)
return PrimaryKeyInfo(impl: .regular(columns: columns, tableHasRowID: tableHasRowID))
static func regular(_ columnInfos: [ColumnInfo], tableHasRowID: Bool) -> PrimaryKeyInfo {
assert(!columnInfos.isEmpty)
return PrimaryKeyInfo(impl: .regular(columnInfos: columnInfos, tableHasRowID: tableHasRowID))
}
static let hiddenRowID = PrimaryKeyInfo(impl: .hiddenRowID)
@@ -1175,21 +1339,34 @@ public struct PrimaryKeyInfo {
switch impl {
case .hiddenRowID:
return [Column.rowID.name]
case let .rowID(column):
return [column]
case let .regular(columns: columns, tableHasRowID: _):
return columns
case let .rowID(columnInfo):
return [columnInfo.name]
case let .regular(columnInfos: columnInfos, tableHasRowID: _):
return columnInfos.map(\.name)
}
}
/// The columns in the primary key. Nil if the primary key is the
/// hidden rowID. Never empty otherwise.
var columnInfos: [ColumnInfo]? {
switch impl {
case .hiddenRowID:
return nil
case let .rowID(columnInfo):
return [columnInfo]
case let .regular(columnInfos: columnInfos, tableHasRowID: _):
return columnInfos
}
}
/// When not nil, the name of the column that contains the
/// `INTEGER PRIMARY KEY`.
public var rowIDColumn: String? {
switch impl {
case .hiddenRowID:
return nil
case .rowID(let column):
return column
case .rowID(let columnInfo):
return columnInfo.name
case .regular:
return nil
}
@@ -1216,7 +1393,7 @@ public struct PrimaryKeyInfo {
return true
case .rowID:
return true
case let .regular(columns: _, tableHasRowID: tableHasRowID):
case let .regular(columnInfos: _, tableHasRowID: tableHasRowID):
return tableHasRowID
}
}
@@ -1252,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
@@ -1316,10 +1493,6 @@ struct TableInfo: FetchableRecord {
/// A value in the `type` column of `sqlite_master`.
struct SchemaObjectType: Hashable, RawRepresentable, DatabaseValueConvertible {
var rawValue: String
init(rawValue: String) {
self.rawValue = rawValue
}
static let index = SchemaObjectType(rawValue: "index")
static let table = SchemaObjectType(rawValue: "table")
static let trigger = SchemaObjectType(rawValue: "trigger")
@@ -1344,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).
+6 -1
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 {
@@ -373,7 +378,7 @@ extension SQLStatementCursor: Cursor {
let baseAddress = buffer.baseAddress! // never nil because the buffer contains the trailing \0.
// Compile next statement
var statementEnd: UnsafePointer<Int8>? = nil
var statementEnd: UnsafePointer<CChar>? = nil
let statement = try Statement(
database: database,
statementStart: baseAddress + offset,
+236 -95
View File
@@ -60,16 +60,28 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``inSavepoint(_:)``
/// - ``inTransaction(_:_:)``
/// - ``isInsideTransaction``
/// - ``readOnly(_:)``
/// - ``rollback()``
/// - ``transactionDate``
/// - ``TransactionCompletion``
/// - ``TransactionKind``
///
/// ### Printing Database Content
///
/// - ``dumpContent(format:to:)``
/// - ``dumpRequest(_:format:to:)``
/// - ``dumpSchema(to:)``
/// - ``dumpSQL(_:format:to:)``
/// - ``dumpTables(_:format:tableHeader:stableOrder:to:)``
/// - ``DumpFormat``
/// - ``DumpTableHeaderOptions``
///
/// ### Database Observation
///
/// - ``add(transactionObserver:extent:)``
/// - ``remove(transactionObserver:)``
/// - ``afterNextTransaction(onCommit:onRollback:)``
/// - ``notifyChanges(in:)``
/// - ``registerAccess(to:)``
///
/// ### Collations
@@ -103,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 {
@@ -111,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
@@ -421,6 +432,41 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
configuration.SQLiteConnectionDidOpen?()
}
/// Performs ``Configuration/JournalModeConfiguration/wal``.
func setUpWALMode() throws {
let journalMode = try String.fetchOne(self, sql: "PRAGMA journal_mode = WAL")
guard journalMode == "wal" else {
throw DatabaseError(message: "could not activate WAL Mode at path: \(path)")
}
// https://www.sqlite.org/pragma.html#pragma_synchronous
// > Many applications choose NORMAL when in WAL mode
try execute(sql: "PRAGMA synchronous = NORMAL")
// Make sure a non-empty wal file exists.
//
// The presence of the wal file avoids an SQLITE_CANTOPEN (14)
// error when the user opens a pool and reads from it.
// See <https://github.com/groue/GRDB.swift/issues/102>.
//
// The non-empty wal file avoids an SQLITE_ERROR (1) error
// when the user opens a pool and creates a wal snapshot
// (which happens when starting a ValueObservation).
// See <https://github.com/groue/GRDB.swift/issues/1383>.
let walPath = path + "-wal"
if try FileManager.default.fileExists(atPath: walPath) == false
|| (URL(fileURLWithPath: walPath).resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) == 0
{
try inSavepoint {
try execute(sql: """
CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY);
DROP TABLE grdb_issue_102;
""")
return .commit
}
}
}
private func setupDoubleQuotedStringLiterals() {
if configuration.acceptsDoubleQuotedStringLiterals {
_enableDoubleQuotedStringLiterals(sqliteConnection)
@@ -727,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)
}
@@ -745,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
@@ -756,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
@@ -776,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.
@@ -860,31 +994,16 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
self.trace = trace
if options.isEmpty || trace == nil {
#if os(Linux)
sqlite3_trace(sqliteConnection, nil)
#else
sqlite3_trace_v2(sqliteConnection, 0, nil, nil)
#endif
return
}
// sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0
// http://www.sqlite.org/changes.html#version_3_14
#if os(Linux)
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
guard let sql = sql.map(String.init(cString:)) else { return }
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.trace?(Database.TraceEvent.statement(TraceEvent.Statement(impl: .trace_v1(sql))))
}, dbPointer)
#else
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(sqliteConnection, CUnsignedInt(bitPattern: options.rawValue), { (mask, dbPointer, p, x) in
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.trace_v2(CInt(bitPattern: mask), p, x, sqlite3_expanded_sql)
return SQLITE_OK
}, dbPointer)
#endif
}
// Precondition: configuration.trace != nil
@@ -892,7 +1011,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
_ mask: CInt,
_ p: UnsafeMutableRawPointer?,
_ x: UnsafeMutableRawPointer?,
_ sqlite3_expanded_sql: @escaping @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
_ sqlite3_expanded_sql: @escaping @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<CChar>?)
{
guard let trace else { return }
@@ -900,26 +1019,22 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
case SQLITE_TRACE_STMT:
if let sqliteStatement = p, let unexpandedSQL = x {
let statement = TraceEvent.Statement(
impl: .trace_v2(
sqliteStatement: OpaquePointer(sqliteStatement),
unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)),
sqlite3_expanded_sql: sqlite3_expanded_sql,
publicStatementArguments: configuration.publicStatementArguments))
sqliteStatement: OpaquePointer(sqliteStatement),
unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)),
sqlite3_expanded_sql: sqlite3_expanded_sql,
publicStatementArguments: configuration.publicStatementArguments)
trace(TraceEvent.statement(statement))
}
case SQLITE_TRACE_PROFILE:
if let sqliteStatement = p, let durationP = x?.assumingMemoryBound(to: Int64.self) {
let statement = TraceEvent.Statement(
impl: .trace_v2(
sqliteStatement: OpaquePointer(sqliteStatement),
unexpandedSQL: nil,
sqlite3_expanded_sql: sqlite3_expanded_sql,
publicStatementArguments: configuration.publicStatementArguments))
sqliteStatement: OpaquePointer(sqliteStatement),
unexpandedSQL: nil,
sqlite3_expanded_sql: sqlite3_expanded_sql,
publicStatementArguments: configuration.publicStatementArguments)
let duration = TimeInterval(durationP.pointee) / 1.0e9
#if !os(Linux)
trace(TraceEvent.profile(statement: statement, duration: duration))
#endif
}
default:
break
@@ -1140,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
@@ -1460,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()
@@ -1616,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 {
@@ -1741,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
@@ -1760,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.
@@ -1797,7 +1919,7 @@ 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
@@ -1809,6 +1931,14 @@ extension Database {
/// The `TEXT` column type.
public static let text = ColumnType(rawValue: "TEXT")
/// The `TEXT` column type, suitable for JSON columns.
///
/// SQLite JSON functions and operators are
/// [documented](https://www.sqlite.org/json1.html#interface_overview)
/// to throw errors if any of their arguments are binary blobs.
/// That's the reason why it is recommended to store JSON as text.
public static let jsonText = ColumnType(rawValue: "TEXT")
/// The `INTEGER` column type.
public static let integer = ColumnType(rawValue: "INTEGER")
@@ -1840,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"
@@ -1860,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"
@@ -1877,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
@@ -1897,13 +2053,11 @@ extension Database {
/// Trace event code: `SQLITE_TRACE_STMT`.
public static let statement = TracingOptions(rawValue: SQLITE_TRACE_STMT)
#if !os(Linux)
/// The option that reports executed statements and the estimated
/// duration that the statement took to run.
///
/// Trace event code: `SQLITE_TRACE_PROFILE`.
public static let profile = TracingOptions(rawValue: SQLITE_TRACE_PROFILE)
#endif
}
/// A trace event.
@@ -1914,17 +2068,11 @@ extension Database {
/// Information about an executed statement.
public struct Statement: CustomStringConvertible {
enum Impl {
case trace_v1(String)
case trace_v2(
sqliteStatement: SQLiteStatement,
unexpandedSQL: UnsafePointer<CChar>?,
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?,
publicStatementArguments: Bool) // See Configuration.publicStatementArguments
}
var impl: Impl
var sqliteStatement: SQLiteStatement
var unexpandedSQL: UnsafePointer<CChar>?
var sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<CChar>?
var publicStatementArguments: Bool // See Configuration.publicStatementArguments
#if !os(Linux)
/// The executed SQL, where bound parameters are not expanded.
///
/// For example:
@@ -1932,21 +2080,12 @@ extension Database {
/// ```sql
/// SELECT * FROM player WHERE email = ?
/// ```
public var sql: String { _sql }
#endif
var _sql: String {
switch impl {
case .trace_v1:
// Likely a GRDB bug: this api is not supposed to be available
fatalError("Unavailable statement SQL")
case let .trace_v2(sqliteStatement, unexpandedSQL, _, _):
if let unexpandedSQL {
return String(cString: unexpandedSQL).trimmedSQLStatement
} else {
return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
}
public var sql: String {
if let unexpandedSQL {
let sql = String(cString: unexpandedSQL)
return sql.hasPrefix("--") ? sql : sql.trimmedSQLStatement
} else {
return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
}
}
@@ -1962,30 +2101,22 @@ extension Database {
/// information from leaking in unexpected locations, so use this
/// property with care.
public var expandedSQL: String {
switch impl {
case let .trace_v1(expandedSQL):
return expandedSQL
case let .trace_v2(sqliteStatement, _, sqlite3_expanded_sql, _):
guard let cString = sqlite3_expanded_sql(sqliteStatement) else {
return ""
}
defer { sqlite3_free(cString) }
return String(cString: cString).trimmedSQLStatement
if let unexpandedSQL {
let sql = String(cString: unexpandedSQL)
if sql.hasPrefix("--") { return sql }
}
guard let cString = sqlite3_expanded_sql(sqliteStatement) else {
return ""
}
defer { sqlite3_free(cString) }
return String(cString: cString).trimmedSQLStatement
}
public var description: String {
switch impl {
case let .trace_v1(expandedSQL):
if publicStatementArguments {
return expandedSQL
case let .trace_v2(_, _, _, publicStatementArguments):
if publicStatementArguments {
return expandedSQL
} else {
return _sql
}
} else {
return sql
}
}
}
@@ -2046,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
}
@@ -2054,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"
@@ -2087,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.
+6 -2
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 {
@@ -549,7 +553,7 @@ extension DatabaseError: CustomStringConvertible {
description += ": \(message)"
}
if let sql {
description += " - while executing `\(sql)`"
description += " - while executing `\(sql.trimmedSQLStatement)`"
}
if publicStatementArguments, let arguments, !arguments.isEmpty {
description += " with arguments \(arguments)"
@@ -577,7 +581,7 @@ extension DatabaseError: CustomStringConvertible {
description += ": \(message)"
}
if let sql {
description += " - while executing `\(sql)`"
description += " - while executing `\(sql.trimmedSQLStatement)`"
}
if let arguments, !arguments.isEmpty {
description += " with arguments \(arguments)"
+19 -8
View File
@@ -30,9 +30,9 @@ public final class DatabaseFunction: Hashable {
/// The name of the SQL function
public var name: String { identity.name }
private let identity: Identity
let pure: Bool
let isPure: Bool
private let kind: Kind
private var eTextRep: CInt { (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
private var eTextRep: CInt { (SQLITE_UTF8 | (isPure ? SQLITE_DETERMINISTIC : 0)) }
/// Creates an SQL function.
///
@@ -76,7 +76,7 @@ public final class DatabaseFunction: Hashable {
function: @escaping ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
{
self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
self.pure = pure
self.isPure = pure
self.kind = .function{ (argc, argv) in
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
@@ -140,10 +140,11 @@ public final class DatabaseFunction: Hashable {
aggregate: Aggregate.Type)
{
self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
self.pure = pure
self.isPure = pure
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
@@ -171,13 +172,23 @@ public final class DatabaseFunction: Hashable {
/// ```
public func callAsFunction(_ arguments: any SQLExpressible...) -> SQLExpression {
switch kind {
case .aggregate:
return .function(name, arguments.map(\.sqlExpression))
case .function:
return .aggregate(name, arguments.map(\.sqlExpression))
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) {
+24 -53
View File
@@ -13,6 +13,9 @@ public final class DatabasePool {
@LockedBox var databaseSnapshotCount = 0
/// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers.
private var suspensionObservers: [NSObjectProtocol] = []
// MARK: - Database Information
public var configuration: Configuration {
@@ -72,39 +75,12 @@ public final class DatabasePool {
purpose: "reader.\(readerCount)")
})
// Activate WAL Mode unless readonly
// Set up journal mode unless readonly
if !configuration.readonly {
try writer.sync { db in
let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode = WAL")
guard journalMode == "wal" else {
throw DatabaseError(message: "could not activate WAL Mode at path: \(path)")
}
// https://www.sqlite.org/pragma.html#pragma_synchronous
// > Many applications choose NORMAL when in WAL mode
try db.execute(sql: "PRAGMA synchronous = NORMAL")
// Make sure a non-empty wal file exists.
//
// The presence of the wal file avoids an SQLITE_CANTOPEN (14)
// error when the user opens a pool and reads from it.
// See <https://github.com/groue/GRDB.swift/issues/102>.
//
// The non-empty wal file avoids an SQLITE_ERROR (1) error
// when the user opens a pool and creates a wal snapshot
// (which happens when starting a ValueObservation).
// See <https://github.com/groue/GRDB.swift/issues/1383>.
let walPath = path + "-wal"
if try FileManager.default.fileExists(atPath: walPath) == false
|| (URL(fileURLWithPath: walPath).resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) == 0
{
try db.inSavepoint {
try db.execute(sql: """
CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY);
DROP TABLE grdb_issue_102;
""")
return .commit
}
switch configuration.journalMode {
case .default, .wal:
try writer.sync {
try $0.setUpWALMode()
}
}
}
@@ -121,6 +97,9 @@ public final class DatabasePool {
}
deinit {
// Remove block-based Notification observers.
suspensionObservers.forEach(NotificationCenter.default.removeObserver(_:))
// Undo job done in setupMemoryManagement()
//
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
@@ -169,7 +148,7 @@ public final class DatabasePool {
}
}
// @unchecked because of databaseSnapshotCount and readerPool
// @unchecked because of databaseSnapshotCount, readerPool and suspensionObservers
extension DatabasePool: @unchecked Sendable { }
extension DatabasePool {
@@ -345,29 +324,21 @@ extension DatabasePool: DatabaseReader {
private func setupSuspension() {
if configuration.observesSuspensionNotifications {
let center = NotificationCenter.default
center.addObserver(
self,
selector: #selector(DatabasePool.suspend(_:)),
name: Database.suspendNotification,
object: nil)
center.addObserver(
self,
selector: #selector(DatabasePool.resume(_:)),
name: Database.resumeNotification,
object: nil)
suspensionObservers.append(center.addObserver(
forName: Database.suspendNotification,
object: nil,
queue: nil,
using: { [weak self] _ in self?.suspend() }
))
suspensionObservers.append(center.addObserver(
forName: Database.resumeNotification,
object: nil,
queue: nil,
using: { [weak self] _ in self?.resume() }
))
}
}
@objc
private func suspend(_ notification: Notification) {
suspend()
}
@objc
private func resume(_ notification: Notification) {
resume()
}
// MARK: - Reading from Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
+126 -23
View File
@@ -7,15 +7,15 @@ import UIKit
public final class DatabaseQueue {
private let writer: SerializedDatabase
/// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers.
private var suspensionObservers: [NSObjectProtocol] = []
// MARK: - Configuration
public var configuration: Configuration {
writer.configuration
}
/// The path to the database file.
///
/// The path is `:memory:` for in-memory databases.
public var path: String {
writer.path
}
@@ -47,6 +47,18 @@ public final class DatabaseQueue {
configuration: configuration,
defaultLabel: "GRDB.DatabaseQueue")
// Set up journal mode unless readonly
if !configuration.readonly {
switch configuration.journalMode {
case .default:
break
case .wal:
try writer.sync {
try $0.setUpWALMode()
}
}
}
setupSuspension()
// Be a nice iOS citizen, and don't consume too much memory
@@ -100,6 +112,9 @@ public final class DatabaseQueue {
}
deinit {
// Remove block-based Notification observers.
suspensionObservers.forEach(NotificationCenter.default.removeObserver(_:))
// Undo job done in setupMemoryManagement()
//
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
@@ -108,6 +123,9 @@ public final class DatabaseQueue {
}
}
// @unchecked because of suspensionObservers
extension DatabaseQueue: @unchecked Sendable { }
extension DatabaseQueue {
// MARK: - Memory management
@@ -189,29 +207,21 @@ extension DatabaseQueue: DatabaseReader {
private func setupSuspension() {
if configuration.observesSuspensionNotifications {
let center = NotificationCenter.default
center.addObserver(
self,
selector: #selector(DatabaseQueue.suspend(_:)),
name: Database.suspendNotification,
object: nil)
center.addObserver(
self,
selector: #selector(DatabaseQueue.resume(_:)),
name: Database.resumeNotification,
object: nil)
suspensionObservers.append(center.addObserver(
forName: Database.suspendNotification,
object: nil,
queue: nil,
using: { [weak self] _ in self?.suspend() }
))
suspensionObservers.append(center.addObserver(
forName: Database.resumeNotification,
object: nil,
queue: nil,
using: { [weak self] _ in self?.resume() }
))
}
}
@objc
private func suspend(_ notification: Notification) {
suspend()
}
@objc
private func resume(_ notification: Notification) {
resume()
}
// MARK: - Reading from Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
@@ -419,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
}
}
+21
View File
@@ -17,6 +17,7 @@ import Dispatch
/// ### Database Information
///
/// - ``configuration``
/// - ``path``
///
/// ### Reading from the Database
///
@@ -32,6 +33,16 @@ import Dispatch
/// - ``unsafeReentrantRead(_:)``
/// - ``asyncUnsafeRead(_:)``
///
/// ### Printing Database Content
///
/// - ``dumpContent(format:to:)``
/// - ``dumpRequest(_:format:to:)``
/// - ``dumpSchema(to:)``
/// - ``dumpSQL(_:format:to:)``
/// - ``dumpTables(_:format:tableHeader:stableOrder:to:)``
/// - ``DumpFormat``
/// - ``DumpTableHeaderOptions``
///
/// ### Other Database Operations
///
/// - ``backup(to:pagesPerStep:progress:)``
@@ -46,6 +57,12 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// The database configuration.
var configuration: Configuration { get }
/// The path to the database file.
///
/// In-memory databases also have a path:
/// see [In-Memory Databases](https://www.sqlite.org/inmemorydb.html).
var path: String { get }
/// Closes the database connection.
///
/// - note: You do not have to call this method, and you should not call
@@ -644,6 +661,10 @@ extension AnyDatabaseReader: DatabaseReader {
base.configuration
}
public var path: String {
base.path
}
public func close() throws {
try base.close()
}
+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)
/// ```
///
+2 -1
View File
@@ -44,6 +44,7 @@ import Foundation
/// ### Creating a DatabaseValue
///
/// - ``init(value:)``
/// - ``init(sqliteStatement:index:)``
/// - ``null``
///
/// ### Accessing the SQLite storage
@@ -149,7 +150,7 @@ public struct DatabaseValue: Hashable {
}
/// Creates a `DatabaseValue` initialized from a raw SQLite statement pointer.
init(sqliteStatement: SQLiteStatement, index: CInt) {
public init(sqliteStatement: SQLiteStatement, index: CInt) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_NULL:
storage = .null
+54
View File
@@ -1,3 +1,5 @@
import Foundation
// Standard collections `Array`, `Set`, and `Dictionary` do not conform to
// `DatabaseValueConvertible`, on purpose.
//
@@ -59,6 +61,18 @@ public protocol DatabaseValueConvertible: SQLExpressible, StatementBinding {
///
/// - returns: A decoded value, or, if decoding is impossible, nil.
static func fromMissingColumn() -> Self?
/// Returns the `JSONDecoder` that decodes the value.
///
/// This method is dedicated to ``DatabaseValueConvertible`` types that
/// also conform to the standard `Decodable` protocol.
static func databaseJSONDecoder() -> JSONDecoder
/// Returns the `JSONEncoder` that encodes the value.
///
/// This method is dedicated to ``DatabaseValueConvertible`` types that
/// also conform to the standard `Encodable` protocol.
static func databaseJSONEncoder() -> JSONEncoder
}
extension DatabaseValueConvertible {
@@ -75,6 +89,41 @@ extension DatabaseValueConvertible {
public static func fromMissingColumn() -> Self? {
nil // failure.
}
/// Returns the `JSONDecoder` that decodes the value.
///
/// The default implementation returns a `JSONDecoder` with the
/// following properties:
///
/// - `dataDecodingStrategy`: `.base64`
/// - `dateDecodingStrategy`: `.millisecondsSince1970`
/// - `nonConformingFloatDecodingStrategy`: `.throw`
public static func databaseJSONDecoder() -> JSONDecoder {
let decoder = JSONDecoder()
decoder.dataDecodingStrategy = .base64
decoder.dateDecodingStrategy = .millisecondsSince1970
decoder.nonConformingFloatDecodingStrategy = .throw
return decoder
}
/// Returns the `JSONEncoder` that encodes the value.
///
/// The default implementation returns a `JSONEncoder` with the
/// following properties:
///
/// - `dataEncodingStrategy`: `.base64`
/// - `dateEncodingStrategy`: `.millisecondsSince1970`
/// - `nonConformingFloatEncodingStrategy`: `.throw`
/// - `outputFormatting`: `.sortedKeys`
public static func databaseJSONEncoder() -> JSONEncoder {
let encoder = JSONEncoder()
encoder.dataEncodingStrategy = .base64
encoder.dateEncodingStrategy = .millisecondsSince1970
encoder.nonConformingFloatEncodingStrategy = .throw
// guarantee some stability in order to ease value comparison
encoder.outputFormatting = .sortedKeys
return encoder
}
}
// MARK: - Conversions
@@ -173,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:
///
+30 -4
View File
@@ -445,10 +445,21 @@ extension DatabaseWriter {
// MARK: - Transaction Observers
/// Adds a transaction observer, so that it gets notified of
/// database changes and transactions.
/// Adds a transaction observer to the writer connection, so that it
/// gets notified of database changes and transactions.
///
/// This method has no effect on read-only database connections.
/// This method waits until all currently executing database accesses
/// performed by the writer dispatch queue finish executing.
/// At that point, database observation begins.
///
/// It has no effect on read-only database connections.
///
/// For example:
///
/// ```swift
/// let myObserver = MyObserver()
/// try dbQueue.add(transactionObserver: myObserver)
/// ```
///
/// - parameter transactionObserver: A transaction observer.
/// - parameter extent: The duration of the observation. The default is
@@ -461,7 +472,18 @@ extension DatabaseWriter {
writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) }
}
/// Removes a transaction observer.
/// Removes a transaction observer from the writer connection.
///
/// This method waits until all currently executing database accesses
/// performed by the writer dispatch queue finish executing.
/// At that point, database observation stops.
///
/// For example:
///
/// ```swift
/// let myObserver = MyObserver()
/// try dbQueue.remove(transactionObserver: myObserver)
/// ```
public func remove(transactionObserver: some TransactionObserver) {
writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) }
}
@@ -964,6 +986,10 @@ extension AnyDatabaseWriter: DatabaseReader {
base.configuration
}
public var path: String {
base.path
}
public func close() throws {
try base.close()
}
+30 -2
View File
@@ -107,6 +107,28 @@ extension FetchRequest {
// MARK: - PreparedRequest
/// A closure executed before a supplementary fetch is performed.
///
/// Support for `Database.dumpRequest`.
///
/// - parameter request: The supplementary request
/// - parameter keyPath: The key path target of the supplementary fetch.
typealias WillExecuteSupplementaryRequest = (_ request: AnyFetchRequest<Row>, _ keyPath: [String]) throws -> Void
/// A closure that performs supplementary fetches.
///
/// Support for eager loading of hasMany associations.
///
/// - parameter db: A database connection.
/// - parameter rows: The rows that are modified by the supplementary fetch.
/// - parameter willExecuteSupplementaryRequest: A closure to execute before
/// performing supplementary fetches.
typealias SupplementaryFetch = (
_ db: Database,
_ rows: [Row],
_ willExecuteSupplementaryRequest: WillExecuteSupplementaryRequest?)
throws -> Void
/// A `PreparedRequest` is a request that is ready to be executed.
public struct PreparedRequest {
/// A prepared statement with bound parameters.
@@ -115,13 +137,14 @@ public struct PreparedRequest {
/// An eventual adapter for rows fetched by the select statement.
public var adapter: (any RowAdapter)?
/// A closure that performs supplementary fetches.
/// Support for eager loading of hasMany associations.
var supplementaryFetch: ((Database, [Row]) throws -> Void)?
var supplementaryFetch: SupplementaryFetch?
init(
statement: Statement,
adapter: (any RowAdapter)?,
supplementaryFetch: ((Database, [Row]) throws -> Void)? = nil)
supplementaryFetch: SupplementaryFetch? = nil)
{
self.statement = statement
self.adapter = adapter
@@ -129,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
+15 -4
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
@@ -1739,7 +1750,7 @@ extension Row {
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Row] {
let request = try request.makePreparedRequest(db, forSingleResult: false)
let rows = try fetchAll(request.statement, adapter: request.adapter)
try request.supplementaryFetch?(db, rows)
try request.supplementaryFetch?(db, rows, nil)
return rows
}
@@ -1772,7 +1783,7 @@ extension Row {
let request = try request.makePreparedRequest(db, forSingleResult: false)
if let supplementaryFetch = request.supplementaryFetch {
let rows = try fetchAll(request.statement, adapter: request.adapter)
try supplementaryFetch(db, rows)
try supplementaryFetch(db, rows, nil)
return Set(rows)
} else {
return try fetchSet(request.statement, adapter: request.adapter)
@@ -1809,7 +1820,7 @@ extension Row {
guard let row = try fetchOne(request.statement, adapter: request.adapter) else {
return nil
}
try request.supplementaryFetch?(db, [row])
try request.supplementaryFetch?(db, [row], nil)
return row
}
}
@@ -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>
+3 -5
View File
@@ -39,8 +39,6 @@
///
/// - ``append(literal:)``
/// - ``append(sql:arguments:)``
/// - ``Swift/Collection/joined(separator:)``
/// - ``Swift/Sequence/joined(separator:)``
public struct SQL {
/// `SQL.Element` is a component of an `SQL` literal.
///
@@ -318,12 +316,12 @@ extension SQL: SQLOrderingTerm {
}
extension Sequence where Element == SQL {
/// Concatenates the sequence elements into a new `SQL` literal,
/// Returns the concatenated `SQL` literal of this sequence of literals,
/// inserting the given raw SQL separator between each element.
///
/// For example:
///
/// ```swift
/// ```
/// let components: [SQL] = [
/// "UPDATE player",
/// "SET name = \(name)",
@@ -343,7 +341,7 @@ extension Sequence where Element == SQL {
}
extension Collection where Element == SQL {
/// Concatenates the collection elements into a new `SQL` literal,
/// Returns the concatenated `SQL` literal of this collection of literals,
/// inserting the given raw SQL separator between each element.
///
/// For example:
+14 -8
View File
@@ -42,14 +42,15 @@ public final class Statement {
public var sql: String {
SchedulingWatchdog.preconditionValidQueue(database)
// trim white space and semicolumn for homogeneous output
// trim white space and semicolon for homogeneous output
return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
}
/// The column names, ordered from left to right.
public lazy var columnNames: [String] = {
// swiftlint:disable:next redundant_self_in_closure
let sqliteStatement = self.sqliteStatement
return (0..<CInt(self.columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
return (0..<CInt(columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
}()
// The database region is reported by `sqlite3_set_authorizer`, and maybe
@@ -90,8 +91,8 @@ public final class Statement {
sqlite3_stmt_readonly(sqliteStatement) != 0
}
/// A boolean value indicating if the statement deletes some rows.
var isDeleteStatement: Bool {
/// A boolean value indicating if the statement can delete some rows.
var canDeleteRows: Bool {
authorizerEventKinds.contains(where: \.isDelete)
}
@@ -101,7 +102,7 @@ public final class Statement {
/// Cache for index(ofColumn:). Keys are lowercase.
private lazy var columnIndexes: [String: Int] = {
Dictionary(
self.columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
}()
@@ -118,8 +119,8 @@ public final class Statement {
/// - throws: DatabaseError in case of compilation error.
required init?(
database: Database,
statementStart: UnsafePointer<Int8>,
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
statementStart: UnsafePointer<CChar>,
statementEnd: UnsafeMutablePointer<UnsafePointer<CChar>?>,
prepFlags: CUnsignedInt) throws
{
SchedulingWatchdog.preconditionValidQueue(database)
@@ -222,7 +223,7 @@ public final class Statement {
private var _arguments = StatementArguments()
lazy var sqliteArgumentCount: Int = {
Int(sqlite3_bind_parameter_count(self.sqliteStatement))
Int(sqlite3_bind_parameter_count(sqliteStatement))
}()
// Returns ["id", nil, "name"] for "INSERT INTO table VALUES (:id, ?, :name)"
@@ -622,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"
+9 -5
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
@@ -57,10 +61,10 @@ final class StatementAuthorizer {
private func authorize(
_ actionCode: CInt,
_ cString1: UnsafePointer<Int8>?,
_ cString2: UnsafePointer<Int8>?,
_ cString3: UnsafePointer<Int8>?,
_ cString4: UnsafePointer<Int8>?)
_ cString1: UnsafePointer<CChar>?,
_ cString2: UnsafePointer<CChar>?,
_ cString3: UnsafePointer<CChar>?,
_ cString4: UnsafePointer<CChar>?)
-> CInt
{
// Uncomment when debugging
@@ -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 -1
View File
@@ -1,7 +1,7 @@
#if canImport(CoreGraphics)
import CoreGraphics
/// `CGFloat` is a database value.
/// CGFloat adopts DatabaseValueConvertible
extension CGFloat: DatabaseValueConvertible {
/// Returns a REAL database value.
public var databaseValue: DatabaseValue {
+1 -1
View File
@@ -1,6 +1,6 @@
import Foundation
/// `Data` is a database value.
/// Data is convertible to and from DatabaseValue.
extension Data: DatabaseValueConvertible, StatementColumnConvertible {
public init(sqliteStatement: SQLiteStatement, index: CInt) {
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
@@ -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"
@@ -75,7 +75,7 @@ extension DatabaseDateComponents: StatementColumnConvertible {
}
let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen
let components = cString.withMemoryRebound(
to: Int8.self,
to: CChar.self,
capacity: length + 1 /* trailing \0 */) { cString in
SQLiteDateParser().components(cString: cString, length: length)
}
+4 -2
View File
@@ -1,7 +1,8 @@
import Foundation
#if !os(Linux)
/// `NSDate` is a database value.
/// NSDate is stored in the database using the format
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
extension NSDate: DatabaseValueConvertible {
/// Returns a TEXT database value that contains the date encoded as
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
@@ -30,6 +31,8 @@ extension NSDate: DatabaseValueConvertible {
}
#endif
/// Date is stored in the database using the format
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
extension Date: DatabaseValueConvertible {
/// Returns a TEXT database value that contains the date encoded as
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
@@ -112,7 +115,6 @@ extension Date: DatabaseValueConvertible {
}
}
/// `Date` is a database value.
extension Date: StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
+1 -1
View File
@@ -1,7 +1,7 @@
#if !os(Linux)
import Foundation
/// `Decimal` is a database value.
/// Decimal adopts DatabaseValueConvertible
extension Decimal: DatabaseValueConvertible {
/// Returns a TEXT decimal value.
public var databaseValue: DatabaseValue {
+1 -1
View File
@@ -1,7 +1,7 @@
#if !os(Linux)
import Foundation
/// `NSData` is a database value.
/// NSData is convertible to and from DatabaseValue.
extension NSData: DatabaseValueConvertible {
/// Returns a BLOB database value.
+1 -1
View File
@@ -1,6 +1,6 @@
import Foundation
/// `NSDate` is a database value.
/// NSNull adopts DatabaseValueConvertible
extension NSNull: DatabaseValueConvertible {
/// Returns the NULL database value.
+1 -1
View File
@@ -9,7 +9,7 @@ private let integerRoundingBehavior = NSDecimalNumberHandler(
raiseOnUnderflow: false,
raiseOnDivideByZero: false)
/// `NSNumber` is a database value.
/// NSNumber adopts DatabaseValueConvertible
extension NSNumber: DatabaseValueConvertible {
/// A database value.
+1 -1
View File
@@ -1,7 +1,7 @@
#if !os(Linux)
import Foundation
/// `NSString` is a database value.
/// NSString adopts DatabaseValueConvertible
extension NSString: DatabaseValueConvertible {
/// Returns a TEXT database value.
+2 -6
View File
@@ -1,9 +1,7 @@
import Foundation
#if !os(Linux)
/// `NSURL` is a database value.
///
/// `NSURL` stores its `absoluteString` in the database.
/// NSURL stores its absoluteString in the database.
extension NSURL: DatabaseValueConvertible {
/// Returns a TEXT database value containing the absolute URL.
@@ -20,7 +18,5 @@ extension NSURL: DatabaseValueConvertible {
}
#endif
/// `URL` is a database value.
///
/// `URL` stores its `absoluteString` in the database.
/// URL stores its absoluteString in the database.
extension URL: DatabaseValueConvertible { }
+2 -2
View File
@@ -1,7 +1,7 @@
import Foundation
#if !os(Linux)
/// `NSUUID` is a database value.
/// NSUUID adopts DatabaseValueConvertible
extension NSUUID: DatabaseValueConvertible {
/// Returns a BLOB database value containing the uuid bytes.
public var databaseValue: DatabaseValue {
@@ -35,7 +35,7 @@ extension NSUUID: DatabaseValueConvertible {
}
#endif
/// `UUID` is a database value.
/// UUID adopts DatabaseValueConvertible
extension UUID: DatabaseValueConvertible {
/// Returns a BLOB database value containing the uuid bytes.
public var databaseValue: DatabaseValue {
@@ -179,11 +179,7 @@ extension DatabaseValueConvertible where Self: Decodable {
guard let data = Data.fromDatabaseValue(databaseValue) else {
return nil
}
let decoder = JSONDecoder()
decoder.dataDecodingStrategy = .base64
decoder.dateDecodingStrategy = .millisecondsSince1970
decoder.nonConformingFloatDecodingStrategy = .throw
return try? decoder.decode(Self.self, from: data)
return try? databaseJSONDecoder().decode(Self.self, from: data)
} catch {
return nil
}
@@ -2,6 +2,7 @@ import Foundation
private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
let encode: (DatabaseValue) -> Void
let jsonEncoder: JSONEncoder
var codingPath: [any CodingKey] { [] }
@@ -42,16 +43,21 @@ private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
// This allows us to encode Date as String, for example.
encode(dbValueConvertible.databaseValue)
} else {
try DatabaseValueEncoder(encode: encode).encode(value)
try DatabaseValueEncoder(jsonEncoder: jsonEncoder, encode: encode).encode(value)
}
}
}
private class DatabaseValueEncoder: Encoder {
let encode: (DatabaseValue) -> Void
let jsonEncoder: JSONEncoder
var requiresJSON = false
init(encode: @escaping (DatabaseValue) -> Void) {
init(
jsonEncoder: JSONEncoder,
encode: @escaping (DatabaseValue) -> Void
) {
self.jsonEncoder = jsonEncoder
self.encode = encode
}
@@ -104,7 +110,7 @@ private class DatabaseValueEncoder: Encoder {
/// - precondition: May not be called after a value has been encoded through
/// a previous `self.singleValueContainer()` call.
func singleValueContainer() -> SingleValueEncodingContainer {
DatabaseValueEncodingContainer(encode: encode)
DatabaseValueEncodingContainer(encode: encode, jsonEncoder: jsonEncoder)
}
func encode<T: Encodable>(_ value: T) throws {
@@ -115,13 +121,7 @@ private class DatabaseValueEncoder: Encoder {
throw JSONRequiredError()
}
} catch is JSONRequiredError {
let encoder = JSONEncoder()
encoder.dataEncodingStrategy = .base64
encoder.dateEncodingStrategy = .millisecondsSince1970
encoder.nonConformingFloatEncodingStrategy = .throw
// guarantee some stability in order to ease value comparison
encoder.outputFormatting = .sortedKeys
let jsonData = try encoder.encode(value)
let jsonData = try jsonEncoder.encode(value)
// Store JSON String in the database for easier debugging and
// database inspection. Thanks to SQLite weak typing, we won't
@@ -138,7 +138,11 @@ private class DatabaseValueEncoder: Encoder {
extension DatabaseValueConvertible where Self: Encodable {
public var databaseValue: DatabaseValue {
var dbValue: DatabaseValue! = nil
try! DatabaseValueEncoder(encode: { dbValue = $0 }).encode(self)
try! DatabaseValueEncoder(
jsonEncoder: Self.databaseJSONEncoder(),
encode: { dbValue = $0 }
)
.encode(self)
return dbValue
}
}
@@ -44,7 +44,6 @@ extension Optional: SQLSelectable where Wrapped: SQLSelectable {
extension Optional: SQLSpecificExpressible where Wrapped: SQLSpecificExpressible { }
/// `Optional` is a database value when it wrapped type is.
extension Optional: DatabaseValueConvertible where Wrapped: DatabaseValueConvertible {
public var databaseValue: DatabaseValue {
switch self {
@@ -1,6 +1,6 @@
// MARK: - Value Types
/// `Bool` is a database value.
/// Bool adopts DatabaseValueConvertible and StatementColumnConvertible.
extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -95,7 +95,7 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// `Int` is a database value.
/// Int adopts DatabaseValueConvertible and StatementColumnConvertible.
extension Int: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -134,7 +134,7 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// `Int8` is a database value.
/// Int8 adopts DatabaseValueConvertible and StatementColumnConvertible.
extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -173,7 +173,7 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// `Int16` is a database value.
/// Int16 adopts DatabaseValueConvertible and StatementColumnConvertible.
extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -212,7 +212,7 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// `Int32` is a database value.
/// Int32 adopts DatabaseValueConvertible and StatementColumnConvertible.
extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -251,7 +251,7 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// `Int64` is a database value.
/// Int64 adopts DatabaseValueConvertible and StatementColumnConvertible.
extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -294,7 +294,7 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// `UInt` is a database value.
/// UInt adopts DatabaseValueConvertible and StatementColumnConvertible.
extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -333,7 +333,7 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// `UInt8` is a database value.
/// UInt8 adopts DatabaseValueConvertible and StatementColumnConvertible.
extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -372,7 +372,7 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// `UInt16` is a database value.
/// UInt16 adopts DatabaseValueConvertible and StatementColumnConvertible.
extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -411,7 +411,7 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// `UInt32` is a database value.
/// UInt32 adopts DatabaseValueConvertible and StatementColumnConvertible.
extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -450,7 +450,7 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// `UInt64` is a database value.
/// UInt64 adopts DatabaseValueConvertible and StatementColumnConvertible.
extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -489,7 +489,7 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// `Double` is a database value.
/// Double adopts DatabaseValueConvertible and StatementColumnConvertible.
extension Double: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -529,7 +529,7 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// `Float` is a database value.
/// Float adopts DatabaseValueConvertible and StatementColumnConvertible.
extension Float: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
@@ -569,7 +569,7 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
}
}
/// `String` is a database value.
/// String adopts DatabaseValueConvertible and StatementColumnConvertible.
extension String: DatabaseValueConvertible, StatementColumnConvertible {
/// Returns a value initialized from a raw SQLite statement pointer.
+99 -24
View File
@@ -2,11 +2,20 @@ extension Database {
// MARK: - Database Observation
/// Adds a transaction observer, so that it gets notified of
/// database changes and transactions.
/// Adds a transaction observer on the database connection, so that it
/// gets notified of database changes and transactions.
///
/// This method has no effect on read-only database connections.
///
/// For example:
///
/// ```swift
/// let myObserver = MyObserver()
/// try dbQueue.write { db in
/// db.add(transactionObserver: myObserver)
/// }
/// ```
///
/// - parameter transactionObserver: A transaction observer.
/// - parameter extent: The duration of the observation. The default is
/// the observer lifetime (observation lasts until observer
@@ -20,21 +29,30 @@ extension Database {
// Drop cached statements that delete, because the addition of an
// observer may change the need for truncate optimization prevention.
publicStatementCache.removeAll { $0.isDeleteStatement }
internalStatementCache.removeAll { $0.isDeleteStatement }
publicStatementCache.removeAll { $0.canDeleteRows }
internalStatementCache.removeAll { $0.canDeleteRows }
observationBroker.add(transactionObserver: transactionObserver, extent: extent)
}
/// Removes a transaction observer.
/// Removes a transaction observer from the database connection.
///
/// For example:
///
/// ```swift
/// let myObserver = MyObserver()
/// try dbQueue.write { db in
/// db.remove(transactionObserver: myObserver)
/// }
/// ```
public func remove(transactionObserver: some TransactionObserver) {
SchedulingWatchdog.preconditionValidQueue(self)
guard let observationBroker else { return }
// Drop cached statements that delete, because the removal of an
// observer may change the need for truncate optimization prevention.
publicStatementCache.removeAll { $0.isDeleteStatement }
internalStatementCache.removeAll { $0.isDeleteStatement }
publicStatementCache.removeAll { $0.canDeleteRows }
internalStatementCache.removeAll { $0.canDeleteRows }
observationBroker.remove(transactionObserver: transactionObserver)
}
@@ -117,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.
@@ -264,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
@@ -548,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()
@@ -764,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.
///
@@ -778,7 +825,8 @@ public protocol TransactionObserver: AnyObject {
/// - note: The event is only valid for the duration of this method call.
/// If you need to keep it longer, store a copy: `event.copy()`.
///
/// - precondition: This method must not access the database.
/// - precondition: This method must not access the observed writer
/// database connection.
func databaseDidChange(with event: DatabaseEvent)
/// Called when a transaction is about to be committed.
@@ -786,7 +834,8 @@ public protocol TransactionObserver: AnyObject {
/// The transaction observer has an opportunity to rollback pending changes
/// by throwing an error from this method.
///
/// - precondition: This method must not access the database.
/// - precondition: This method must not access the observed writer
/// database connection.
/// - throws: The eventual error that rollbacks pending changes.
func databaseWillCommit() throws
@@ -837,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:
///
@@ -854,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
///
@@ -864,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)
@@ -922,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)
@@ -991,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)
@@ -1044,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
@@ -1093,7 +1158,12 @@ public struct DatabaseEvent {
self.impl = impl
}
init(kind: Kind, rowID: Int64, databaseNameCString: UnsafePointer<Int8>?, tableNameCString: UnsafePointer<Int8>?) {
init(
kind: Kind,
rowID: Int64,
databaseNameCString: UnsafePointer<CChar>?,
tableNameCString: UnsafePointer<CChar>?)
{
self.init(
kind: kind,
rowID: rowID,
@@ -1103,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)
@@ -1129,8 +1204,8 @@ private protocol DatabaseEventImpl {
/// Optimization: MetalDatabaseEventImpl does not create Swift strings from raw
/// SQLite char* until actually asked for databaseName or tableName.
private struct MetalDatabaseEventImpl: DatabaseEventImpl {
let databaseNameCString: UnsafePointer<Int8>?
let tableNameCString: UnsafePointer<Int8>?
let databaseNameCString: UnsafePointer<CChar>?
let tableNameCString: UnsafePointer<CChar>?
var databaseName: String { String(cString: databaseNameCString!) }
var tableName: String { String(cString: tableNameCString!) }
@@ -1265,8 +1340,8 @@ public struct DatabasePreUpdateEvent {
kind: Kind,
initialRowID: Int64,
finalRowID: Int64,
databaseNameCString: UnsafePointer<Int8>?,
tableNameCString: UnsafePointer<Int8>?)
databaseNameCString: UnsafePointer<CChar>?,
tableNameCString: UnsafePointer<CChar>?)
{
self.init(
kind: kind,
@@ -1322,8 +1397,8 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
let connection: SQLiteConnection
let kind: DatabasePreUpdateEvent.Kind
let databaseNameCString: UnsafePointer<Int8>?
let tableNameCString: UnsafePointer<Int8>?
let databaseNameCString: UnsafePointer<CChar>?
let tableNameCString: UnsafePointer<CChar>?
var databaseName: String { String(cString: databaseNameCString!) }
var tableName: String { String(cString: tableNameCString!) }
+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
@@ -20,14 +20,20 @@ GRDB puts this SQLite feature to some good use, and lets you observe the databas
- ``ValueObservation``
- ``SharedValueObservation``
- ``AsyncValueObservation``
- ``Database/registerAccess(to:)``
### Observing Database Transactions
- ``DatabaseRegionObservation``
- ``Database/afterNextTransaction(onCommit:onRollback:)``
### Low-Level Transaction Observers
- ``TransactionObserver``
- ``Database/add(transactionObserver:extent:)``
- ``Database/remove(transactionObserver:)``
- ``DatabaseWriter/add(transactionObserver:extent:)``
- ``DatabaseWriter/remove(transactionObserver:)``
- ``Database/TransactionObservationExtent``
### Database Regions
+30 -21
View File
@@ -1,5 +1,7 @@
# The Database Schema
Define or query the database schema.
## Overview
**GRDB supports all database schemas, and has no requirement.** Any existing SQLite database can be opened, and you are free to structure your new databases as you wish.
@@ -16,7 +18,7 @@ try db.create(table: "player") { t in
When you plan to evolve the schema as new versions of your application ship, wrap all schema changes in <doc:Migrations>.
Prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exist (when creating views or triggers, for example).
Prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exist (when creating triggers, for example).
When a schema change is not directly supported by SQLite, or not available on the target operating system, database tables have to be recreated. See <doc:Migrations> for the detailed procedure.
@@ -24,7 +26,9 @@ When a schema change is not directly supported by SQLite, or not available on th
Even though all schema are supported, some features of the library and of the Swift language are easier to use when the schema follows a few conventions described below.
When those conventions are not applied, or not applicable, you will have to perform extra configurations.
When those conventions are not applied, or not applicable, you will have to perform extra configurations.
For recommendations specific to JSON columns, see <doc:JSON>.
### Table names should be English, singular, and camelCased
@@ -135,8 +139,8 @@ try db.create(table: "team") { t in
try db.create(table: "membership") { t in
// Composite primary key
t.primaryKey {
t.column("playerId", .integer).references("player")
t.column("teamId", .text).references("team")
t.belongsTo("player")
t.belongsTo("team")
}
t.column("role", .text).notNull()
}
@@ -163,11 +167,6 @@ struct Player: Codable {
var score: Int
}
extension Player: Identifiable {
// Required because the primary key column is not 'id'
var id: Int64? { rowid }
}
extension Player: FetchableRecord, MutablePersistableRecord {
// Required because the primary key
// is the hidden rowid column.
@@ -241,10 +240,10 @@ Unique indexes makes sure SQLite prevents the insertion of conflicting rows:
// RECOMMENDED
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("team").notNull()
t.column("position", .integer).notNull()
// Players must have distinct names
t.column("name", .text).unique()
t.column("teamId", .integer).notNull().references("team")
t.column("position", .integer).notNull()
}
// One single player at any given position in a team
@@ -307,7 +306,7 @@ try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
// A player must refer to an existing team
t.column("teamId", .integer).notNull().references("team")
t.belongsTo("team").notNull()
}
// REQUIRES EXTRA CONFIGURATION
@@ -319,6 +318,8 @@ try db.create(table: "player") { t in
}
```
See ``TableDefinition/belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`` for more information about the creation of foreign keys.
GRDB [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) are automatically configured from foreign keys declared in the database schema:
```swift
@@ -372,27 +373,35 @@ extension Team: TableRecord {
- ``TableOptions``
- ``VirtualTableModule``
### Database Views
- ``Database/create(view:options:columns:as:)``
- ``Database/create(view:options:columns:asLiteral:)``
- ``Database/drop(view:)``
- ``ViewOptions``
### Database Indexes
- ``Database/create(indexOn:columns:options:condition:)``
- ``Database/create(index:on:columns:options:condition:)``
- ``Database/create(index:on:expressions:options:condition:)``
- ``Database/drop(indexOn:columns:)``
- ``Database/drop(index:)``
- ``IndexOptions``
### 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``
@@ -401,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
+12 -7
View File
@@ -21,11 +21,13 @@ We'll address all of those challenges below.
>
> Always consider sharing plain files, or any other inter-process communication technique, before sharing an SQLite database.
## Use a Database Pool
## Use the WAL mode
In order to access a shared database, use a ``DatabasePool``. It opens the database in the [WAL mode], which helps sharing a database.
In order to access a shared database, use a ``DatabasePool``. It opens the database in the [WAL mode], which helps sharing a database because it allows multiple processes to access the database concurrently.
Since several processes may open the database at the same time, protect the creation of the database pool with an [NSFileCoordinator].
It is also possible to use a ``DatabaseQueue``, with the `.wal` ``Configuration/journalMode``.
Since several processes may open the database at the same time, protect the creation of the database connection with an [NSFileCoordinator].
- In a process that can create and write in the database, use this sample code:
@@ -150,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 {
@@ -226,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
@@ -244,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
@@ -83,7 +83,9 @@ do {
- ``acceptsDoubleQuotedStringLiterals``
- ``busyMode``
- ``foreignKeysEnabled``
- ``journalMode``
- ``readonly``
- ``JournalModeConfiguration``
### Configuring GRDB Connections
@@ -78,8 +78,7 @@ A `DatabasePool` needs your application to follow rules in order to deliver its
### Accessing the Database
See ``DatabaseReader`` and ``DatabaseWriter`` for more database
access methods.
See ``DatabaseReader`` and ``DatabaseWriter`` for more database access methods.
- ``asyncConcurrentRead(_:)``
- ``writeInTransaction(_:_:)``
@@ -88,11 +88,12 @@ 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
See ``DatabaseReader`` and ``DatabaseWriter`` for more database
access methods.
See ``DatabaseReader`` and ``DatabaseWriter`` for more database access methods.
- ``inDatabase(_:)``
- ``inTransaction(_:_:)``
@@ -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
@@ -74,7 +74,14 @@ extension Color: DatabaseValueConvertible { }
By default, such codable value types are encoded and decoded with the standard [JSONEncoder](https://developer.apple.com/documentation/foundation/jsonencoder) and [JSONDecoder](https://developer.apple.com/documentation/foundation/jsondecoder). `Data` values are handled with the `.base64` strategy, `Date` with the `.millisecondsSince1970` strategy, and non conforming floats with the `.throw` strategy.
To customize the JSON format, provide an explicit implementation for the `DatabaseValueConvertible` requirements.
To customize the JSON format, provide an explicit implementation for the `DatabaseValueConvertible` requirements, or implement these two methods:
```swift
protocol DatabaseValueConvertible {
static func databaseJSONDecoder() -> JSONDecoder
static func databaseJSONEncoder() -> JSONEncoder
}
```
### Adding support for the Tagged library
@@ -144,6 +151,11 @@ This extra conformance is not required: only aim at the low-level C interface if
- ``databaseValue-1ob9k``
### Configuring the JSON format for the standard Decodable protocol
- ``databaseJSONDecoder()-7zou9``
- ``databaseJSONEncoder()-37sff``
### Fetching Values from Raw SQL
- ``fetchCursor(_:sql:arguments:adapter:)-6elcz``
@@ -165,38 +177,6 @@ This extra conformance is not required: only aim at the low-level C interface if
- ``fetchSet(_:_:)-1foke``
- ``fetchOne(_:_:)-o6yj``
### Supported Value Types
- ``Swift/Bool``
- ``CoreFoundation/CGFloat``
- ``Foundation/Data``
- ``DatabaseDateComponents``
- ``Foundation/Date``
- ``Swift/Double``
- ``Foundation/Decimal``
- ``Swift/Float``
- ``Swift/Int``
- ``Swift/Int8``
- ``Swift/Int16``
- ``Swift/Int32``
- ``Swift/Int64``
- ``Foundation/NSData``
- ``Foundation/NSDate``
- ``Foundation/NSNull``
- ``Foundation/NSNumber``
- ``Foundation/NSString``
- ``Foundation/NSURL``
- ``Foundation/NSUUID``
- ``Swift/Optional``
- ``Swift/UInt``
- ``Swift/UInt8``
- ``Swift/UInt16``
- ``Swift/UInt32``
- ``Swift/UInt64``
- ``Swift/String``
- ``Foundation/URL``
- ``Foundation/UUID``
### Supporting Types
- ``DatabaseValueCursor``
@@ -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:
@@ -97,7 +91,7 @@ do {
- Note: All callbacks are called in the writer dispatch queue, and serialized with all database updates.
- Note: The `databaseDidChange` and `databaseWillCommit` callbacks must not touch the SQLite database. This limitation does not apply to `databaseDidCommit` and `databaseDidRollback` which can use their database argument.
- Note: The `databaseDidChange` and `databaseWillCommit` callbacks must not access the observed writer database connection in any way. This limitation does not apply to `databaseDidCommit` and `databaseDidRollback` which can use their database argument.
## Filtering Database Events
@@ -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).
+8 -11
View File
@@ -6,10 +6,6 @@ A toolkit for SQLite databases, with a focus on application development
![GRDB Logo](GRDBLogo.png)
- [GitHub Repository](http://github.com/groue/GRDB.swift)
- [Installation Instructions, encryption with SQLCipher, custom SQLite builds](https://github.com/groue/GRDB.swift#installation)
- [GRDBQuery](https://github.com/groue/GRDBQuery), the SwiftUI companion for GRDB
## Overview
Use this library to save your application’s permanent data into SQLite databases. It comes with built-in tools that address common needs:
@@ -71,6 +67,12 @@ let players: [Player] = try dbQueue.read { db in
}
```
## Links and Companion Libraries
- [GitHub Repository](http://github.com/groue/GRDB.swift)
- [Installation Instructions, encryption with SQLCipher, custom SQLite builds](https://github.com/groue/GRDB.swift#installation)
- [GRDBQuery](https://github.com/groue/GRDBQuery): the SwiftUI companion for GRDB.
- [GRDBSnapshotTesting](https://github.com/groue/GRDBSnapshotTesting): Test your database.
## Topics
@@ -93,14 +95,9 @@ let players: [Player] = try dbQueue.read { db in
- <doc:RecordTimestamps>
- <doc:SingleRowTables>
### Responding to Database Changes
### Application Tools
- <doc:DatabaseObservation>
### Full-Text Search
- <doc:FullTextSearch>
### Combine Publishers
- <doc:JSON>
- ``DatabasePublishers``
+150
View File
@@ -0,0 +1,150 @@
# JSON Support
Store and use JSON values in SQLite databases.
## Overview
SQLite and GRDB can store and fetch JSON values in database columns. Starting iOS 16+, macOS 10.15+, tvOS 17+, and watchOS 9+, JSON values can be manipulated at the database level.
## Store and fetch JSON values
### JSON columns in the database schema
It is recommended to store JSON values in text columns. In the example below, we create a ``Database/ColumnType/jsonText`` column with ``Database/create(table:options:body:)``:
```swift
try db.create(table: "player") { t in
t.primaryKey("id", .text)
t.column("name", .text).notNull()
t.column("address", .jsonText).notNull() // A JSON column
}
```
> Note: `.jsonText` and `.text` are equivalent, because both build a TEXT column in SQL. Yet the former better describes the intent of the column.
>
> Note: SQLite JSON functions and operators are [documented](https://www.sqlite.org/json1.html#interface_overview) to throw errors if any of their arguments are binary blobs. That's the reason why it is recommended to store JSON as text.
> Tip: When an application performs queries on values embedded inside JSON columns, indexes can help performance:
>
> ```swift
> // CREATE INDEX "player_on_country"
> // ON "player"("address" ->> 'country')
> try db.create(
> index: "player_on_country",
> on: "player",
> expressions: [
> JSONColumn("address")["country"],
> ])
>
> // SELECT * FROM player
> // WHERE "address" ->> 'country' = 'DE'
> let germanPlayers = try Player
> .filter(JSONColumn("address")["country"] == "DE")
> .fetchAll(db)
> ```
### Strict and flexible JSON schemas
[Codable Records](https://github.com/groue/GRDB.swift/blob/master/README.md#codable-records) handle both strict and flexible JSON schemas.
**For strict schemas**, use `Codable` properties. They will be stored as JSON strings in the database:
```swift
struct Address: Codable {
var street: String
var city: String
var country: String
}
struct Player: Codable {
var id: String
var name: String
// Stored as a JSON string
// {"street": "...", "city": "...", "country": "..."}
var address: Address
}
extension Player: FetchableRecord, PersistableRecord { }
```
**For flexible schemas**, use `String` or `Data` properties.
In the specific case of `Data` properties, it is recommended to store them as text in the database, because SQLite JSON functions and operators are [documented](https://www.sqlite.org/json1.html#interface_overview) to throw errors if any of their arguments are binary blobs. This encoding is automatic with ``DatabaseDataEncodingStrategy/text``:
```swift
// JSON String property
struct Player: Codable {
var id: String
var name: String
var address: String // JSON string
}
extension Player: FetchableRecord, PersistableRecord { }
// JSON Data property, saved as text in the database
struct Team: Codable {
var id: String
var color: String
var info: Data // JSON UTF8 data
}
extension Team: FetchableRecord, PersistableRecord {
// Support SQLite JSON functions and operators
// by storing JSON data as database text:
static let databaseDataEncodingStrategy = DatabaseDataEncodingStrategy.text
}
```
## Manipulate JSON values at the database level
[SQLite JSON functions and operators](https://www.sqlite.org/json1.html) are available starting iOS 16+, macOS 10.15+, tvOS 17+, and watchOS 9+.
Functions such as `JSON`, `JSON_EXTRACT`, `JSON_PATCH` and others are available as static methods on `Database`: ``Database/json(_:)``, ``Database/jsonExtract(_:atPath:)``, ``Database/jsonPatch(_:with:)``, etc.
See the full list below.
## JSON table-valued functions
The JSON table-valued functions `json_each` and `json_tree` are not supported.
## Topics
### JSON Values
- ``SQLJSONExpressible``
- ``JSONColumn``
### Access JSON subcomponents, and query JSON values, at the SQL level
The `->` and `->>` SQL operators are available on the ``SQLJSONExpressible`` protocol.
- ``Database/jsonArrayLength(_:)``
- ``Database/jsonArrayLength(_:atPath:)``
- ``Database/jsonExtract(_:atPath:)``
- ``Database/jsonExtract(_:atPaths:)``
- ``Database/jsonType(_:)``
- ``Database/jsonType(_:atPath:)``
### Build new JSON values at the SQL level
- ``Database/json(_:)``
- ``Database/jsonArray(_:)-8xxe3``
- ``Database/jsonArray(_:)-469db``
- ``Database/jsonObject(_:)``
- ``Database/jsonQuote(_:)``
- ``Database/jsonGroupArray(_:filter:)``
- ``Database/jsonGroupObject(key:value:filter:)``
### Modify JSON values at the SQL level
- ``Database/jsonInsert(_:_:)``
- ``Database/jsonPatch(_:with:)``
- ``Database/jsonReplace(_:_:)``
- ``Database/jsonRemove(_:atPath:)``
- ``Database/jsonRemove(_:atPaths:)``
- ``Database/jsonSet(_:_:)``
### Validate JSON values at the SQL level
- ``Database/jsonIsValid(_:)``
+2 -5
View File
@@ -26,10 +26,7 @@ migrator.registerMigration("Create authors") { db in
migrator.registerMigration("Add books and author.birthYear") { db in
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("authorId", .integer)
.notNull()
.indexed()
.references("author", onDelete: .cascade)
t.belongsTo("author").notNull()
t.column("title", .text).notNull()
}
@@ -236,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),
+12 -4
View File
@@ -17,16 +17,22 @@ For an overview, see [Records](https://github.com/groue/GRDB.swift/blob/master/R
- ``PersistableRecord``
- ``TableRecord``
### Associations
### Expressions
- ``Association``
- ``Column``
- ``JSONColumn``
- ``SQLExpression``
### Query Interface Requests
### Requests
- ``CommonTableExpression``
- ``QueryInterfaceRequest``
- ``Table``
### Associations
- ``Association``
### Errors
- ``RecordError``
@@ -34,9 +40,11 @@ For an overview, see [Records](https://github.com/groue/GRDB.swift/blob/master/R
### Supporting Types
- ``ColumnExpression``
- ``DerivableRequest``
- ``SQLExpressible``
- ``SQLJSONExpressible``
- ``SQLSpecificExpressible``
- ``SQLSubqueryable``
- ``SQLOrderingTerm``
- ``SQLSelectable``
- ``SQLSubqueryable``
@@ -31,10 +31,8 @@ migrator.registerMigration("createLibrary") { db in
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("title", .text).notNull() // (5)
t.column("authorId", .integer) // (6)
t.belongsTo("author", onDelete: .cascade) // (6)
.notNull() // (7)
.indexed() // (8)
.references("author", onDelete: .cascade) // (9)
}
}
@@ -46,10 +44,8 @@ try migrator.migrate(dbQueue)
3. An author must have a name.
4. The country of an author is not always known.
5. A book must have a title.
6. The `book.authorId` column is used to link a book to the author it belongs to.
6. The `book.authorId` column is used to link a book to the author it belongs to. This column is indexed in order to ease the selection of an author's books. A foreign key is defined from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions](https://sqlite.org/foreignkeys.html#fk_actions) for more information.
7. The `book.authorId` column is not null so that SQLite guarantees that all books have an author.
8. The `book.authorId` column is indexed in order to ease the selection of an author's books.
9. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, the `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions](https://sqlite.org/foreignkeys.html#fk_actions) for more information.
Thanks to this database schema, the application will always process *consistent data*, no matter how wrong the Swift code can get. Even after a hard crash, all books will have an author, a non-nil title, etc.
@@ -65,16 +61,16 @@ Thanks to this database schema, the application will always process *consistent
**Define one record type per database table.** This record type will be responsible for writing in this table.
**Let's start from regular structs** whose properties match the columns in their database table. Those structs conform to the standard [`Identifiable`] protocol because they have an identifier (the primary key). They conform to the standard [`Codable`] protocol so that we don't have to write the methods that convert to and from raw database rows.
**Let's start from regular structs** whose properties match the columns in their database table. They conform to the standard [`Codable`] protocol so that we don't have to write the methods that convert to and from raw database rows.
```swift
struct Author: Codable, Identifiable {
struct Author: Codable {
var id: Int64?
var name: String
var countryCode: String?
}
struct Book: Codable, Identifiable {
struct Book: Codable {
var id: Int64?
var authorId: Int64
var title: String
@@ -133,7 +129,7 @@ let books = try dbQueue.read { db in
> t.column("countryCode", .text) // Can be NULL
> }
>
> struct Author: Codable, Identifiable {
> struct Author: Codable {
> var id: Int64?
> var name: String // Not optional
> var countryCode: String? // Optional
@@ -154,6 +150,25 @@ let books = try dbQueue.read { db in
> try Author.find(db, id: authorID)
> }
> ```
>
> Take care that **`Identifiable` is not a good fit for optional ids**. You will frequently meet optional ids for records with auto-incremented ids:
>
> ```swift
> struct Player: Codable {
> var id: Int64? // Optional ids are not suitable for Identifiable
> var name: String
> var score: Int
> }
>
> extension Player: FetchableRecord, MutablePersistableRecord {
> // Update auto-incremented id upon successful insertion
> mutating func didInsert(_ inserted: InsertionSuccess) {
> id = inserted.rowID
> }
> }
> ```
>
> For more details about auto-incremented ids and `Identifiable`, see [issue #1435](https://github.com/groue/GRDB.swift/issues/1435#issuecomment-1740857712).
### Record Types Hide Intimate Database Details
+4 -4
View File
@@ -25,7 +25,7 @@ try db.create(table: "player") { t in
t.column("score", .integer).notNull()
}
struct Player: Identifiable {
struct Player {
var id: Int64?
var creationDate: Date?
var modificationDate: Date?
@@ -156,7 +156,7 @@ When you fetch timestamped records from the database, it may be inconvenient to
```swift
let player = try dbQueue.read { db
try Player.find(db, id: 1)
try Player.find(db, key: 1)
}
player.creationDate // optional 😕
player.modificationDate // optional 😕
@@ -166,7 +166,7 @@ A possible technique is to define two record types: one that deals with players
```swift
/// `Player` deals with unsaved players
struct Player: Identifiable {
struct Player {
var id: Int64? // optional
var creationDate: Date? // optional
var modificationDate: Date? // optional
@@ -244,7 +244,7 @@ You can copy it in your application, or use it as an inspiration. Not all apps h
```swift
// The base Player type
struct Player: Identifiable {
struct Player {
var id: Int64?
var creationDate: Date?
var modificationDate: Date?
+1
View File
@@ -81,6 +81,7 @@ For a more detailed overview, see [SQLite API](https://github.com/groue/GRDB.swi
### Database Values
- ``DatabaseDateComponents``
- ``DatabaseValueConvertible``
- ``StatementColumnConvertible``
+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
}
}
+2
View File
@@ -1,5 +1,7 @@
# Transactions and Savepoints
Precise transaction handling.
## Transactions and Safety
**A transaction is a fundamental tool of SQLite** that guarantees [data consistency](https://www.sqlite.org/transactional.html) as well as [proper isolation](https://sqlite.org/isolation.html) between application threads and database connections. It is at the core of GRDB <doc:Concurrency> guarantees.
+357
View File
@@ -0,0 +1,357 @@
import Foundation
// MARK: - Dump
extension Database {
/// Prints the results of all statements in the provided SQL.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// // Prints
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// try db.dumpSQL("SELECT * FROM player ORDER BY id")
/// }
/// ```
///
/// - Parameters:
/// - sql: The executed SQL.
/// - format: The output format.
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpSQL(
_ sql: SQL,
format: some DumpFormat = .debug(),
to stream: (any TextOutputStream)? = nil)
throws
{
var dumpStream = DumpStream(stream)
try _dumpSQL(sql, format: format, to: &dumpStream)
}
/// Prints the results of a request.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// // Prints
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// try db.dumpRequest(Player.orderByPrimaryKey())
/// }
/// ```
///
/// - Parameters:
/// - request : The executed request.
/// - format: The output format.
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpRequest(
_ request: some FetchRequest,
format: some DumpFormat = .debug(),
to stream: (any TextOutputStream)? = nil)
throws
{
var dumpStream = DumpStream(stream)
try _dumpRequest(request, format: format, to: &dumpStream)
}
/// Prints the contents of the provided tables and views.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// // player
/// // 1|Arthur|500
/// // 2|Barbara|1000
/// //
/// // team
/// // 1|Red
/// // 2|Blue
/// try db.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
{
var dumpStream = DumpStream(stream)
try _dumpTables(
tables,
format: format,
tableHeader: tableHeader,
stableOrder: stableOrder,
to: &dumpStream)
}
/// Prints the contents of the database.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// try db.dumpContent()
/// }
/// ```
///
/// This prints the database schema as well as the content of all
/// tables. For example:
///
/// ```
/// sqlite_master
/// CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)
///
/// player
/// 1,'Arthur',500
/// 2,'Barbara',1000
/// ```
///
/// > 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.
/// - stream: A stream for text output, which directs output to the
/// console by default.
public func dumpContent(
format: some DumpFormat = .debug(),
to stream: (any TextOutputStream)? = nil)
throws
{
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: -
extension Database {
func _dumpStatements(
_ statements: some Cursor<Statement>,
format: some DumpFormat,
to stream: inout DumpStream)
throws
{
while let statement = try statements.next() {
var stepFormat = format
let cursor = try statement.makeCursor()
while try cursor.next() != nil {
try stepFormat.writeRow(self, statement: statement, to: &stream)
}
stepFormat.finalize(self, statement: statement, to: &stream)
}
}
func _dumpSQL(
_ sql: SQL,
format: some DumpFormat,
to stream: inout DumpStream)
throws
{
try _dumpStatements(allStatements(literal: sql), format: format, to: &stream)
}
func _dumpRequest(
_ request: some FetchRequest,
format: some DumpFormat,
to stream: inout DumpStream)
throws
{
let preparedRequest = try request.makePreparedRequest(self, forSingleResult: false)
try _dumpStatements(AnyCursor([preparedRequest.statement]), format: format, to: &stream)
if let supplementaryFetch = preparedRequest.supplementaryFetch {
let rows = try Row.fetchAll(self, request)
try withoutActuallyEscaping(
{ request, keyPath in
stream.write("\n")
stream.writeln(keyPath.joined(separator: "."))
try self._dumpRequest(request, format: format, to: &stream)
},
do: { willExecuteSupplementaryRequest in
try supplementaryFetch(self, rows, willExecuteSupplementaryRequest)
})
}
}
func _dumpTables(
_ tables: [String],
format: some DumpFormat,
tableHeader: DumpTableHeaderOptions,
stableOrder: Bool,
to stream: inout DumpStream)
throws
{
let header: Bool
switch tableHeader {
case .always: header = true
case .automatic: header = tables.count > 1
}
var first = true
for table in tables {
if first {
first = false
} else {
stream.write("\n")
}
if header {
stream.writeln(table)
}
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)
}
}
}
func _dumpContent(
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: """
SELECT sql || ';', name
FROM sqlite_master
WHERE sql IS NOT NULL
ORDER BY
tbl_name COLLATE NOCASE,
CASE type WHEN 'table' THEN 'a' WHEN 'index' THEN 'aa' ELSE type END,
name COLLATE NOCASE,
sql
""")
for row in sqlRows {
let name: String = row[1]
if try ignoresObject(named: name) {
continue
}
stream.writeln(row[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
}
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: Sendable {
/// Table names are only printed when several tables are printed.
case automatic
/// Table names are always printed.
case always
}
Loaded 100 of 267 files, more files were not shown because too many files have changed in this diff. Show more