Compare commits

...
Author SHA1 Message Date
Gwendal Roué 4cdb45e012 Merge branch 'development' 2020-06-15 20:06:34 +02:00
Gwendal Roué 4e182a511f v5.0.0-beta.5 2020-06-15 20:05:13 +02:00
Gwendal Roué a4443b8ebb FAQ Navigation 2020-06-15 19:57:50 +02:00
Gwendal Roué 0f55f76caa Demo app tweaks 2020-06-15 19:45:00 +02:00
Gwendal Roué e3e1feee2b Demo app tweaks 2020-06-15 19:36:43 +02:00
Gwendal Roué 1a1c0cd3d1 Demo app tweaks 2020-06-15 19:23:21 +02:00
Gwendal Roué dd63ddf7f2 CHANGELOG 2020-06-15 17:04:16 +02:00
Gwendal Roué c4ab23761e QueryInterfaceRequest.selectPrimaryKey(as:) 2020-06-15 17:02:00 +02:00
Gwendal Roué 86a8439473 Fix typo 2020-06-15 14:14:09 +02:00
Gwendal Roué 47cf3b0108 Update FAQ sample code with TableRecord.primaryKey, and add tests for FAQ 2020-06-15 14:09:15 +02:00
Gwendal Roué ab97ceb784 TableRecord.primaryKey 2020-06-15 14:08:50 +02:00
Gwendal Roué ae7cdb1f5b Precision 2020-06-14 20:58:04 +02:00
Gwendal Roué c0cf3c0525 Fix wording 2020-06-14 20:51:38 +02:00
Gwendal Roué 82feed42c2 Fix wording 2020-06-14 20:50:46 +02:00
Gwendal Roué 5c697659b4 Foster SQLITE_ENABLE_SNAPSHOT in the "Custom SQLite Builds" guide 2020-06-14 20:49:22 +02:00
Gwendal Roué efc12c2ef9 CHANGELOG 2020-06-14 20:39:31 +02:00
Gwendal Roué 280c9f0155 Fix sample code 2020-06-14 20:33:49 +02:00
Gwendal Roué 9608b5edd5 Fix typo 2020-06-14 20:32:36 +02:00
Gwendal Roué 7662e53dce Fix typo 2020-06-14 20:31:29 +02:00
Gwendal Roué 1f5cc801e1 Fix typos 2020-06-14 20:29:38 +02:00
Gwendal Roué 2c6ca91985 Fix inner links 2020-06-14 20:28:16 +02:00
Gwendal Roué 023a04aff9 Associations FAQ 2020-06-14 20:25:22 +02:00
Gwendal Roué ffe40dbf79 Fix indentation 2020-06-14 17:10:24 +02:00
Gwendal Roué cf9b9206bd Fix typo 2020-06-14 17:06:36 +02:00
Gwendal Roué 0f70af7a22 Fix typo 2020-06-14 17:05:56 +02:00
Gwendal Roué 7068a4f149 Update the demo app for better alignment with "Good Practices for Designing Record Types" 2020-06-14 17:03:24 +02:00
Gwendal Roué 70714768d9 Always use snapshots apis through grdb_xxx shims 2020-06-14 15:38:16 +02:00
Gwendal Roué ec0e8672be Documentation, cleanup 2020-06-14 11:03:24 +02:00
Gwendal Roué 9215f88e7f Documentation, cleanup, and checkpoint prevention 2020-06-14 10:47:27 +02:00
Gwendal Roué 510daa84a7 This is hard 2020-06-14 06:36:53 +02:00
Gwendal Roué eacf48fef3 More snapshot-based optimization of ValueObservation with DatabasePool
This time, for the .immediate scheduler.
2020-06-14 06:34:08 +02:00
Gwendal Roué 0dee6425d1 Fix free function 2020-06-14 05:36:33 +02:00
Gwendal Roué 842846dbc4 Documentation 2020-06-14 05:36:12 +02:00
Gwendal Roué 8b800ecbe1 CHANGELOG 2020-06-13 20:19:00 +02:00
Gwendal Roué f1e65fbb2c Optimization of ValueObservation with DatabasePool thanks to SQLITE_ENABLE_SNAPSHOT
The difficulty is that system <sqlite3.h> does not contain the expected declarations, even when SQLite is compiled with SQLITE_ENABLE_SNAPSHOT :-(

Since snapshots are not exposed in any public API, we don't bother dealing with availability checks. We just add the missing declarations, and rely on the linker in order to spot eventual errors.

This commit is likely to break Linux builds, though.
2020-06-13 20:14:40 +02:00
Gwendal Roué 372996deb3 TODO
# Conflicts:
#	TODO.md
2020-06-13 13:36:51 +02:00
Gwendal Roué 45f5ece534 CHANGELOG 2020-06-12 14:22:47 +02:00
Gwendal Roué a95b3264de Fix documentation 2020-06-12 14:20:29 +02:00
Gwendal Roué 8d44ad7256 Database.maximumStatementArgumentCount 2020-06-12 14:19:31 +02:00
Gwendal Roué a136384c7d Merge pull request #795 from groue/dev/more-checkpoint
Enhanced support for WAL Checkpoints
2020-06-12 12:46:52 +02:00
Gwendal Roué b15999e4c9 TODO 2020-06-12 12:45:12 +02:00
Gwendal Roué e8235f8d6a Database.columnsForUniqueKey(_:in:) does not hit the database for empty column sequences 2020-06-11 12:49:22 +02:00
Gwendal Roué e31f7a4763 CHANGELOG 2020-06-07 17:07:31 +02:00
Gwendal Roué 3103e6e373 Fix Swiftlint warning 2020-06-07 17:07:31 +02:00
Gwendal Roué 3a42a4bf9f Rename checkpoint tuple members 2020-06-07 17:07:31 +02:00
Gwendal Roué 3e5a21b49b Tests for Database.checkpoint(_🔛) 2020-06-07 17:07:31 +02:00
Gwendal Roué 6f3ec89bcd Update checkpointing tests 2020-06-07 17:07:31 +02:00
Gwendal Roué 56f6984f9d Introduce Database.checkpoint(_🔛) 2020-06-07 17:07:31 +02:00
Gwendal Roué 5f88a400d5 DatabasePool.checkpoint(_:) is unavailable 2020-06-07 17:07:31 +02:00
Gwendal Roué 91ed7d762b Setup busy handler as soon as possible 2020-06-07 17:07:30 +02:00
Gwendal Roué 668c1d632e f67f9ebd4b did spot an oddity
This is a temp fix
2020-06-07 17:07:02 +02:00
Gwendal Roué 20f693c508 Disable two SQLCipher tests until we understand what is happening 2020-06-07 16:36:55 +02:00
Gwendal Roué f67f9ebd4b Add a sanity transaction assertion 2020-06-07 15:57:50 +02:00
Gwendal Roué 53dade2740 Merge branch 'development' 2020-06-06 15:12:27 +02:00
Gwendal Roué 9ec9880889 v5.0.0-beta.4 2020-06-06 15:11:56 +02:00
Gwendal Roué eb27b0cfc5 BRAG 2020-06-06 15:11:28 +02:00
Gwendal Roué d3cc23d5a3 Harmonize GRDB, GRDBCombine, RxGRDB for next beta 2020-06-06 15:04:13 +02:00
Gwendal Roué e129463bae Maybe fix a broken link in the generated jazzy doc 2020-06-06 13:46:32 +02:00
Gwendal Roué b567d64489 fix typo 2020-06-05 20:49:21 +02:00
Gwendal Roué d94fcc398b Date modifiers, more julianDay(), and dateTime() 2020-06-05 20:48:12 +02:00
Gwendal Roué 3c48a434f1 Tests for default SQLExpressible conformance for RawRepresentable 2020-06-05 12:27:58 +02:00
Gwendal Roué d04dda1888 Default SQLExpressible conformance for RawRepresentable 2020-06-05 12:27:42 +02:00
Gwendal Roué 842c6ced0c Documentation for julianDay function 2020-06-05 12:14:46 +02:00
Gwendal Roué 59c5d2e43b test for julianDay function 2020-06-05 12:14:40 +02:00
Gwendal Roué 2aeddda77d julianDay function 2020-06-05 12:14:34 +02:00
Gwendal Roué 9aeccce227 Makefile: support for Xcode 11.5 2020-06-05 08:33:20 +02:00
Gwendal Roué 45e5333c2c Test optimized SQLCipher 2020-06-05 08:32:05 +02:00
Gwendal Roué f4581b993b Merge pull request #794 from groue/dev/Database-description
Name of Database Connections
2020-06-04 18:20:18 +02:00
Gwendal Roué d2b1853b7b Database.debugDescription 2020-06-04 18:15:48 +02:00
Gwendal Roué 800b9ffc3d Name the temporary database used by DatabaseMigrator.eraseDatabaseOnSchemaChange 2020-06-03 20:09:22 +02:00
Gwendal Roué a93f75a6fc CHANGELOG 2020-06-03 20:01:59 +02:00
Gwendal Roué 04df4ba157 Documentation 2020-06-03 19:57:43 +02:00
Gwendal Roué d55e16de3c Database.description tests 2020-06-03 19:37:34 +02:00
Gwendal Roué 780ba744f1 Database.description 2020-06-03 19:37:24 +02:00
Gwendal Roué 8027925ae6 TODO 2020-06-03 19:07:03 +02:00
Gwendal Roué b29695b024 Link to statement profiling FAQ from SharingADatabase.md 2020-06-03 19:06:09 +02:00
Gwendal Roué d98904727f Thank you 2020-06-01 21:12:53 +02:00
Gwendal Roué 4cd421ff7c Merge branch 'development' 2020-06-01 20:21:22 +02:00
Gwendal Roué a8b58cb7e7 v5.0.0-beta.3 2020-06-01 20:20:52 +02:00
Gwendal Roué 578fa162f1 Merge pull request #791 from groue/dev/trace
Extend tracing of statement execution
2020-06-01 20:14:35 +02:00
Gwendal Roué 7333b1a080 Travis: no more stages 2020-06-01 18:20:02 +02:00
Gwendal Roué 961e5e46c1 Fix SQLCipher tests 2020-06-01 14:09:22 +02:00
Gwendal Roué a2dce4a238 Come on, Travis 2020-06-01 09:02:25 +02:00
Gwendal Roué 996c1c994f Documentation 2020-06-01 07:41:46 +02:00
Gwendal Roué 9540df84cf Documentation 2020-06-01 07:39:43 +02:00
Gwendal Roué b47680638d Trace statements by default 2020-06-01 07:16:48 +02:00
Gwendal Roué 5f7a9de8a5 Fix statement profiling test for slow setups 2020-06-01 06:28:46 +02:00
Gwendal Roué b80814a77e CHANGELOG 2020-05-31 20:16:00 +02:00
Gwendal Roué b95d7cb647 More Tests for Database.trace(options:_:) 2020-05-31 20:13:45 +02:00
Gwendal Roué 3e25faabba Update the migration guide 2020-05-31 19:16:35 +02:00
Gwendal Roué 2677cf8de8 Update documentation 2020-05-31 19:16:23 +02:00
Gwendal Roué 81213f2649 Tests for Database.trace(options:_:) 2020-05-31 19:08:42 +02:00
Gwendal Roué 30f619ca2c Refactor database tracing
- Make it possible to log the database label along with the executed SQL
- Make it possible to avoid arguments expansion
- Make it possible to profile statements
2020-05-31 19:08:08 +02:00
Gwendal Roué 9552a5ce40 Merge pull request #790 from groue/dev/iOS10
Bump required iOS version to 10.0
2020-05-31 14:20:33 +02:00
Gwendal Roué 318564a13c CHANGELOG 2020-05-31 14:02:18 +02:00
Gwendal Roué 9ee3fd38b5 Remove mentions of unsupported iOS versions 2020-05-31 13:54:02 +02:00
Gwendal Roué 03a66af35e Bump iOS requirement to iOS10+
iOS9 simulator is no longer available with the Xcode 11.4+ requirement. https://twitter.com/xenadu02/status/1140093901438689280
2020-05-31 13:48:59 +02:00
Gwendal Roué 00c2f61535 TODO 2020-05-30 13:54:45 +02:00
Gwendal Roué 289394c7ac Turn LockedBox and ReadWriteBox into property wrappers.
Also fix an old concurrency bug in tests, regarding query recording
2020-05-30 13:52:39 +02:00
Gwendal Roué a5de2b9288 Breaking: AnyFetchRequest.asRequest(of:) 2020-05-30 10:30:07 +02:00
Gwendal Roué e0266bdde3 Merge pull request #784 from groue/dev/fix-783
Fix observation of eager-loaded to-many associations
2020-05-25 18:34:30 +02:00
Gwendal Roué e82ecfee9f CHANGELOG 2020-05-25 13:41:41 +02:00
Gwendal Roué 80f0379d71 Remove database content unused by test 2020-05-25 13:39:35 +02:00
Gwendal Roué 449c0e37b1 Update regression tests for #783 2020-05-25 13:24:25 +02:00
Gwendal Roué f825c52ecf Update request region tests for both DatabaseRegionConvertible and statement region 2020-05-25 13:04:48 +02:00
Gwendal Roué 4c2042c3ce Cleanup 2bb53026ef 2020-05-25 13:04:10 +02:00
Gwendal Roué af0946fd21 Regression tests for #783 (WIP) 2020-05-25 09:34:35 +02:00
Gwendal Roué 2bb53026ef Fix #783 2020-05-25 09:34:11 +02:00
Gwendal Roué 0929fe72b8 Cleanup detection of queries that return a single row 2020-05-14 12:28:52 +02:00
Gwendal Roué e0a40776ee Makefile update for Travis 2020-05-12 07:21:13 +02:00
Gwendal Roué e99015bcff Merge branch 'development' 2020-05-11 18:50:35 +02:00
Gwendal Roué abd7ee9f17 v5.0.0-beta.2 2020-05-11 18:49:57 +02:00
Gwendal Roué 364c624a37 Update sample code for sharing databases 2020-05-11 18:44:38 +02:00
Gwendal Roué 00e10324d8 Merge pull request #775 from groue/dev/superseded-migrator
DatabaseMigrator can check if it has been superseded
2020-05-11 13:35:10 +02:00
Gwendal Roué 0539c41d17 CHANGELOG 2020-05-11 09:10:14 +02:00
Gwendal Roué 212a6f7e53 Documentation 2020-05-11 09:06:04 +02:00
Gwendal Roué cff769ddd5 Documentation 2020-05-11 08:54:31 +02:00
Gwendal Roué ed6ad9d373 Clean up DatabaseMigrator tests 2020-05-11 08:50:04 +02:00
Gwendal Roué 44772f89d7 More tests for DatabaseMigrator.hasBeenSuperseded(_:) 2020-05-11 08:46:41 +02:00
Gwendal Roué 2aa61c3403 Tests for DatabaseMigrator.hasBeenSuperseded(_:) 2020-05-11 08:28:02 +02:00
Gwendal Roué 3fea5db763 DatabaseMigrator.hasBeenSuperseded(_:) 2020-05-11 08:27:41 +02:00
Gwendal Roué b2bc0e7941 Merge pull request #774 from groue/dev/request-as-expression-and-collection
All requests are usable as SQL expressions and collections
2020-05-11 08:10:45 +02:00
Gwendal Roué c7d98e0231 CHANGELOG 2020-05-10 15:34:38 +02:00
Gwendal Roué 6fcf4f565a Relax test for various SQLite versions 2020-05-10 15:34:38 +02:00
Gwendal Roué 8c11a751ff TODO 2020-05-10 15:34:38 +02:00
Gwendal Roué c0217d56ca Remove doubt about how SQLRequest uses singleResult 2020-05-10 15:34:38 +02:00
Gwendal Roué 89ba8c3398 Remove unclear rationale 2020-05-10 15:34:38 +02:00
Gwendal Roué d814ab216d Documentation 2020-05-10 15:34:38 +02:00
Gwendal Roué 284ec22dd5 Documentation 2020-05-10 15:34:38 +02:00
Gwendal Roué 57e5735e9a Documentation 2020-05-10 15:34:38 +02:00
Gwendal Roué 5786d19ff4 Documentation 2020-05-10 15:34:38 +02:00
Gwendal Roué c73872549a Fix typo 2020-05-10 15:34:38 +02:00
Gwendal Roué f799d5f30c Documentation 2020-05-10 15:34:38 +02:00
Gwendal Roué e94be4a06e Upgrade path for FetchRequest 2020-05-10 15:34:38 +02:00
Gwendal Roué e9a68d82e6 Remove FetchRequest documentation from the main README 2020-05-10 15:34:38 +02:00
Gwendal Roué b16a0da88c Documentation 2020-05-10 15:34:37 +02:00
Gwendal Roué a318d4cc82 Test upgrade path from GRDB4 to GRDB5 2020-05-10 15:34:37 +02:00
Gwendal Roué 4f500de04b Expose SQLLiteral.sql(_:)
This is needed for custom FetchRequest types
2020-05-10 15:34:37 +02:00
Gwendal Roué a77b195c7c Reopen FetchRequest 2020-05-10 15:34:37 +02:00
Gwendal Roué d2928a9929 requestSQL(_:forSingleResult:) is experimental 2020-05-10 15:34:37 +02:00
Gwendal Roué 476e72cca2 requestSQL(_:forSingleResult:) is experimental 2020-05-10 15:34:37 +02:00
Gwendal Roué 375ed0135c PreparedRequest is still documented 2020-05-10 15:34:37 +02:00
Gwendal Roué 17e745f52b SQLRequestProtocol, close FetchRequest 2020-05-10 15:34:37 +02:00
Gwendal Roué a3cc5745ac Revert "Test for the immutable flag"
This reverts commit 8a595be54f.
2020-05-10 15:31:56 +02:00
Gwendal Roué 8a595be54f Test for the immutable flag
https://sqlite.org/uri.html#uriimmutable
2020-05-10 12:38:04 +02:00
Gwendal Roué 68203b5373 Merge pull request #773 from groue/dev/subqueries-and-aliases
Allow subqueries to refer to outer tables
2020-05-09 08:20:49 +02:00
Gwendal Roué a79fc34071 CHANGELOG 2020-05-08 20:57:50 +02:00
Gwendal Roué 7f66f41026 TODO 2020-05-08 20:43:10 +02:00
Gwendal Roué 956f419b20 TODO 2020-05-08 20:41:21 +02:00
Gwendal Roué e414aca05b Cleanup 2020-05-08 20:41:18 +02:00
Gwendal Roué 76e0a9f6b6 AnyFetchRequest is now generic on RowDecoder 2020-05-08 16:43:02 +02:00
Gwendal Roué 94b4131ce4 TODO 2020-05-08 15:07:18 +02:00
Gwendal Roué a26901cb80 Allow subqueries to refer to table aliases from parent query 2020-05-08 15:06:16 +02:00
Gwendal Roué a4d7f39ad8 Merge pull request #772 from groue/dev/SQLITE_FCNTL_PERSIST_WAL
Update the Database Sharing Guide with mention of the persistent WAL mode
2020-05-06 19:39:53 +02:00
Gwendal Roué 6f02a90a7a Remove link to deleted chapter 2020-05-06 19:38:24 +02:00
Gwendal Roué ae3c06f761 Remove the obsolete "Performance" chapter
It contained outdated information, and removing it helps GitHub preserve Markdown rendering of our looooong README.
2020-05-06 19:37:08 +02:00
Gwendal Roué f29a98aac3 Fix inner documentation links 2020-05-06 19:33:39 +02:00
Gwendal Roué a641b1efd4 Documentation 2020-05-06 19:29:48 +02:00
Gwendal Roué fc6c46e628 CHANGELOG 2020-05-06 19:25:11 +02:00
Gwendal Roué cb8c9f5ba3 SQLITE_FCNTL_PERSIST_WAL is always recommended 2020-05-06 19:13:16 +02:00
Gwendal Roué a8122b44f1 Wording 2020-05-06 18:52:39 +02:00
Gwendal Roué 6b86e61056 Cool URIs don't change 2020-05-06 18:38:36 +02:00
Gwendal Roué 97bbb5bced Rename AppGroupContainers.md to SharingADatabase.md 2020-05-06 18:34:45 +02:00
Gwendal Roué b3b155459f Document the "persistent WAL mode" and SQLITE_FCNTL_PERSIST_WAL 2020-05-06 18:24:06 +02:00
Gwendal Roué e4803c1e0c Cleanup SQLITE_FCNTL_PERSIST_WAL tests 2020-05-06 13:25:59 +02:00
Gwendal Roué db7fb96142 Tests for persistent WAL mode
Tests for SQLITE_FCNTL_PERSIST_WAL: https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlpersistwal
2020-05-06 08:55:27 +02:00
Gwendal Roué 3eb7d57754 [skip travis] Documentation 2020-05-04 12:57:42 +02:00
Gwendal Roué 7af96a69a0 Merge pull request #753 from groue/GRDB5
GRDB 5
2020-05-02 18:07:54 +02:00
Gwendal Roué 00e6d4ed0e Give *even* more time to tests 2020-05-02 16:23:31 +02:00
Gwendal Roué f4b2c2d40a [skip travis] Bump release date 2020-05-02 15:36:10 +02:00
Gwendal Roué 75e9056ac8 [skip travis] Fix inner links 2020-05-02 15:22:19 +02:00
Gwendal Roué a69be48066 Give more time to tests 2020-05-02 15:13:02 +02:00
Gwendal Roué 420fb93356 Fix testErrorCompletesTheObservation 2020-05-02 12:30:54 +02:00
Gwendal Roué 425e506862 Make all ValueObservation tests deterministic (avoid inverted expectations)
Inverted expectations were just too flaky on Travis
2020-05-02 12:19:23 +02:00
Gwendal Roué f09a62415d Restore disabled Travis jobs
We'll need some stronger cure. All timeout-based tests are flaky on Travis :-(
2020-05-02 09:04:51 +02:00
Gwendal Roué 90028ee9f5 Give more time for Travis 2020-05-02 08:41:56 +02:00
Gwendal Roué e37d2ae18c [skip travis] Fix inner links 2020-05-02 05:51:14 +02:00
Gwendal Roué 0322537b63 [skip travis] Fix inner links 2020-05-02 05:42:33 +02:00
Gwendal Roué 7b6bd84ac2 Disable flaky tvOS tests
https://travis-ci.org/github/groue/GRDB.swift/jobs/682070292
2020-05-02 05:28:42 +02:00
Gwendal Roué 6a98a46c85 Speed up slow tests 2020-05-01 20:11:02 +02:00
Gwendal Roué 0ab974e1b7 [skip travis] Rename Travis jobs 2020-05-01 19:47:46 +02:00
Gwendal Roué 85b84f217d Fix for Travis 2020-05-01 19:27:17 +02:00
Gwendal Roué 5e9cbf41a5 Let people find the non-beta version 2020-05-01 19:02:24 +02:00
Gwendal Roué 773db56d79 Sort the section of moved chapters 2020-05-01 18:59:28 +02:00
Gwendal Roué f68cbb03ee Update link to migration guide 2020-05-01 18:57:32 +02:00
Gwendal Roué 15f1e5259d Extract the Migration guide from the main README
README is too big, and Github stops rendering Markdown
2020-05-01 18:56:05 +02:00
Gwendal Roué 7ede3edf0c v5.0.0-beta 2020-05-01 18:44:13 +02:00
Gwendal Roué 14d16ffd20 My 🦋 keyboard is 💩 2020-05-01 17:34:08 +02:00
Gwendal Roué a7df6cc7df CHANGELOG 2020-05-01 17:30:11 +02:00
Gwendal Roué aaa5986e33 CHANGELOG 2020-05-01 17:26:43 +02:00
Gwendal Roué 3173dd20fe CHANGELOG 2020-05-01 17:18:14 +02:00
Gwendal Roué a29ca8348f CHANGELOG: documentation diff 2020-05-01 17:15:44 +02:00
Gwendal Roué 278e72ecc8 Fix typo 2020-05-01 17:15:35 +02:00
Gwendal Roué cf738588f2 Fix typo 2020-05-01 16:30:41 +02:00
Gwendal Roué 146b06f27a bugfix 2020-05-01 16:15:54 +02:00
Gwendal Roué fa4a90f720 Improve SQLQueryGenerator.expectsSingleResult 2020-05-01 16:06:56 +02:00
Gwendal Roué 93f4d43ee6 Cleanup 2020-05-01 15:43:57 +02:00
Gwendal Roué da4b96c2ca Cleanup handling of subquery sources 2020-05-01 15:42:01 +02:00
Gwendal Roué 420a257650 Test for case insensitivity in association requests 2020-05-01 15:07:40 +02:00
Gwendal Roué 39f327fcb3 Optimize SQLAssociationCondition.filteringExpression(_:leftRows:)
And make sure we compute a correct database region for association requests
2020-05-01 15:06:47 +02:00
Gwendal Roué 27ffb2a418 Rename index(ofColumn:) to index(forColumn:) 2020-05-01 15:01:01 +02:00
Gwendal Roué 0dc18cdaab CHANGELOG 2020-05-01 13:17:23 +02:00
Gwendal Roué 1ac9051384 Merge pull request #770 from groue/dev/subqueries
Subqueries
2020-05-01 12:36:19 +02:00
Gwendal Roué 691bb73d3e Bump iOS version in Makefile 2020-05-01 12:07:32 +02:00
Gwendal Roué 61d7740767 Fix FTS5 2020-05-01 11:27:08 +02:00
Gwendal Roué 7f7554f601 Document support for subqueries 2020-05-01 11:12:44 +02:00
Gwendal Roué ee68550052 Fix typo 2020-05-01 10:59:10 +02:00
Gwendal Roué 4de63ca9a2 Documentation fix 2020-05-01 10:47:23 +02:00
Gwendal Roué ef42035fe4 Documentation 2020-05-01 10:36:36 +02:00
Gwendal Roué eb93b25301 Fix typo 2020-05-01 10:28:19 +02:00
Gwendal Roué 2502747a7b Update the "Joined Queries Support" chapter 2020-05-01 10:25:44 +02:00
Gwendal Roué de5477d8f0 Documentation 2020-05-01 09:47:27 +02:00
Gwendal Roué fae562f20d Documentation 2020-05-01 09:43:48 +02:00
Gwendal Roué 307c3d5a13 Documentation 2020-05-01 09:01:10 +02:00
Gwendal Roué 7a1afba26e Documentation 2020-05-01 08:59:00 +02:00
Gwendal Roué b2370dd597 TODO 2020-05-01 08:58:52 +02:00
Gwendal Roué 513b7e9379 Tests for interpolation of TableRecord selection 2020-05-01 08:58:46 +02:00
Gwendal Roué 9392722bab Restore and fix test for TableRecord selection interpolation 2020-04-30 19:47:35 +02:00
Gwendal Roué 321b6a3488 Fixits for renamed generic parameter 2020-04-30 19:37:02 +02:00
Gwendal Roué 443d44cc7a Restore TableRecord.selectionSQL in the form of SQL interpolation 2020-04-30 19:33:33 +02:00
Gwendal Roué df2cc0af36 Test for SQLCollection qualification 2020-04-30 19:01:14 +02:00
Gwendal Roué dfcc6f99a5 SQLCollection can be qualified, now 2020-04-30 18:49:20 +02:00
Gwendal Roué 664c1ed281 Documentation 2020-04-30 18:35:05 +02:00
Gwendal Roué 057679a2ba We don't need to prevent requests that select several columns 2020-04-30 18:22:59 +02:00
Gwendal Roué e05b8b2b47 Unify SQLGenerationContext 2020-04-30 17:56:15 +02:00
Gwendal Roué d67f4802d3 Documentation 2020-04-30 15:21:41 +02:00
Gwendal Roué 72e4fc620b Remove LIMIT 1 from aggregated requests 2020-04-30 15:16:00 +02:00
Gwendal Roué 9c53ed94a7 Documentation 2020-04-30 15:13:33 +02:00
Gwendal Roué cac605749d Cleanup SQLExpressionBinaryReduce.truthComponents 2020-04-30 14:21:25 +02:00
Gwendal Roué 9006c701b3 Replace the expectsSingleResult hint with an analysis of the query 2020-04-30 14:14:07 +02:00
Gwendal Roué 05c001865b Cleanup 2020-04-30 09:12:57 +02:00
Gwendal Roué cb7a7633b1 TODO 2020-04-30 09:04:17 +02:00
Gwendal Roué 1e92b98165 TODO 2020-04-30 08:40:35 +02:00
Gwendal Roué 0bf23477f8 Less TODO 2020-04-30 08:36:10 +02:00
Gwendal Roué 359df39b7e Make it easier to look for subquery tests 2020-04-30 08:36:04 +02:00
Gwendal Roué cfd4141469 CHANGELOG 2020-04-30 08:32:51 +02:00
Gwendal Roué 90415fa936 Documentation 2020-04-30 08:31:59 +02:00
Gwendal Roué 1d89d184fd Fix subqueries semantics 2020-04-30 08:19:00 +02:00
Gwendal Roué 026e5b288f Documentation 2020-04-29 23:46:42 +02:00
Gwendal Roué be249bc697 SQLRequestExpressible is a sub protocol of SQLSpecificExpressible 2020-04-29 23:40:37 +02:00
Gwendal Roué 69641ff7d6 Undo undesired change 2020-04-29 22:29:53 +02:00
Gwendal Roué 4245e8f09e Cleanup 2020-04-29 22:24:58 +02:00
Gwendal Roué 94fed7965b Cleanup 2020-04-29 22:16:19 +02:00
Gwendal Roué a15233eff1 SQLGenerationContext no longer needs to be mutated 2020-04-29 21:59:04 +02:00
Gwendal Roué e47a584c3e TableRecord.selectionSQL can no longer be implemented 🤷 2020-04-29 21:51:02 +02:00
Gwendal Roué 188f51c513 Refactor handling of arguments during SQL generation 2020-04-29 21:27:14 +02:00
Gwendal Roué e800c71cbc Refactor SQLLiteral so that subqueries are no longer a special case 2020-04-29 20:20:13 +02:00
Gwendal Roué 3d86f45aa2 SQLRequestExpressible
This protocol makes it possible to write request.filter(column == subRequest)
2020-04-29 20:18:00 +02:00
Gwendal Roué 473bc3a88e SQLQueryGenerator handles the single result optimization. Make sure a single column is selected for expression/collection requests 2020-04-29 18:30:46 +02:00
Gwendal Roué 4b9336f5c5 TODO 2020-04-29 15:21:22 +02:00
Gwendal Roué 8bcf9257f6 TODO 2020-04-29 14:32:53 +02:00
Gwendal Roué ca59d706e9 Cleanup 2020-04-29 14:27:58 +02:00
Gwendal Roué 82ff6cb4c5 Cleanup 2020-04-29 14:24:25 +02:00
Gwendal Roué 21552d8838 SQLRequest & QueryInterfaceRequest are SQLExpression 2020-04-29 14:24:18 +02:00
Gwendal Roué 26f40efece TODO 2020-04-29 13:54:00 +02:00
Gwendal Roué c82dbb35ad SQLLiteral and SQLRequest no longer have sql and arguments properties 2020-04-29 13:52:29 +02:00
Gwendal Roué 84ca69d27c Value quoting can now require a database connection 2020-04-29 11:03:51 +02:00
Gwendal Roué 6dca9e1068 Cleanup 2020-04-29 09:49:24 +02:00
Gwendal Roué 8cb75dd814 Subqueries wip 2020-04-28 21:03:58 +02:00
Gwendal Roué 59e81f70bd Cleanup aggregates 2020-04-28 19:49:41 +02:00
Gwendal Roué 399766fe10 Fix #739 2020-04-28 19:19:30 +02:00
Gwendal Roué f543784241 TODO 2020-04-28 14:20:05 +02:00
Gwendal Roué 0b0f0e53da TODO 2020-04-26 18:04:57 +02:00
Gwendal Roué f738fdfa8e Cleanup Decodable behavior regarding missing keys and optionals 2020-04-26 14:19:29 +02:00
Gwendal Roué a8f7978ec4 Update documention after d0ba9e342c 2020-04-26 11:55:53 +02:00
Gwendal Roué d1af9dbdf1 Fix documentation comment 2020-04-25 20:27:25 +02:00
Gwendal Roué d0ba9e342c Turn selection and having clauses into promises. Give association aggregates access to the actual primary key, for better support for WITHOUT ROW ID tables. 2020-04-25 19:51:03 +02:00
Gwendal Roué b38ccb5f40 TODO 2020-04-25 15:15:06 +02:00
Gwendal Roué 605aad79ad Replace use of rowid by primary key when possible. Cleanup management of association cardinality
This is a backport of enhancements brought by the failed pull request https://github.com/groue/GRDB.swift/pull/767
2020-04-25 15:15:01 +02:00
174 changed files with 8003 additions and 4432 deletions

No files matched your search

+1
View File
@@ -3,6 +3,7 @@ included:
disabled_rules:
- cyclomatic_complexity
- duplicate_enum_cases
- file_length
- force_cast
- force_try
+19 -85
View File
@@ -30,179 +30,113 @@ jobs:
###########################################
## Test GRDB Xcode 11.4
- stage: Test GRDB Xcode 11.4
- name: "Test GRDB Xcode 11.4 - GRDBOSX"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBOSX (Swift 5.1, macOS)
script: make test_framework_GRDBOSX_maxSwift
- stage: Test GRDB Xcode 11.4
- name: "Test GRDB Xcode 11.4 - GRDBWatchOS"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBOSX (Swift 4.2, macOS)
script: make test_framework_GRDBOSX_minSwift
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBWatchOS (watchOS)
script: make test_framework_GRDBWatchOS
- stage: Test GRDB Xcode 11.4
- name: "Test GRDB Xcode 11.4 - GRDBiOS iOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 5.1, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget_maxSwift
- stage: Test GRDB Xcode 11.4
- name: "Test GRDB Xcode 11.4 - GRDBiOS iOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget_minSwift
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 5.1, iOS <MIN>)
script: make test_framework_GRDBiOS_minTarget
- stage: Test GRDB Xcode 11.4
- name: "Test GRDB Xcode 11.4 - GRDBtvOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBtvOS (Swift 5.1, tvOS <MAX>)
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
- stage: Test GRDB Xcode 11.4
- name: "Test GRDB Xcode 11.4 - GRDBtvOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBtvOS (Swift 4.2, tvOS <MAX>)
script: make test_framework_GRDBtvOS_maxTarget_minSwift
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBtvOS (Swift 5.1, tvOS <MIN>)
script: make test_framework_GRDBtvOS_minTarget
- stage: Test GRDB Xcode 11.4
- name: "Test GRDB Xcode 11.4 - SPM"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDB [SPM] (macOS)
script: make test_SPM
###########################################
## Test GRDBCustom Xcode 11.4
- stage: Test GRDBCustom Xcode 11.4
- name: "Test GRDBCustom Xcode 11.4 - GRDBOSX"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBOSX (Swift 5.1, macOS)
script: make test_framework_GRDBCustomSQLiteOSX
- stage: Test GRDBCustom Xcode 11.4
- name: "Test GRDBCustom Xcode 11.4 - GRDBiOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 5.1, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
- stage: Test GRDBCustom Xcode 11.4
- name: "Test GRDBCustom Xcode 11.4 - GRDBiOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_minSwift
- stage: Test GRDBCustom Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 5.1, iOS <MIN>)
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
###########################################
## Test SQLCipher Xcode 11.4
- stage: Test SQLCipher Xcode 11.4
- name: "Test SQLCipher Xcode 11.4 - SQLCipher 3"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=SQLCipher 3
script: make test_framework_SQLCipher3
- stage: Test SQLCipher Xcode 11.4
- name: "Test SQLCipher Xcode 11.4 - SQLCipher 4"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=SQLCipher 4
script: make test_framework_SQLCipher4
###########################################
## Test Installation Xcode 11.4
# Manual Install
- stage: Test Installation Xcode 11.4
- name: "Test Installation Xcode 11.4 - Manual Install"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=Manual Install
script: make test_install_manual
# CocoaPods Lint
- stage: Test Installation Xcode 11.4
- name: "Test Installation Xcode 11.4 - CocoaPods Lint"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=CocoaPods Lint
script: make test_CocoaPodsLint_GRDB
# CocoaPods Install GRDB
- stage: Test Installation Xcode 11.4
- name: "Test Installation Xcode 11.4 - CocoaPods Framework"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=CocoaPods GRDB (framework)
script: make test_install_GRDB_CocoaPods_framework
# CocoaPods Install GRDB
- stage: Test Installation Xcode 11.4
- name: "Test Installation Xcode 11.4 - CocoaPods Static"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=CocoaPods GRDB (static)
script: make test_install_GRDB_CocoaPods_static
# SPM Install
- stage: Test Installation Xcode 11.4
- name: "Test Installation Xcode 11.4 - SPM Package"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=SPM Package
script: make test_install_SPM_Package
# SPM Install
- stage: Test Installation Xcode 11.4
- name: "Test Installation Xcode 11.4 - SPM Package in Xcode Project"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=SPM Package in Xcode Project
script: make test_install_SPM_Project
# Custom SQLite Install
- stage: Test Installation Xcode 11.4
- name: "Test Installation Xcode 11.4 - Custom SQLite"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=Custom SQLite
script: make test_install_customSQLite
+12
View File
@@ -4,6 +4,18 @@ Here is a list of people who were happy to meet GRDB :-)
---
https://twitter.com/stephencelis/status/1263518304980918274
> GRDB.swift is great! (I say this as the person that started SQLite.swift long ago.) And @groue’s very helpful and friendly.
---
https://twitter.com/peres/status/1262682199482142720
> GRDB in already in my top3 when it comes to documentation. Clearly and pragmatically explained.GRDB in already in my top3 when it comes to documentation. Clearly and pragmatically explained.
---
https://twitter.com/layoutsubviews/status/1249940744929816582
> Mixing SQLite / GRDB with Combine is my whole world right now, and it is delightful.
+147 -8
View File
@@ -5,15 +5,13 @@ All notable changes to this project will be documented in this file.
GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library.
<!--
[Next Release](#next-release)
-->
#### 5.x Releases
- `5.0.x` Development - [GRDB5 Branch](#grdb5-branch)
- `5.0.0` Betas - [5.0.0-beta](#500-beta) | [5.0.0-beta.2](#500-beta2) | [5.0.0-beta.3](#500-beta3) | [5.0.0-beta.4](#500-beta4) | [5.0.0-beta.5](#500-beta5)
#### 4.x Releases
@@ -76,14 +74,148 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
## Next Release
-->
## GRDB5 Branch
## 5.0.0-beta.5
Released June 15, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.4...v5.0.0-beta.5)
- **Breaking Change** [#795](https://github.com/groue/GRDB.swift/pull/795): Enhanced support for WAL Checkpoints
- **New**: `Database.maximumStatementArgumentCount` returns the maximum number of arguments accepted by an SQLite statement.
- **New**: Optimize DatabasePool handling of ValueObservation when SQLite is compiled with the SQLITE_ENABLE_SNAPSHOT option. We are now able to avoid fetching the observed value when we can prove that the database wasn't changed between the initial fetch and the beginning of transaction tracking. This optimization avoids duplicate notifications.
- **New**: The query interface now exposes the primary key through `TableRecord.primaryKey`, as well as the `selectPrimaryKey(as:)` method.
### Documentation Diff
- The [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) Guide helps migrating your apps and turn your attention where it needs to focus during the upgrade.
- The [ValueObservation](README.md#valueobservation) chapter has been fully rewritten and describes the new ValueObservation behaviors.
- The [DatabaseError](README.md#databaseerror) chapter demonstrates the new way to catch and match DatabaseError on their codes, in a fashion similar to CocoaError et al.
- The [Batch Updates](README.md#update-requests) chapter has been updated for the new `set(to:)` method.
- The [Demo Application](Documentation/DemoApps/GRDBDemoiOS) was updated for better conformance with the [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) Guide.
- A new [FAQ: Associations](README.md#faq-associations) addresses three frequent questions:
- [How do I filter records and only keep those that are associated to another record?](README.md#how-do-i-filter-records-and-only-keep-those-that-are-associated-to-another-record)
- [How do I filter records and only keep those that are NOT associated to another record?](README.md#how-do-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record)
- [How do I select only one column of an associated record?](README.md#how-do-i-select-only-one-column-of-an-associated-record)
- The guide for [Custom SQLite builds](Documentation/CustomSQLiteBuilds.md) now recommends enabling the `SQLITE_ENABLE_SNAPSHOT` option.
## 5.0.0-beta.4
Released June 6, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.3...v5.0.0-beta.4)
### Documentation Diff
- [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) was updated for RxGRDB and GRDBCombine 1.0 beta 2, which haved change their way to configure how ValueObservation schedules fresh database values.
- The [SQL Functions](README.md#sql-functions) chapter was updated for the new `julianDay` and `dateTime` functions.
### New
- [#794](https://github.com/groue/GRDB.swift/pull/794): Name of Database Connections
- Add the `julianDay` and `dateTime` functions
## 5.0.0-beta.3
Released June 1, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.2...v5.0.0-beta.3)
### Documentation Diff
- Updated FAQ: [How do I print a request as SQL?](README.md#how-do-i-print-a-request-as-sql)
- New FAQ: [How do I monitor the duration of database statements execution?](README.md#how-do-i-monitor-the-duration-of-database-statements-execution)
### Fixed
- [#784](https://github.com/groue/GRDB.swift/pull/784): Fix observation of eager-loaded to-many associations
### Breaking Changes
- [#790](https://github.com/groue/GRDB.swift/pull/790): Bump required iOS version to 10.0
- [#791](https://github.com/groue/GRDB.swift/pull/791): Extend tracing of statement execution
## 5.0.0-beta.2
Released May 11, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta...v5.0.0-beta.2)
### Documentation Diff
- [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) describes the sunsetting of custom `FetchRequest` types.
- The [Sharing a Database](Documentation/SharingADatabase.md) guide has an updated recommendation for opening writer connections to a shared database.
### New
- [#772](https://github.com/groue/GRDB.swift/pull/772): Update the Database Sharing Guide with mention of the persistent WAL mode
- [#775](https://github.com/groue/GRDB.swift/pull/775): DatabaseMigrator can check if it has been superseded
### Breaking Changes
- [#774](https://github.com/groue/GRDB.swift/pull/774): All requests are usable as SQL expressions and collections
### Fixed
- [#773](https://github.com/groue/GRDB.swift/pull/773): Allow subqueries to refer to outer tables
## 5.0.0-beta
Released May 2, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v4.14.0...v5.0.0-beta)
GRDB 5 is a release focused on **Swift 5.2**, and **removing technical debt**.
There are breaking changes, though as few as possible. They open the door for future library improvements. And they have GRDB, [GRDBCombine](http://github.com/groue/GRDBCombine), and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) offer a common behavior.
New features include support for SQL subqueries, and a simplified handling of database errors. The most demanding users will also find it easier to switch between the system SQLite, SQLCipher, and custom SQLite builds.
<details>
<summary>A glimpse on the new features</summary>
All requests can now be used as subqueries:
```swift
// Define a request with the query interface or raw SQL
let maximumScore = Player.select(max(Column("score")))
let maximumScore: SQLRequest<Int> = "SELECT MAX(score) FROM player"
// Use the request as a subquery in the query interface
let request = Player.filter(Column("score") == maximumScore)
let bestPlayers = try request.fetchAll(db)
// Use the request as a subquery in SQL requests
let request: SQLRequest<Player> = "SELECT * FROM player WHERE score = (\(maximumScore))"
let bestPlayers = try request.fetchAll(db)
```
Catch specific SQLite error codes in a simplified fashion:
```swift
do {
try ...
} catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY {
// foreign key constraint error
} catch DatabaseError.SQLITE_CONSTRAINT {
// any other constraint error
} catch {
// any other database error
}
```
Reuse the same code for system SQLite, SQLCipher, and custom SQLite builds:
```swift
// Supported in all GRDB flavors
import GRDB
let sqliteVersion = String(cString: sqlite3_libversion())
```
</details>
### Documentation Diff
- **[Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)**: how to upgrade your apps, and deal with breaking changes.
- [ValueObservation](README.md#valueobservation): this chapter describes the new ValueObservation behaviors.
- [DatabaseError](README.md#databaseerror): learn how to catch and match DatabaseError on their codes, in a fashion similar to `CocoaError`.
- [Batch Updates](README.md#update-requests): this chapter is updated for the new `set(to:)` method.
- [SQL Operators](README.md#sql-operators): introduces support for SQL and query interface subqueries.
- [How do I print a request as SQL?](README.md#how-do-i-print-a-request-as-sql) This FAQ was updated for GRDB 5.
- [SQL Interpolation](Documentation/SQLInterpolation.md): this guide now describes how to embed subqueries and record columns in your SQL literals.
- [Joined Queries Support](README.md#joined-queries-support): describes the GRDB 5 way of dealing with complex and hand-crafted SQL queries.
- [Raw SQLite Pointers](README.md#raw-sqlite-pointers) and [Custom SQLite builds](Documentation/CustomSQLiteBuilds.md): `import GRDB` now provides access to the full [C SQLite API](https://www.sqlite.org/capi3ref.html), and custom SQLite builds.
### New
@@ -108,6 +240,13 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
- [#747](https://github.com/groue/GRDB.swift/pull/747): Rename GRDBCustomSQLite to GRDB
- [#750](https://github.com/groue/GRDB.swift/pull/750): Batch updates do not need any operator
- [#752](https://github.com/groue/GRDB.swift/pull/752): Remove ValueObservation.combine
- [#770](https://github.com/groue/GRDB.swift/pull/770): Subqueries
### Fixed
- [#601](https://github.com/groue/GRDB.swift/pull/601): ValueObservation won't start until concurrent write transaction has ended
- [#697](https://github.com/groue/GRDB.swift/pull/697): `SQLInterpolation` could not work with `QueryInterfaceRequest`
- [#743](https://github.com/groue/GRDB.swift/pull/743): Rename GRDBCustomSQLite to GRDB for compatibility with dependents?
## 4.14.0
+1 -247
View File
@@ -1,250 +1,4 @@
Sharing a Database in an App Group Container
============================================
On iOS, you can share database files between multiple processes by storing them in an [App Group Container](https://developer.apple.com/documentation/foundation/nsfilemanager/1412643-containerurlforsecurityapplicati).
A shared database is accessed from several SQLite connections, from several processes. This creates challenges at various levels:
1. **Database setup** may be attempted by multiple processes, concurrently.
2. **SQLite** may throw `SQLITE_BUSY` errors, code 5, "database is locked".
3. **iOS** may kill your application with a `0xDEAD10CC` exception.
4. **GRDB** database observation misses changes performed by external processes.
We'll address all of those challenges below.
- [Use a Database Pool]
- [How to limit the `SQLITE_BUSY` error]
- [How to limit the `0xDEAD10CC` exception]
- [How to perform cross-process database observation]
## Use a Database Pool
In order to access a shared database, use a [Database Pool]. It opens the database in the [WAL mode](https://www.sqlite.org/wal.html), which helps sharing a database.
Since several processes may open the database at the same time, protect the creation of the database pool with an [NSFileCoordinator].
- In a process that can create and write in the database, use this sample code:
```swift
/// Returns an initialized database pool at the shared location databaseURL
func openSharedDatabase(at databaseURL: URL) throws -> DatabasePool {
let coordinator = NSFileCoordinator(filePresenter: nil)
var coordinatorError: NSError?
var dbPool: DatabasePool?
var dbError: Error?
coordinator.coordinate(writingItemAt: databaseURL, options: .forMerging, error: &coordinatorError, byAccessor: { url in
do {
dbPool = try openDatabase(at: url)
} catch {
dbError = error
}
})
if let error = dbError ?? coordinatorError {
throw error
}
return dbPool!
}
private func openDatabase(at databaseURL: URL) throws -> DatabasePool {
let dbPool = try DatabasePool(path: databaseURL.path)
// Perform here other database setups, such as defining
// the database schema with a DatabaseMigrator.
try migrator.migrate(dbPool)
return dbPool
}
```
- In a process that only reads in the database, use this sample code:
```swift
/// Returns an initialized database pool at the shared location databaseURL,
/// or nil if the database is not created yet, or does not have the required
/// schema version.
func openSharedReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
let coordinator = NSFileCoordinator(filePresenter: nil)
var coordinatorError: NSError?
var dbPool: DatabasePool?
var dbError: Error?
coordinator.coordinate(readingItemAt: databaseURL, options: .withoutChanges, error: &coordinatorError, byAccessor: { url in
do {
dbPool = try openReadOnlyDatabase(at: url)
} catch {
dbError = error
}
})
if let error = dbError ?? coordinatorError {
throw error
}
return dbPool
}
private func openReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
do {
var configuration = Configuration()
configuration.readonly = true
let dbPool = try DatabasePool(path: databaseURL.path, configuration: configuration)
// Check here if the database schema is correct, for example
// with a DatabaseMigrator.
if try dbPool.read(migrator.hasCompletedMigrations) {
return dbPool
} else {
return nil
}
} catch {
if FileManager.default.fileExists(atPath: databaseURL.path) {
throw error
} else {
return nil
}
}
}
```
## How to limit the `SQLITE_BUSY` error
> The SQLITE_BUSY result code indicates that the database file could not be written (or in some cases read) because of concurrent activity by some other database connection, usually a database connection in a separate process.
See https://www.sqlite.org/rescode.html#busy for more information about this error.
If several processes want to write in the database, configure the database pool of each process that wants to write:
```swift
var configuration = Configuration()
configuration.busyMode = .timeout(/* a TimeInterval */)
configuration.defaultTransactionKind = .immediate
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
With such a setup, you may still get `SQLITE_BUSY` (5, "database is locked") errors from all write operations. They will occur if the database remains locked by another process for longer than the specified timeout.
```swift
do {
try dbPool.write { db in ... }
} catch let error as DatabaseError where error.resultCode == .SQLITE_BUSY {
// Another process won't let you write. Deal with it.
}
```
> :bulb: **Tip**: In order to be nice to other processes, measure the duration of your longest writes, and attempt at optimizing the ones that last for too long.
## How to limit the `0xDEAD10CC` exception
> The exception code 0xDEAD10CC indicates that an application has been terminated by the OS because it held on to a file lock or sqlite database lock during suspension.
See https://developer.apple.com/library/archive/technotes/tn2151/_index.html for more information about this exception.
1. If you use SQLCipher, use SQLCipher 4+, and call the `cipher_plaintext_header_size` pragma from your database preparation function:
```swift
var configuration = Configuration()
configuration.prepareDatabase = { (db: Database) in
try db.usePassphrase("secret")
try db.execute(sql: "PRAGMA cipher_plaintext_header_size = 32")
}
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
This will avoid https://github.com/sqlcipher/sqlcipher/issues/255.
2. [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features) In each process that wants to write in the database:
Set the `observesSuspensionNotifications` configuration flag:
```swift
var configuration = Configuration()
configuration.suspendsOnBackgroundTimeExpiration = true
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
Post `Database.suspendNotification` when the application is about to be [suspended](https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle). You can for example post this notification from `UIApplicationDelegate.applicationDidEnterBackground(_:)`, or in the expiration handler of a [background task](https://forums.developer.apple.com/thread/85066).
```swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func applicationDidEnterBackground(_ application: UIApplication) {
// Suspend databases
NotificationCenter.default.post(name: Database.suspendNotification, object: self)
}
}
```
Post `Database.resumeNotification` from `UIApplicationDelegate.applicationWillEnterForeground(_:)` (or `SceneDelegate.sceneWillEnterForeground(_:)` for scene-based applications):
```swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func applicationWillEnterForeground(_ application: UIApplication) {
// Resume databases
NotificationCenter.default.post(name: Database.resumeNotification, object: self)
}
}
```
If the application uses the background modes supported by iOS, post `Database.resumeNotification` method from each and every background mode callback that may use the database. For example, if your application supports background fetches:
```swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// Resume databases
NotificationCenter.default.post(name: Database.resumeNotification, object: self)
// Proceed with background fetch
...
}
}
```
Suspended databases greatly reduce the odds of `0xDEAD10CC` exception are greatly reduced. If you see one in your crash logs, please open an issue!
In exchange, you will get `SQLITE_INTERRUPT` (9) or `SQLITE_ABORT` (4) errors, with messages "Database is suspended", "Transaction was aborted", or "interrupted", for any attempt at writing in the database when it is suspended.
You can catch those errors:
```swift
do {
try dbPool.write { db in ... }
} catch let error as DatabaseError where error.isInterruptionError {
// Oops, the database is suspended.
// Maybe try again after database is resumed?
}
```
## How to perform cross-process database observation
GRDB [Database Observation] features, as well as [GRDBCombine] and [RxGRDB], are not able to notify 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]:
```swift
// Notify all changes made to the "player" and "team" database tables
let observation = DatabaseRegionObservation(tracking: Player.all(), Team.all())
let observer = try observation.start(in: dbPool) { (db: Database) in
// Notify other processes
}
// Notify all changes made to the database
let observation = DatabaseRegionObservation(tracking: DatabaseRegion.fullDatabase)
let observer = try observation.start(in: dbPool) { (db: Database) in
// Notify other processes
}
```
[Use a Database Pool]: #use-a-database-pool
[How to limit the `SQLITE_BUSY` error]: #how-to-limit-the-sqlite_busy-error
[How to limit the `0xDEAD10CC` exception]: #how-to-limit-the-0xdead10cc-exception
[How to perform cross-process database observation]: #how-to-perform-cross-process-database-observation
[Database Pool]: ../README.md#database-pools
[Database Observation]: ../README.md#database-changes-observation
[GRDBCombine]: http://github.com/groue/GRDBCombine
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
[NSFileCoordinator]: https://developer.apple.com/documentation/foundation/nsfilecoordinator
[CFNotificationCenterGetDarwinNotifyCenter]: https://developer.apple.com/documentation/corefoundation/1542572-cfnotificationcentergetdarwinnot
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
This guide [has moved](SharingADatabase.md).
+25 -17
View File
@@ -39,7 +39,14 @@ GRDB Associations
- [Aggregate Operations]
- [Isolation of Multiple Aggregates]
- [DerivableRequest Protocol]
- [Known Issues]
**[FAQ]**
- [How do I filter records and only keep those that are associated to another record?](../README.md#how-do-i-filter-records-and-only-keep-those-that-are-associated-to-another-record)
- [How do I filter records and only keep those that are NOT associated to another record?](../README.md#how-do-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record)
- [How do I select only one column of an associated record?](../README.md#how-do-i-select-only-one-column-of-an-associated-record)
**[Known Issues]**
## Associations Benefits
@@ -1830,7 +1837,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
}
// SELECT author.*,
// COUNT(DISTINCT book.rowid) AS bookCount,
// COUNT(DISTINCT book.id) AS bookCount,
// MAX(book.year) AS maxBookYear,
// FROM author
// LEFT JOIN book ON book.authorId = author.id
@@ -1923,7 +1930,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
FROM author
LEFT JOIN book ON book.authorId = author.id
GROUP BY author.id
HAVING COUNT(DISTINCT book.rowid) = 0
HAVING COUNT(DISTINCT book.id) = 0
```
</details>
@@ -1942,7 +1949,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
FROM author
LEFT JOIN book ON book.authorId = author.id
GROUP BY author.id
HAVING COUNT(DISTINCT book.rowid) > 0
HAVING COUNT(DISTINCT book.id) > 0
```
</details>
@@ -1961,7 +1968,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
FROM author
LEFT JOIN book ON book.authorId = author.id
GROUP BY author.id
HAVING COUNT(DISTINCT book.rowid) >= 2
HAVING COUNT(DISTINCT book.id) >= 2
```
</details>
@@ -1999,7 +2006,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
FROM author
LEFT JOIN book ON book.authorId = author.id AND book.kind = 'novel'
GROUP BY author.id
HAVING COUNT(DISTINCT book.rowid) > 0
HAVING COUNT(DISTINCT book.id) > 0
```
</details>
@@ -2020,7 +2027,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
LEFT JOIN book ON book.authorId = author.id
LEFT JOIN painting ON painting.authorId = author.id
GROUP BY author.id
HAVING COUNT(DISTINCT book.rowid) > COUNT(DISTINCT painting.rowid)
HAVING COUNT(DISTINCT book.id) > COUNT(DISTINCT painting.id)
```
</details>
@@ -2040,7 +2047,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
LEFT JOIN book ON book.authorId = author.id
LEFT JOIN painting ON painting.authorId = author.id
GROUP BY author.id
HAVING ((COUNT(DISTINCT book.rowid) = 0) AND (COUNT(DISTINCT painting.rowid) > 0))
HAVING ((COUNT(DISTINCT book.id) = 0) AND (COUNT(DISTINCT painting.id) > 0))
```
</details>
@@ -2065,7 +2072,7 @@ Aggregates can be modified and combined with Swift operators:
LEFT JOIN book ON book.authorId = author.id
LEFT JOIN painting ON painting.authorId = author.id
GROUP BY author.id
HAVING ((COUNT(DISTINCT book.rowid) = 0) AND (COUNT(DISTINCT painting.rowid) = 0))
HAVING ((COUNT(DISTINCT book.id) = 0) AND (COUNT(DISTINCT painting.id) = 0))
```
</details>
@@ -2101,8 +2108,8 @@ Aggregates can be modified and combined with Swift operators:
```sql
SELECT author.*,
(COUNT(DISTINCT book.rowid) +
COUNT(DISTINCT painting.rowid)) AS workCount
(COUNT(DISTINCT book.id) +
COUNT(DISTINCT painting.id)) AS workCount
FROM author
LEFT JOIN book ON book.authorId = author.id
LEFT JOIN painting ON painting.authorId = author.id
@@ -2183,7 +2190,7 @@ In this other example, the `Author.books` and `Author.paintings` have the distin
```sql
SELECT author.*,
(COUNT(DISTINCT book.rowid) + COUNT(DISTINCT painting.rowid)) AS workCount
(COUNT(DISTINCT book.id) + COUNT(DISTINCT painting.id)) AS workCount
FROM author
LEFT JOIN book ON book.authorId = author.id
LEFT JOIN painting ON painting.authorId = author.id
@@ -2218,8 +2225,8 @@ But in the following example, we use the same association `Author.books` twice,
```sql
SELECT author.*,
COUNT(DISTINCT book1.rowid) AS novelCount,
COUNT(DISTINCT book2.rowid) AS theatrePlayCount
COUNT(DISTINCT book1.id) AS novelCount,
COUNT(DISTINCT book2.id) AS theatrePlayCount
FROM author
LEFT JOIN book book1 ON book1.authorId = author.id AND book1.kind = 'novel'
LEFT JOIN book book2 ON book2.authorId = author.id AND book2.kind = 'theatrePlay'
@@ -2258,8 +2265,8 @@ But in the following example, we use the same association `Author.books` twice,
```sql
SELECT author.*,
COUNT(DISTINCT book.rowid) AS novelCount,
COUNT(DISTINCT book.rowid) AS theatrePlayCount
COUNT(DISTINCT book.id) AS novelCount,
COUNT(DISTINCT book.id) AS theatrePlayCount
FROM author
LEFT JOIN book ON book.authorId = author.id
AND (book.kind = 'novel' AND book.kind = 'theatrePlay')
@@ -2422,7 +2429,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[Ordered Associations]: #ordered-associations
[The Types of Associations]: #the-types-of-associations
[FetchableRecord]: ../README.md#fetchablerecord-protocols
[migration]: ../README.md#migrations
[migration]: Migrations.md
[Record]: ../README.md#records
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
[Associations and the Database Schema]: #associations-and-the-database-schema
@@ -2468,3 +2475,4 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[persistence methods]: ../README.md#persistence-methods
[database observation tools]: ../README.md#database-changes-observation
[ValueObservation]: ../README.md#valueobservation
[FAQ]: ../README.md#faq-associations
+6 -4
View File
@@ -19,7 +19,9 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
git submodule update --init SQLiteCustom/src
```
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5` and `SQLITE_ENABLE_PREUPDATE_HOOK`.
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5`, `SQLITE_ENABLE_PREUPDATE_HOOK`.
It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](../README.md#valueobservation) when you use a [Database Pool](../README.md#database-pools).
3. Create a folder named `GRDBCustomSQLite` somewhere in your project directory.
@@ -30,7 +32,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
```xcconfig
// As many -D options as there are custom SQLite compilation options
// Note: there is no space between -D and the option name.
CUSTOM_SQLLIBRARY_CFLAGS = -DSQLITE_ENABLE_FTS5 -DSQLITE_ENABLE_PREUPDATE_HOOK
CUSTOM_SQLLIBRARY_CFLAGS = -DSQLITE_ENABLE_SNAPSHOT -DSQLITE_ENABLE_FTS5
```
- `GRDBCustomSQLite-USER.xcconfig`: this file lets GRDB know about extra compilation flags, and enables extra GRDB APIs.
@@ -38,15 +40,15 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
```xcconfig
// As many -D options as there are custom SQLite compilation options
// Note: there is one space between -D and the option name.
CUSTOM_OTHER_SWIFT_FLAGS = -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK
CUSTOM_OTHER_SWIFT_FLAGS = -D SQLITE_ENABLE_SNAPSHOT -D SQLITE_ENABLE_FTS5
```
- `GRDBCustomSQLite-USER.h`: this file lets your application know about extra compilation flags.
```c
// As many #define as there are custom SQLite compilation options
#define SQLITE_ENABLE_SNAPSHOT
#define SQLITE_ENABLE_FTS5
#define SQLITE_ENABLE_PREUPDATE_HOOK
```
- `GRDBCustomSQLite-INSTALL.sh`: this file installs the three other files.
@@ -25,7 +25,7 @@
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */; };
56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Player.swift */; };
56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */; };
56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */; };
56B036241E8D9F4C003B6DA4 /* PlayerListViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -181,7 +181,7 @@
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
56B0361A1E8D9F38003B6DA4 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = "<group>"; };
56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = "<group>"; };
56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayersViewController.swift; sourceTree = "<group>"; };
56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerListViewController.swift; sourceTree = "<group>"; };
56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = "<group>"; };
/* End PBXFileReference section */
@@ -273,15 +273,15 @@
56B036051E8D9EBE003B6DA4 /* GRDBDemoiOS */ = {
isa = PBXGroup;
children = (
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */,
56B036121E8D9EBE003B6DA4 /* Info.plist */,
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */,
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */,
56B0361A1E8D9F38003B6DA4 /* Player.swift */,
56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */,
56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */,
56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */,
56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */,
56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */,
56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */,
56B036121E8D9EBE003B6DA4 /* Info.plist */,
56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */,
);
path = GRDBDemoiOS;
sourceTree = "<group>";
@@ -507,7 +507,7 @@
56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */,
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */,
56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */,
56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */,
56B036241E8D9F4C003B6DA4 /* PlayerListViewController.swift in Sources */,
56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -1,26 +1,22 @@
import GRDB
/// A type responsible for initializing the application database.
/// AppDatabase lets the application access the database.
///
/// See AppDelegate.setupDatabase()
struct AppDatabase {
/// It applies the pratices recommended at
/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
final class AppDatabase {
private let dbQueue: DatabaseQueue
/// Creates a fully initialized database at path
static func openDatabase(atPath path: String) throws -> DatabaseQueue {
// Connect to the database
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
let dbQueue = try DatabaseQueue(path: path)
// Define the database schema
/// Creates an AppDatabase and updates its schema if necessary.
init(_ dbQueue: DatabaseQueue) throws {
self.dbQueue = dbQueue
try migrator.migrate(dbQueue)
return dbQueue
}
/// The DatabaseMigrator that defines the database schema.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#migrations
static var migrator: DatabaseMigrator {
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
migrator.registerMigration("createPlayer") { db in
@@ -54,3 +50,107 @@ struct AppDatabase {
}
}
// MARK: - Database Access
//
// This extension defines methods that fulfill application needs, both in terms
// of writes and reads.
extension AppDatabase {
// MARK: Writes
/// Save (insert or update) a player.
func savePlayer(_ player: inout Player) throws {
try dbQueue.write { db in
try player.save(db)
}
}
/// Delete one player
func deletePlayer(_ player: Player) throws {
try dbQueue.write { db in
_ = try player.delete(db)
}
}
/// Delete all players
func deleteAllPlayers() throws {
try dbQueue.write { db in
_ = try Player.deleteAll(db)
}
}
/// Refresh all players (by performing some random changes, for demo purpose).
func refreshPlayers() throws {
try dbQueue.write { db in
if try Player.fetchCount(db) == 0 {
// Insert new random players
for _ in 0..<8 {
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
try player.insert(db)
}
} else {
// Insert a player
if Bool.random() {
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
try player.insert(db)
}
// Delete a random player
if Bool.random() {
try Player.order(sql: "RANDOM()").limit(1).deleteAll(db)
}
// Update some players
for var player in try Player.fetchAll(db) where Bool.random() {
try player.updateChanges(db) {
$0.score = Player.randomScore()
}
}
}
}
}
// MARK: Reads
/// Tracks changes in the number of players
func observePlayerCount(
onError: @escaping (Error) -> Void,
onChange: @escaping (Int) -> Void)
-> DatabaseCancellable
{
ValueObservation
.tracking(Player.fetchCount)
.start(
in: dbQueue,
onError: onError,
onChange: onChange)
}
/// Tracks changes in players ordered by name
func observePlayersOrderedByName(
onError: @escaping (Error) -> Void,
onChange: @escaping ([Player]) -> Void)
-> DatabaseCancellable
{
ValueObservation
.tracking(Player.all().orderedByName().fetchAll)
.start(
in: dbQueue,
onError: onError,
onChange: onChange)
}
/// Tracks changes in players ordered by score
func observePlayersOrderedByScore(
onError: @escaping (Error) -> Void,
onChange: @escaping ([Player]) -> Void)
-> DatabaseCancellable
{
ValueObservation
.tracking(Player.all().orderedByScore().fetchAll)
.start(
in: dbQueue,
onError: onError,
onChange: onChange)
}
}
@@ -1,8 +1,8 @@
import UIKit
import GRDB
// The shared database queue
var dbQueue: DatabaseQueue!
// The shared application database
var appDatabase: AppDatabase!
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
@@ -14,9 +14,14 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
}
private func setupDatabase(_ application: UIApplication) throws {
// AppDelegate is responsible for choosing the location of the database file.
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
let databaseURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("db.sqlite")
dbQueue = try AppDatabase.openDatabase(atPath: databaseURL.path)
let dbQueue = try DatabaseQueue(path: databaseURL.path)
// Create the shared application database
appDatabase = try AppDatabase(dbQueue)
}
}
@@ -1,8 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="15505" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
<device id="retina4_7" orientation="portrait" appearance="light"/>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="16097" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="15510"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="16087"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
@@ -10,25 +10,25 @@
<scene sceneID="Juk-Ad-tZ2">
<objects>
<tableViewController id="iNr-Oe-muq" customClass="PlayerEditionViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" dataMode="static" style="plain" separatorStyle="none" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="28" sectionFooterHeight="28" id="vlV-lc-eQA">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" dataMode="static" style="insetGrouped" separatorStyle="none" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="-1" estimatedSectionHeaderHeight="-1" sectionFooterHeight="-1" estimatedSectionFooterHeight="-1" id="vlV-lc-eQA">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<sections>
<tableViewSection id="Nzq-eO-jT3">
<tableViewSection headerTitle="Name" id="Nzq-eO-jT3">
<cells>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="2gb-gB-918">
<rect key="frame" x="0.0" y="28" width="375" height="44"/>
<rect key="frame" x="20" y="55.5" width="374" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="2gb-gB-918" id="iyM-TJ-JB4">
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<rect key="frame" x="0.0" y="0.0" width="374" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Name" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="m5m-Zs-j0z">
<rect key="frame" x="16" y="11.5" width="343" height="21"/>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="m5m-Zs-j0z">
<rect key="frame" x="20" y="11" width="334" height="22"/>
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
<textInputTraits key="textInputTraits" autocapitalizationType="words" autocorrectionType="no" spellCheckingType="no" returnKeyType="next"/>
<connections>
<action selector="textFieldDidChange:" destination="iNr-Oe-muq" eventType="editingChanged" id="EmC-Rp-f6S"/>
<outlet property="delegate" destination="iNr-Oe-muq" id="K2p-7d-teD"/>
</connections>
</textField>
@@ -40,17 +40,24 @@
</constraints>
</tableViewCellContentView>
</tableViewCell>
</cells>
</tableViewSection>
<tableViewSection headerTitle="Score" id="Urb-uF-sj1">
<cells>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="vp3-Ft-Gth">
<rect key="frame" x="0.0" y="72" width="375" height="44"/>
<rect key="frame" x="20" y="155" width="374" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="vp3-Ft-Gth" id="ccO-0O-u72">
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<rect key="frame" x="0.0" y="0.0" width="374" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Score" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="rZ9-Fa-cyr">
<rect key="frame" x="16" y="11.5" width="343" height="21"/>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="0" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="rZ9-Fa-cyr">
<rect key="frame" x="20" y="11" width="334" height="22"/>
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
<textInputTraits key="textInputTraits" autocorrectionType="no" spellCheckingType="no" keyboardType="numberPad" returnKeyType="done"/>
<connections>
<action selector="textFieldDidChange:" destination="iNr-Oe-muq" eventType="editingChanged" id="ebo-2z-Z9P"/>
</connections>
</textField>
</subviews>
<constraints>
@@ -101,7 +108,7 @@
<objects>
<navigationController id="ein-Sr-i8w" sceneMemberID="viewController">
<navigationBar key="navigationBar" contentMode="scaleToFill" id="zIT-dB-Mfo">
<rect key="frame" x="0.0" y="0.0" width="375" height="56"/>
<rect key="frame" x="0.0" y="0.0" width="414" height="56"/>
<autoresizingMask key="autoresizingMask"/>
</navigationBar>
<connections>
@@ -117,7 +124,7 @@
<objects>
<navigationController id="UAh-8N-CM8" sceneMemberID="viewController">
<navigationBar key="navigationBar" contentMode="scaleToFill" id="U7d-1C-GnL">
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
<rect key="frame" x="0.0" y="44" width="414" height="44"/>
<autoresizingMask key="autoresizingMask"/>
</navigationBar>
<connections>
@@ -131,27 +138,27 @@
<!--Hall Of Fame-->
<scene sceneID="9su-ms-vdJ">
<objects>
<tableViewController id="PJp-Eq-ZjA" customClass="PlayersViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
<tableViewController id="PJp-Eq-ZjA" customClass="PlayerListViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="-1" estimatedSectionHeaderHeight="-1" sectionFooterHeight="-1" estimatedSectionFooterHeight="-1" id="tX0-ON-WSI">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<prototypes>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" reuseIdentifier="Player" textLabel="G8y-VE-YRu" detailTextLabel="NNc-J4-xiE" style="IBUITableViewCellStyleValue1" id="bFj-Hd-fwd">
<rect key="frame" x="0.0" y="28" width="375" height="43.5"/>
<rect key="frame" x="0.0" y="28" width="414" height="43.5"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="bFj-Hd-fwd" id="kDf-TZ-xhb">
<rect key="frame" x="0.0" y="0.0" width="348" height="43.5"/>
<rect key="frame" x="0.0" y="0.0" width="383" height="43.5"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontForContentSizeCategory="YES" adjustsFontSizeToFit="NO" id="G8y-VE-YRu">
<rect key="frame" x="16" y="12" width="33.5" height="20.5"/>
<rect key="frame" x="20" y="12" width="33.5" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Detail" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontForContentSizeCategory="YES" adjustsFontSizeToFit="NO" id="NNc-J4-xiE">
<rect key="frame" x="296" y="12" width="44" height="20.5"/>
<rect key="frame" x="331" y="12" width="44" height="20.5"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
<color key="textColor" systemColor="secondaryLabelColor" red="0.23529411759999999" green="0.23529411759999999" blue="0.26274509800000001" alpha="0.59999999999999998" colorSpace="custom" customColorSpace="sRGB"/>
@@ -1,23 +1,23 @@
import GRDB
// A plain Player struct
/// The Player struct
struct Player {
// Prefer Int64 for auto-incremented database ids
var id: Int64?
var id: Int64? // Use Int64 for auto-incremented database ids
var name: String
var score: Int
}
// Hashable conformance supports tableView diffing
/// Hashable conformance supports tableView diffing
extension Player: Hashable { }
// MARK: - Persistence
// Turn Player into a Codable Record.
// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
/// Make Player a Codable Record.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
// Define database columns from CodingKeys
private enum Columns {
fileprivate enum Columns {
static let id = Column(CodingKeys.id)
static let name = Column(CodingKeys.name)
static let score = Column(CodingKeys.score)
@@ -29,17 +29,33 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
}
}
// MARK: - Database access
// MARK: - Player Requests
// Define some useful player requests.
// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
extension Player {
static func orderedByName() -> QueryInterfaceRequest<Player> {
Player.order(Columns.name)
/// Define some player requests used by the application.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
extension DerivableRequest where RowDecoder == Player {
/// A request of players ordered by name
///
/// For example:
///
/// let players = try dbQueue.read { db in
/// try Player.all().orderedByName().fetchAll(db)
/// }
func orderedByName() -> Self {
order(Player.Columns.name)
}
static func orderedByScore() -> QueryInterfaceRequest<Player> {
Player.order(Columns.score.desc, Columns.name)
/// A request of players ordered by score
///
/// For example:
///
/// let players = try dbQueue.read { db in
/// try Player.all().orderedByScore().fetchAll(db)
/// }
func orderedByScore() -> Self {
order(Player.Columns.score.desc, Player.Columns.name)
}
}
@@ -2,55 +2,44 @@ import UIKit
class PlayerEditionViewController: UITableViewController {
enum Presentation {
/// Modal presentation: edition ends with the "Commit" segue.
/// Modal presentation: edition ends with the "Commit" unwind segue.
case modal
/// Push presentation: edition ends when user hits the back button.
case push
}
var player: Player! { didSet { configureView() } }
var presentation: Presentation! { didSet { configureView() } }
@IBOutlet fileprivate weak var cancelBarButtonItem: UIBarButtonItem!
@IBOutlet fileprivate weak var commitBarButtonItem: UIBarButtonItem!
@IBOutlet fileprivate weak var nameCell: UITableViewCell!
@IBOutlet fileprivate weak var nameTextField: UITextField!
@IBOutlet fileprivate weak var scoreCell: UITableViewCell!
@IBOutlet fileprivate weak var scoreTextField: UITextField!
/// The edited player
var player: Player! {
didSet {
configureForm()
}
}
/// The presentation mode
var presentation: Presentation! {
didSet {
configureNavigationItem()
}
}
@IBOutlet private weak var cancelBarButtonItem: UIBarButtonItem!
@IBOutlet private weak var commitBarButtonItem: UIBarButtonItem!
@IBOutlet private weak var nameCell: UITableViewCell!
@IBOutlet private weak var nameTextField: UITextField!
@IBOutlet private weak var scoreCell: UITableViewCell!
@IBOutlet private weak var scoreTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
configureView()
}
fileprivate func configureView() {
guard isViewLoaded else { return }
nameTextField.text = player.name
if player.score == 0 && player.id == nil {
scoreTextField.text = ""
} else {
scoreTextField.text = "\(player.score)"
}
switch presentation! {
case .modal:
navigationItem.leftBarButtonItem = cancelBarButtonItem
navigationItem.rightBarButtonItem = commitBarButtonItem
case .push:
navigationItem.leftBarButtonItem = nil
navigationItem.rightBarButtonItem = nil
}
configureForm()
configureNavigationItem()
}
}
// MARK: - Navigation
extension PlayerEditionViewController {
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
// Force keyboard to dismiss early
view.endEditing(true)
@@ -66,24 +55,31 @@ extension PlayerEditionViewController {
override func willMove(toParent parent: UIViewController?) {
super.willMove(toParent: parent)
switch presentation! {
case .modal:
break
case .push:
if parent == nil {
// Self is popping from its navigation controller
saveChanges()
}
if case .push = presentation, parent == nil {
// Self is popping from its navigation controller
saveChanges()
}
}
private func configureNavigationItem() {
guard isViewLoaded else { return }
if let presentation = presentation {
switch presentation {
case .modal:
navigationItem.leftBarButtonItem = cancelBarButtonItem
navigationItem.rightBarButtonItem = commitBarButtonItem
case .push:
navigationItem.leftBarButtonItem = nil
navigationItem.rightBarButtonItem = nil
}
}
}
}
// MARK: - Form
extension PlayerEditionViewController: UITextFieldDelegate {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
nameTextField.becomeFirstResponder()
@@ -106,16 +102,32 @@ extension PlayerEditionViewController: UITextFieldDelegate {
return false
}
@IBAction func textFieldDidChange(_ textField: UITextField) {
// User has edited the player: prevent interactive dismissal
if case .modal = presentation {
isModalInPresentation = true
}
}
private func configureForm() {
guard isViewLoaded else { return }
nameTextField.text = player.name
if player.score == 0 && player.id == nil {
scoreTextField.text = ""
} else {
scoreTextField.text = "\(player.score)"
}
}
private func saveChanges() {
guard var player = self.player else {
return
}
player.name = nameTextField.text ?? ""
player.score = scoreTextField.text.flatMap { Int($0) } ?? 0
try! appDatabase.savePlayer(&player)
self.player = player
try! dbQueue.inDatabase { db in
try player.save(db)
}
}
}
@@ -0,0 +1,243 @@
import UIKit
import GRDB
/// PlayerListViewController displays the list of players.
class PlayerListViewController: UITableViewController {
private enum PlayerOrdering {
case byName
case byScore
}
@IBOutlet private weak var newPlayerButtonItem: UIBarButtonItem!
private var animatesPlayersChange = false // Don't animate first update
private var players: [Player] = []
private var playersCancellable: DatabaseCancellable?
private var playerCountCancellable: DatabaseCancellable?
private var playerOrdering: PlayerOrdering = .byScore {
didSet {
configureOrderingBarButtonItem()
configureTableView()
}
}
override func viewDidLoad() {
super.viewDidLoad()
configureToolbar()
configureNavigationItem()
configureTableView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.isToolbarHidden = false
}
private func configureToolbar() {
toolbarItems = [
UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deletePlayers)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refresh)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "💣", style: .plain, target: self, action: #selector(stressTest)),
]
}
private func configureNavigationItem() {
navigationItem.backBarButtonItem = UIBarButtonItem(
title: "Players", style: .plain,
target: nil, action: nil)
navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem]
configureOrderingBarButtonItem()
configureTitle()
}
private func configureOrderingBarButtonItem() {
switch playerOrdering {
case .byScore:
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Score ▼",
style: .plain,
target: self, action: #selector(sortByName))
case .byName:
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Name ▲",
style: .plain,
target: self, action: #selector(sortByScore))
}
}
private func configureTitle() {
playerCountCancellable = appDatabase.observePlayerCount(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] count in
guard let self = self else { return }
switch count {
case 0: self.navigationItem.title = "No Player"
case 1: self.navigationItem.title = "1 Player"
default: self.navigationItem.title = "\(count) Players"
}
})
}
private func configureTableView() {
switch playerOrdering {
case .byName:
playersCancellable = appDatabase.observePlayersOrderedByName(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
self.updateTableView(with: players)
})
case .byScore:
playersCancellable = appDatabase.observePlayersOrderedByScore(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
self.updateTableView(with: players)
})
}
}
private func updateTableView(with players: [Player]) {
if animatesPlayersChange == false {
self.players = players
tableView.reloadData()
// Future updates will be animated
animatesPlayersChange = true
return
}
// Compute difference between current and new list of players
let difference = players
.difference(from: self.players)
.inferringMoves()
// Apply those changes to the table view
tableView.performBatchUpdates({
self.players = players
for change in difference {
switch change {
case let .remove(offset, _, associatedWith):
if let associatedWith = associatedWith {
self.tableView.moveRow(
at: IndexPath(row: offset, section: 0),
to: IndexPath(row: associatedWith, section: 0))
} else {
self.tableView.deleteRows(
at: [IndexPath(row: offset, section: 0)],
with: .fade)
}
case let .insert(offset, _, associatedWith):
if associatedWith == nil {
self.tableView.insertRows(
at: [IndexPath(row: offset, section: 0)],
with: .fade)
}
}
}
}, completion: nil)
}
}
// MARK: - Navigation
extension PlayerListViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Edit" {
guard
let controller = segue.destination as? PlayerEditionViewController,
let indexPath = tableView.indexPathForSelectedRow
else { return }
let player = players[indexPath.row]
controller.title = player.name
controller.player = player
controller.presentation = .push
}
else if segue.identifier == "New" {
guard
let navigationController = segue.destination as? UINavigationController,
let controller = navigationController.viewControllers.first as? PlayerEditionViewController
else { return }
setEditing(false, animated: true)
controller.title = "New Player"
controller.player = Player(id: nil, name: "", score: 0)
controller.presentation = .modal
}
}
@IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) {
// Player creation cancelled
}
@IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) {
// Player creation committed
}
}
// MARK: - UITableViewDataSource
extension PlayerListViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
players.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath)
configure(cell, at: indexPath)
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
// Delete the player
let player = players[indexPath.row]
try! appDatabase.deletePlayer(player)
}
private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
let player = players[indexPath.row]
if player.name.isEmpty {
cell.textLabel?.text = "(anonymous)"
} else {
cell.textLabel?.text = player.name
}
cell.detailTextLabel?.text = abs(player.score) > 1 ? "\(player.score) points" : "0 point"
}
}
// MARK: - Actions
extension PlayerListViewController {
@IBAction func sortByName() {
setEditing(false, animated: true)
playerOrdering = .byName
}
@IBAction func sortByScore() {
setEditing(false, animated: true)
playerOrdering = .byScore
}
@IBAction func deletePlayers() {
setEditing(false, animated: true)
try! appDatabase.deleteAllPlayers()
}
@IBAction func refresh() {
setEditing(false, animated: true)
try! appDatabase.refreshPlayers()
}
@IBAction func stressTest() {
setEditing(false, animated: true)
for _ in 0..<50 {
DispatchQueue.global().async {
try! appDatabase.refreshPlayers()
}
}
}
}
@@ -1,8 +1,8 @@
import UIKit
import GRDB
/// PlayersViewController displays the list of players.
class PlayersViewController: UITableViewController {
/// PlayerListViewController displays the list of players.
class PlayerListViewController: UITableViewController {
private enum PlayerOrdering {
case byName
case byScore
@@ -18,14 +18,6 @@ class PlayersViewController: UITableViewController {
configureTableView()
}
}
private var playersRequest: QueryInterfaceRequest<Player> {
switch playerOrdering {
case .byName:
return Player.orderedByName()
case .byScore:
return Player.orderedByScore()
}
}
override func viewDidLoad() {
super.viewDidLoad()
@@ -71,13 +63,7 @@ class PlayersViewController: UITableViewController {
}
private func configureTitle() {
// Track changes in the number of players
let observation = ValueObservation.tracking { db in
try Player.fetchCount(db)
}
playerCountCancellable = observation.start(
in: dbQueue,
scheduling: .immediate,
playerCountCancellable = appDatabase.observePlayerCount(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] count in
guard let self = self else { return }
@@ -90,19 +76,22 @@ class PlayersViewController: UITableViewController {
}
private func configureTableView() {
// Track changes in the list of players
let request = self.playersRequest
let observation = ValueObservation.tracking { db in
try request.fetchAll(db)
switch playerOrdering {
case .byName:
playersCancellable = appDatabase.observePlayersOrderedByName(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
self.updateTableView(players)
})
case .byScore:
playersCancellable = appDatabase.observePlayersOrderedByScore(
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
self.updateTableView(players)
})
}
playersCancellable = observation.start(
in: dbQueue,
scheduling: .immediate,
onError: { error in fatalError("Unexpected error: \(error)") },
onChange: { [weak self] players in
guard let self = self else { return }
self.updateTableView(players)
})
}
private func updateTableView(_ players: [Player]) {
@@ -141,7 +130,7 @@ class PlayersViewController: UITableViewController {
// MARK: - Navigation
extension PlayersViewController {
extension PlayerListViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Edit" {
@@ -173,7 +162,7 @@ extension PlayersViewController {
// MARK: - UITableViewDataSource
extension PlayersViewController {
extension PlayerListViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
players.count
}
@@ -187,9 +176,7 @@ extension PlayersViewController {
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
// Delete the player
let player = players[indexPath.row]
try! dbQueue.write { db in
_ = try player.delete(db)
}
try! appDatabase.deletePlayer(player)
}
private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
@@ -206,7 +193,7 @@ extension PlayersViewController {
// MARK: - Actions
extension PlayersViewController {
extension PlayerListViewController {
@IBAction func sortByName() {
setEditing(false, animated: true)
playerOrdering = .byName
@@ -219,48 +206,19 @@ extension PlayersViewController {
@IBAction func deletePlayers() {
setEditing(false, animated: true)
try! dbQueue.write { db in
_ = try Player.deleteAll(db)
}
try! appDatabase.deleteAllPlayers()
}
@IBAction func refresh() {
setEditing(false, animated: true)
refreshPlayers()
try! appDatabase.refreshPlayers()
}
@IBAction func stressTest() {
setEditing(false, animated: true)
for _ in 0..<50 {
DispatchQueue.global().async {
self.refreshPlayers()
}
}
}
private func refreshPlayers() {
try! dbQueue.write { db in
if try Player.fetchCount(db) == 0 {
// Insert new random players
for _ in 0..<8 {
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
try player.insert(db)
}
} else {
// Insert a player
if Bool.random() {
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
try player.insert(db)
}
// Delete a random player
if Bool.random() {
try Player.order(sql: "RANDOM()").limit(1).deleteAll(db)
}
// Update some players
for var player in try Player.fetchAll(db) where Bool.random() {
player.score = Player.randomScore()
try player.update(db)
}
try! appDatabase.refreshPlayers()
}
}
}
+9 -8
View File
@@ -5,27 +5,28 @@ Demo Application
**This demo application shows you:**
- 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 table view with [ValueObservation](../../README.md#valueobservation).
- 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 table view with [ValueObservation](../../../README.md#valueobservation).
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
**Files of interest:**
- [AppDelegate.swift](GRDBDemoiOS/AppDelegate.swift)
`AppDelegate` creates, on application startup, a unique instance of [DatabaseQueue](../../README.md#database-queues) available for the whole application.
`AppDelegate` creates, on application startup, a unique instance of [DatabaseQueue](../../../README.md#database-queues) available for the whole application.
- [AppDatabase.swift](GRDBDemoiOS/AppDatabase.swift)
`AppDatabase` defines the database for the whole application. It uses [DatabaseMigrator](../../README.md#migrations) in order to setup the database schema.
`AppDatabase` grants database access for the whole application. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema, and [ValueObservation](../../../README.md#valueobservation) in order to let the application observe database changes.
- [Player.swift](GRDBDemoiOS/Player.swift)
`Player` is a [Record](../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../README.md#codable-records).
`Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records). It defines the database requests used by the application.
- [PlayersViewController.swift](GRDBDemoiOS/PlayersViewController.swift)
- [PlayerListViewController.swift](GRDBDemoiOS/PlayerListViewController.swift)
`PlayersViewController` displays a list of players. It keeps its view up-to-date with [ValueObservation](../../README.md#valueobservation).
`PlayerListViewController` displays the list of players.
- [PlayerEditionViewController.swift](GRDBDemoiOS/PlayerEditionViewController.swift)
+1 -1
View File
@@ -371,7 +371,7 @@ final class LatinAsciiTokenizer : FTS5WrapperTokenizer {
}
```
> :point_up: **Note**: String.applyingTransform is not available before iOS 9.0 and macOS 10.11. Use the Core Foundation function [CFStringTransform](https://developer.apple.com/reference/corefoundation/1542411-cfstringtransform) instead.
> :point_up: **Note**: String.applyingTransform is not available before macOS 10.11. Use the Core Foundation function [CFStringTransform](https://developer.apple.com/reference/corefoundation/1542411-cfstringtransform) instead.
Remember to register LatinAsciiTokenizer before using it:
+2 -2
View File
@@ -280,7 +280,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
```
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.5/Structs/StatementArguments.html):
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
@@ -529,7 +529,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
```
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.5/Structs/StatementArguments.html):
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
+102 -33
View File
@@ -24,7 +24,7 @@ GRDB requirements have been bumped:
- **Swift 5.2+** (was Swift 4.2+)
- **Xcode 11.4+** (was Xcode 10.0+)
- iOS 9.0+ (unchanged)
- **iOS 10.0+** (was iOS 9.0+)
- **macOS 10.10+** (was macOS 10.9+)
- tvOS 9.0+ (unchanged)
- watchOS 2.0+ (unchanged)
@@ -193,9 +193,10 @@ The changes can quite impact your application. We'll describe them below, as wel
```swift
let observation = ValueObservation.tracking(Player.fetchAll)
let cancellable = observation
.publisher(in: dbQueue)
// Opt in for immediate notification of the initial value
.scheduling(.immediate)
.publisher(
in: dbQueue,
// Opt in for immediate notification of the initial value
scheduling: .immediate)
.sink(...)
```
@@ -207,9 +208,10 @@ The changes can quite impact your application. We'll describe them below, as wel
```swift
let observation = ValueObservation.tracking(Player.fetchAll)
let disposable = observation
.rx.observe(in: dbQueue)
// Opt in for immediate notification of the initial value
.scheduling(.immediate)
.rx.observe(
in: dbQueue,
// Opt in for immediate notification of the initial value
scheduling: .immediate)
.subscribe(...)
```
@@ -293,7 +295,23 @@ The changes can quite impact your application. We'll describe them below, as wel
## Other Changes
1. [Batch updates] used to rely of the `<-` operator. This operator has been removed. Use the `set(to:)` method instead:
1. The `Configuration.trace` property has been removed. You know use the `Database.trace(options:_:)` method instead:
```swift
// BEFORE: GRDB 4
var config = Configuration()
config.trace = { print($0) }
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
// NEW: GRDB 5
var config = Configuration()
config.prepareDatabase = { db in
db.trace { print($0) }
}
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
```
2. [Batch updates] used to rely of the `<-` operator. This operator has been removed. Use the `set(to:)` method instead:
```swift
// BEFORE: GRDB 4
@@ -302,8 +320,72 @@ The changes can quite impact your application. We'll describe them below, as wel
// NEW: GRDB 5
try Player.updateAll(db, Column("score").set(to: 0))
```
> :question: This change avoids conflicts with other libraries that define the same operator.
2. [Custom SQL functions] are now [callable values](https://github.com/apple/swift-evolution/blob/master/proposals/0253-callable.md):
3. [SQL Interpolation] does no longer wrap subqueries in parenthesis:
```swift
// BEFORE: GRDB 4
let maximumScore: SQLRequest<Int> = "SELECT MAX(score) FROM player"
let bestPlayers: SQLRequest<Player> = "SELECT * FROM player WHERE score = \(maximumScore)"
// NEW: GRDB 5
let maximumScore: SQLRequest<Int> = "SELECT MAX(score) FROM player"
let bestPlayers: SQLRequest<Player> = "SELECT * FROM player WHERE score = (\(maximumScore))"
// extra parenthesis required: ^ ^
```
> :question: This change makes it possible to concatenate subqueries with the UNION operator.
4. In order to extract raw SQL string from an [SQLLiteral], you now need a database connection:
```swift
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
// BEFORE: GRDB 4
print(query.sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(query.arguments) // prints ["O'Brien", 42]
// NEW: GRDB 5
let (sql, arguments) = try dbQueue.read(query.build)
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(arguments) // prints ["O'Brien", 42]
```
5. In order to extract raw SQL string from a request ([SQLRequest] or [QueryInterfaceRequest]), you now need to call the `makePreparedRequest()` method:
```swift
// BEFORE: GRDB 4
try dbQueue.read { db in
let request = Player.filter(Column("name") == "O'Brien")
let sqlRequest = try SQLRequest(db, request: request)
print(sqlRequest.sql) // "SELECT * FROM player WHERE name = ?"
print(sqlRequest.arguments) // ["O'Brien"]
}
// NEW: GRDB 5
try dbQueue.read { db in
let request = Player.filter(Column("name") == "O'Brien")
let statement = try request.makePreparedRequest(db, forSingleResult: false).statement
print(statement.sql) // "SELECT * FROM player WHERE name = ?"
print(statement.arguments) // ["O'Brien"]
}
```
6. The `TableRecord.selectionSQL()` method is no longer avaible. When you need to embed the columns selected by a record type in an SQL request, you now have to use [SQL Interpolation]:
```swift
// BEFORE: GRDB 4
let sql = "SELECT \(Player.selectionSQL()) FROM player"
let players = try Player.fetchAll(db, sql: sql)
// NEW: GRDB 5
let request: SQLRequest<Player> = "SELECT \(columnsOf: Player.self) FROM player"
let players = try request.fetchAll(db)
```
7. [Custom SQL functions] are now [callable values](https://github.com/apple/swift-evolution/blob/master/proposals/0253-callable.md):
```swift
// BEFORE: GRDB 4
@@ -313,29 +395,13 @@ The changes can quite impact your application. We'll describe them below, as wel
Player.select(myFunction(Column("name")))
```
3. If you happen to implement custom fetch requests with the `FetchRequest` protocol, you now have to define the `makePreparedRequest(_:forSingleResult:)` method:
8. Defining custom `FetchRequest` types is now **discouraged**.
```swift
// BEFORE: GRDB 4
struct MyRequest: FetchRequest {
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) {
let statement: SelectStatement = ...
let adapter: RowAdapter? = ...
return (statement, adapter)
}
}
// NEW: GRDB 5
struct MyRequest: FetchRequest {
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
let statement: SelectStatement = ...
let adapter: RowAdapter? = ...
return PreparedRequest(statement: statement, adapter: adapter)
}
}
```
4. The module name for [custom SQLite builds](CustomSQLiteBuilds.md) is now the plain `GRDB`:
A future GRDB version will remove the ability to define custom `FetchRequest` types.
Our suggestion is to refactor your app so that your custom request type is no longer needed: [SQLRequest] and [QueryInterfaceRequest] are now supposed to fully address your needs. If it is not possible, then please [open an issue](https://github.com/groue/GRDB.swift/issues) and describe your particular use case.
9. The module name for [custom SQLite builds](CustomSQLiteBuilds.md) is now the plain `GRDB`:
```swift
// BEFORE: GRDB 4
@@ -345,7 +411,7 @@ The changes can quite impact your application. We'll describe them below, as wel
import GRDB
```
5. Importing the `GRDB` module grants access to the [SQLite C interface](https://www.sqlite.org/c3ref/intro.html). You don't need any longer to import the underlying SQLite library:
10. Importing the `GRDB` module grants access to the [SQLite C interface](https://www.sqlite.org/c3ref/intro.html). You don't need any longer to import the underlying SQLite library:
```swift
// BEFORE: GRDB 4
@@ -360,7 +426,6 @@ The changes can quite impact your application. We'll describe them below, as wel
```
[ValueObservation]: ../README.md#valueobservation
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
@@ -369,3 +434,7 @@ The changes can quite impact your application. We'll describe them below, as wel
[removeDuplicates]: ../README.md#valueobservationremoveduplicates
[Custom SQL functions]: ../README.md#custom-sql-functions
[Batch updates]: ../README.md#update-requests
[SQL Interpolation]: SQLInterpolation.md
[SQLLiteral]: SQLInterpolation.md#sqlliteral
[SQLRequest]: ../README.md#custom-requests
[QueryInterfaceRequest]: ../README.md#requests
@@ -701,8 +701,8 @@ Instead, have a look at [Database Observation]:
[Divide and Conquer]: https://en.wikipedia.org/wiki/Divide_and_rule
[Why Adopt GRDB?]: WhyAdoptGRDB.md
[isolation]: https://en.wikipedia.org/wiki/Isolation_(database_systems)
[migrations]: ../README.md#migrations
[migration]: ../README.md#migrations
[migrations]: Migrations.md
[migration]: Migrations.md
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
[Concurrency Guide]: ../README.md#concurrency
[GRDB concurrency rules]: ../README.md#concurrency
+122
View File
@@ -0,0 +1,122 @@
# Migrations
**Migrations** are a convenient way to alter your database schema over time in a consistent and easy way.
Migrations run in order, once and only once. When a user upgrades your application, only non-applied migrations are run.
Inside each migration, you typically [define and update your database tables](../README.md#database-schema) according to your evolving application needs:
```swift
var migrator = DatabaseMigrator()
// 1st migration
migrator.registerMigration("v1") { db in
try db.create(table: "author") { t in ... }
try db.create(table: "book") { t in ... }
try db.create(index: ...)
}
// 2nd migration
migrator.registerMigration("v2") { db in
try db.alter(table: "author") { t in ... }
}
// Migrations for future versions will be inserted here:
//
// // 3rd migration
// migrator.registerMigration("...") { db in
// ...
// }
```
**Each migration runs in a separate transaction.** Should one throw an error, its transaction is rollbacked, subsequent migrations do not run, and the error is eventually thrown by `migrator.migrate(dbQueue)`.
**Migrations run with deferred foreign key checks.** This means that eventual foreign key violations are only checked at the end of the migration (and they make the migration fail).
**The memory of applied migrations is stored in the database itself** (in a reserved table).
You migrate the database up to the latest version with the `migrate(_:)` method:
```swift
try migrator.migrate(dbQueue) // or migrator.migrate(dbPool)
```
Migrate a database up to a specific version (useful for testing):
```swift
try migrator.migrate(dbQueue, upTo: "v2")
// Migrations can only run forward:
try migrator.migrate(dbQueue, upTo: "v2")
try migrator.migrate(dbQueue, upTo: "v1")
// ^ fatal error: database is already migrated beyond migration "v1"
```
When several versions of your app are deployed in the wild, you may want to perform extra checks:
```swift
try dbQueue.read { db in
// Readonly apps may want to check if database lacks expected migrations:
if try migrator.hasCompletedMigrations(db) == false {
// database too old
}
// All apps may want to check if database contains unknown (future) migrations:
if try migrator.hasBeenSuperseded(db) {
// database too new
}
}
```
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/DatabaseMigrator.html) for more migrator methods.
## The `eraseDatabaseOnSchemaChange` Option
A DatabaseMigrator can automatically wipe out the full database content, and recreate the whole database from scratch, if it detects that migrations have changed their definition:
```swift
var migrator = DatabaseMigrator()
migrator.eraseDatabaseOnSchemaChange = true
```
> :warning: **Warning**: This option can destroy your precious users' data!
Setting `eraseDatabaseOnSchemaChange` is useful during application development, as you are still designing migrations, and the schema changes often.
It is recommended that this option does not ship in the released application:
```swift
var migrator = DatabaseMigrator()
#if DEBUG
// Speed up development by nuking the database when migrations change
migrator.eraseDatabaseOnSchemaChange = true
#endif
```
The `eraseDatabaseOnSchemaChange` option triggers a recreation of the database if and only if:
- A migration has been removed, or renamed.
- A *schema change* is detected. A schema change is any difference in the `sqlite_master` table, which contains the SQL used to create database tables, indexes, triggers, and views.
## Advanced Database Schema Changes
SQLite does not support many schema changes, and won't let you drop a table column with "ALTER TABLE ... DROP COLUMN ...", for example.
Yet any kind of schema change is still possible, by recreating tables:
```swift
migrator.registerMigration("AddNotNullCheckOnName") { db in
// Add a NOT NULL constraint on player.name:
try db.create(table: "new_player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
try db.execute(sql: "INSERT INTO new_player SELECT * FROM player")
try db.drop(table: "player")
try db.rename(table: "new_player", to: "player")
}
```
+2
View File
@@ -17,6 +17,8 @@ To release a new GRDB version:
- CHANGELOG.md
- GRDB.swift.podspec
- README.md
- Documentation/FullTextSearch.md
- Documentation/Migrations.md
- Support/Info.plist
- Commit and tag
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
+113 -93
View File
@@ -6,16 +6,17 @@ Your SQL skills are [welcomed] throughout GRDB. Yet writing raw SQL presents com
The query below exemplifies this situation. It even contains a bug that is not quite easy to spot:
```swift
try db.execute(
sql: """
UPDATE student
SET firstName = ?, lastName = ?, department = ?, birthDate = ?,
registrationDate = ?, mainTeacherId = ?
WHERE id = ?
""",
arguments: [firstName, lastName, department, birthDate,
registrationDate, mainTeacherId])
try dbQueue.write { db in
try db.execute(
sql: """
UPDATE student
SET firstName = ?, lastName = ?, department = ?, birthDate = ?,
registrationDate = ?, mainTeacherId = ?
WHERE id = ?
""",
arguments: [firstName, lastName, department, birthDate,
registrationDate, mainTeacherId])
}
```
SQL Interpolation is an answer to these troubles. It is available in Swift 5.
@@ -34,7 +35,9 @@ SQL Interpolation is an answer to these troubles. It is available in Swift 5.
```swift
let name: String = ...
let id: Int64 = ...
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
try dbQueue.write { db in
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
}
```
SQL interpolation looks and feel just like regular [String interpolation]:
@@ -47,16 +50,12 @@ print("Hello \(name)!") // prints "Hello World!"
The difference is that it generates valid SQL which does not suffer from syntax errors or [SQL injection]. For example, you do not need to validate input or process single quotes:
```swift
// Executes `UPDATE player SET name = 'O''Brien' WHERE id = 42`
let name = "O'Brien"
let id = 42
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
```
Under the hood, SQL interpolation generates a plain SQL string. It runs exactly as below:
```swift
try db.execute(sql: "UPDATE player SET name = ? WHERE id = ?", arguments: [name, id])
try dbQueue.write { db in
// Executes `UPDATE player SET name = 'O''Brien' WHERE id = 42`
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
}
```
Plain SQL strings are indeed still available, and SQL interpolation only kicks in when you ask for it. There is a simple rule to remember:
@@ -79,17 +78,21 @@ Plain SQL strings are indeed still available, and SQL interpolation only kicks i
**SQLLiteral** is the type that looks like a plain String, but profits from SQL interpolation:
```swift
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
try db.execute(literal: query)
try dbQueue.write { db in
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
try db.execute(literal: query)
}
```
**SQLLiteral is not a Swift String.** You can not use the `execute(literal:)` method with a String argument:
```swift
// Compiler error:
// Cannot convert value of type 'String' to expected argument type 'SQLLiteral'
let query = "UPDATE player SET name = \(name) WHERE id = \(id)" // a String
try db.execute(literal: query)
try dbQueue.write { db in
let query = "UPDATE player SET name = \(name) WHERE id = \(id)" // a regular String
// Compiler error:
// Cannot convert value of type 'String' to expected argument type 'SQLLiteral'
try db.execute(literal: query)
}
```
SQLLiteral can build your queries step by step, with regular operators and methods:
@@ -113,8 +116,9 @@ Extract the plain SQL string from a literal:
```swift
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
print(query.sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(query.arguments) // prints ["O'Brien", 42]
let (sql, arguments) = try dbQueue.read(query.build)
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(arguments) // prints ["O'Brien", 42]
```
Build a literal from a plain SQL string:
@@ -167,7 +171,7 @@ The [record protocols] extend your application types with database abilities.
**A record type knows everything about the schema of its underlying database table**. With the [TableRecord] protocol, the `databaseTableName` property contains the table name. With the [Decodable] protocol, the [CodingKeys] enum contain the column names. And with [FetchableRecord], you can decode raw database rows.
SQL Interpolation puts this knowledge to good use, so that you can build robust queries that consistently use correct table and column names:
SQL Interpolation puts this knowledge to good use, so that you can build robust queries that consistently use correct table and column names. Let's start from this record:
```swift
struct Player {
@@ -176,51 +180,15 @@ struct Player {
var score: Int?
}
extension Player: Decodable, FetchableRecord, TableRecord {
/// Deletes all player with no score
static func deleteAllWithoutScore(_ db: Database) throws {
try db.execute(literal: "DELETE FROM \(self) WHERE \(CodingKeys.score) IS NULL")
}
/// The player with a given id
static func filter(id: Int64) -> SQLRequest<Player> {
"SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)"
}
/// All players with the given ids
static func filter(ids: [Int64]) -> SQLRequest<Player> {
"SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)"
}
/// The maximum score
static func maximumScore() -> SQLRequest<Int> {
"SELECT MAX(\(CodingKeys.score)) FROM \(self)"
}
/// All players whose score is the maximum score
static func leaders() -> SQLRequest<Player> {
"""
SELECT * FROM \(self)
WHERE \(CodingKeys.score) = \(maximumScore())
"""
}
/// A complex request
static func complexRequest() -> SQLRequest<Player> {
let query: SQLLiteral = "SELECT * FROM \(self) "
query += "JOIN \(Team.self) ON ..."
query += "GROUP BY ..."
return SQLRequest(literal: query)
}
}
extension Player: Decodable, TableRecord, FetchableRecord { }
```
Let's breakdown each one of those methods.
Let's extend Player with database methods.
- `deleteAllWithoutScore(_:)`
- `Player.deleteAllWithoutScore(_:)`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
extension Player {
/// Deletes all player with no score
static func deleteAllWithoutScore(_ db: Database) throws {
try db.execute(literal: "DELETE FROM \(self) WHERE \(CodingKeys.score) IS NULL")
@@ -241,13 +209,22 @@ Let's breakdown each one of those methods.
`... \(CodingKeys.score) IS NULL` embeds CodingKeys.score. This one has been synthesized by the Swift compiler because Player adopts the Decodable protocol. It embeds the column name in the SQL query.
- `filter(id:)`
- `Player.filter(id:)`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// The player with a given id
extension Player {
/// "Simple" version
static func filter(id: Int64) -> SQLRequest<Player> {
"SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)"
"SELECT * FROM player WHERE id = \(id)"
}
/// "Future-proof" version
static func filter(id: Int64) -> SQLRequest<Player> {
"""
SELECT \(columnsOf: self)
FROM \(self)
WHERE \(CodingKeys.id) = \(id)
"""
}
}
```
@@ -261,17 +238,28 @@ Let's breakdown each one of those methods.
}
```
The return type of this method is `SQLRequest<Player>`. It is one of the GRDB [request types]. And it profits from SQL interpolation: this is why this method can simply return an "SQL literal"".
The return type of this method is `SQLRequest<Player>`. It is one of the GRDB [request types]. It profits from SQL interpolation, and this is why this method simply returns an "SQL literal"".
It embeds `\(self)` (the Player type which adopts the TableRecord protocol) and `\(CodingKeys.id)` (the coding key synthesized by the Decodable protocol), and `\(id)` (a [value]).
The first "simple" version only embeds the `\(id)` [value].
The second "robust" version embeds `\(columnsOf: self)`, the [columns selected by the record](#columns-selected-by-a-request), `\(self)` (the Player type which adopts the TableRecord protocol), `\(CodingKeys.id)` (the coding key synthesized by the Decodable protocol), and the `\(id)` [value].
- `filter(ids:)`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// All players with the given ids
/// "Simple" version
static func filter(ids: [Int64]) -> SQLRequest<Player> {
"SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)"
"SELECT * FROM player WHERE id IN \(ids)"
}
/// "Future-proof" version
static func filter(ids: [Int64]) -> SQLRequest<Player> {
"""
SELECT \(columnsOf: self)
FROM \(self)
WHERE \(CodingKeys.id) IN \(ids)
"""
}
}
```
@@ -280,7 +268,7 @@ Let's breakdown each one of those methods.
```swift
let players = try dbQueue.read { db in
// SELECT * player WHERE id IN (1, 2, 3)
// SELECT * FROM player WHERE id IN (1, 2, 3)
try Player.filter(ids: [1, 2, 3]).fetchAll(db) // [Player]
}
```
@@ -309,15 +297,21 @@ Let's breakdown each one of those methods.
The result is `SQLRequest<Int>`, unlike previous requests of type `SQLRequest<Player>`. SQLRequest accepts any fetchable type (database [row], simple [value], or custom [record]).
- `leaders()`
- `bestPlayers()`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// All players whose score is the maximum score
static func leaders() -> SQLRequest<Player> {
/// "Simple" version
static func bestPlayers() -> SQLRequest<Player> {
"SELECT * FROM player WHERE score = (\(maximumScore()))"
}
/// "Future-proof" version
static func bestPlayers() -> SQLRequest<Player> {
"""
SELECT * FROM \(self)
WHERE \(CodingKeys.score) = \(maximumScore())
SELECT \(columnsOf: self)
FROM \(self)
WHERE \(CodingKeys.score) = (\(maximumScore()))
"""
}
}
@@ -326,10 +320,9 @@ Let's breakdown each one of those methods.
Usage:
```swift
let leaders = try dbQueue.read { db in
// SELECT * FROM player
// WHERE score = (SELECT MAX(score) FROM player)
try Player.leaders().fetchAll(db) // [Player]
let bestPlayers = try dbQueue.read { db in
// SELECT * FROM player WHERE score = (SELECT MAX(score) FROM player)
try Player.bestPlayers().fetchAll(db) // [Player]
}
```
@@ -341,7 +334,8 @@ Let's breakdown each one of those methods.
extension Player: Decodable, FetchableRecord, TableRecord {
/// A complex request
static func complexRequest() -> SQLRequest<Player> {
let query: SQLLiteral = "SELECT * FROM \(self) "
let query: SQLLiteral = "SELECT \(columnsOf: self) "
query += "FROM \(self) "
query += "JOIN \(Team.self) ON ..."
query += "GROUP BY ..."
return SQLRequest(literal: query)
@@ -349,7 +343,7 @@ Let's breakdown each one of those methods.
}
```
This last request shows how to build an SQLRequest from an [SQLLiteral]. You will need SQLLiteral when the request can not be expressed in a single "SQL literal".
This last request shows how to build an SQLRequest from an [SQLLiteral]. You will need SQLLiteral when the request can not be written in a single stroke.
@@ -360,8 +354,9 @@ This chapter lists all kinds of supported interpolations.
- Types adopting the [TableRecord] protocol:
```swift
struct Player: TableRecord { ... }
// SELECT * FROM player
extension Player: TableRecord { }
"SELECT * FROM \(Player.self)"
// INSERT INTO player ...
@@ -369,6 +364,26 @@ This chapter lists all kinds of supported interpolations.
"INSERT INTO \(tableOf: player) ..."
```
- Columns selected by [TableRecord]:
```swift
struct Player: TableRecord { ... }
// SELECT player.* FROM player
"SELECT \(columnsOf: Player.self) FROM player"
// SELECT p.* FROM player p
"SELECT \(columnsOf: Player.self, tableAlias: "p") FROM player p"
struct AltPlayer: TableRecord {
static let databaseTableName = "player"
static let databaseSelection: [SQLSelectable] = [Column("id"), Column("name")]
}
// SELECT player.id, player.name FROM player
"SELECT \(columnsOf: AltPlayer.self) FROM player"
```
- [Expressions] and [values]:
```swift
@@ -405,12 +420,16 @@ This chapter lists all kinds of supported interpolations.
"SELECT * FROM player WHERE id IN \(Column("name").desc)"
```
- SQLRequest:
- Subqueries:
```swift
// SELECT * FROM player WHERE score = (SELECT MAX(score) FROM player)
let subQuery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
"SELECT * FROM player WHERE score = \(subQuery)"
let subquery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
"SELECT * FROM player WHERE score = (\(subquery))"
// SELECT * FROM player WHERE score = (SELECT MAX(score) FROM player)
let subquery = Player.select(max(Column("score")))
"SELECT * FROM player WHERE score = (\(subquery))"
```
- SQLLiteral:
@@ -452,3 +471,4 @@ This chapter lists all kinds of supported interpolations.
[welcomed]: ../README.md#sqlite-api
[query interface requests]: ../README.md#requests
[SE-0228 Fix ExpressibleByStringInterpolation]: https://github.com/apple/swift-evolution/blob/master/proposals/0228-fix-expressiblebystringinterpolation.md
[columns selected by the record]: ../README.md#columns-selected-by-a-request
+289
View File
@@ -0,0 +1,289 @@
Sharing a Database
==================
This chapter describes a recommended setup that applies as soon as several processes want to access a same SQLite database.
On iOS for example, you can share database files between multiple processes by storing them in an [App Group Container](https://developer.apple.com/documentation/foundation/nsfilemanager/1412643-containerurlforsecurityapplicati). On macOS as well, several processes may want to open the same database, according to their particular sandboxing contexts.
Accessing a shared database from several SQLite connections, from several processes, creates challenges at various levels:
1. **Database setup** may be attempted by multiple processes, concurrently.
2. **SQLite** may throw `SQLITE_BUSY` errors, code 5, "database is locked".
3. **iOS** may kill your application with a `0xDEAD10CC` exception.
4. **GRDB** database observation misses changes performed by external processes.
We'll address all of those challenges below.
- [Use a Database Pool]
- [How to limit the `SQLITE_BUSY` error]
- [How to limit the `0xDEAD10CC` exception]
- [How to perform cross-process database observation]
## Use a Database Pool
In order to access a shared database, use a [Database Pool]. It opens the database in the [WAL mode](https://www.sqlite.org/wal.html), which helps sharing a database.
Since several processes may open the database at the same time, protect the creation of the database pool with an [NSFileCoordinator].
- In a process that can create and write in the database, use this sample code:
```swift
/// Returns an initialized database pool at the shared location databaseURL
func openSharedDatabase(at databaseURL: URL) throws -> DatabasePool {
let coordinator = NSFileCoordinator(filePresenter: nil)
var coordinatorError: NSError?
var dbPool: DatabasePool?
var dbError: Error?
coordinator.coordinate(writingItemAt: databaseURL, options: .forMerging, error: &coordinatorError, byAccessor: { url in
do {
dbPool = try openDatabase(at: url)
} catch {
dbError = error
}
})
if let error = dbError ?? coordinatorError {
throw error
}
return dbPool!
}
private func openDatabase(at databaseURL: URL) throws -> DatabasePool {
var configuration = Configuration()
configuration.prepareDatabase = { db in
// Activate the persistent WAL mode so that
// readonly processes can access the database.
//
// See https://www.sqlite.org/walformat.html#operations_that_require_locks_and_which_locks_those_operations_use
// and https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlpersistwal
if db.configuration.readonly == false {
var flag: CInt = 1
let code = withUnsafeMutablePointer(to: &flag) { flagP in
sqlite3_file_control(db.sqliteConnection, nil, SQLITE_FCNTL_PERSIST_WAL, flagP)
}
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: ResultCode(rawValue: code))
}
}
}
let dbPool = try DatabasePool(path: databaseURL.path)
// Perform here other database setups, such as defining
// the database schema with a DatabaseMigrator, and
// checking if the application can open the file:
try migrator.migrate(dbPool)
if try dbPool.read(migrator.hasBeenSuperseded) {
// Database is too recent
throw /* some error */
}
return dbPool
}
```
- In a process that only reads in the database, use this sample code:
```swift
/// Returns an initialized database pool at the shared location databaseURL,
/// or nil if the database is not created yet, or does not have the required
/// schema version.
func openSharedReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
let coordinator = NSFileCoordinator(filePresenter: nil)
var coordinatorError: NSError?
var dbPool: DatabasePool?
var dbError: Error?
coordinator.coordinate(readingItemAt: databaseURL, options: .withoutChanges, error: &coordinatorError, byAccessor: { url in
do {
dbPool = try openReadOnlyDatabase(at: url)
} catch {
dbError = error
}
})
if let error = dbError ?? coordinatorError {
throw error
}
return dbPool
}
private func openReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
do {
var configuration = Configuration()
configuration.readonly = true
let dbPool = try DatabasePool(path: databaseURL.path, configuration: configuration)
// Check here if the database schema is the expected one,
// for example with a DatabaseMigrator:
return try dbPool.read { db in
if try migrator.hasBeenSuperseded(db) {
// Database is too recent
return nil
} else if try migrator.hasCompletedMigrations(db) == false {
// Database is too old
return nil
}
return dbPool
}
} catch {
if FileManager.default.fileExists(atPath: databaseURL.path) {
throw error
} else {
return nil
}
}
}
```
#### The specific case of readonly connections
Readonly connections will fail unless two extra files ending in `-shm` and `-wal` are present next to the database file ([source](https://www.sqlite.org/walformat.html#operations_that_require_locks_and_which_locks_those_operations_use)). Those files are regular companions of databases in the [WAL mode]. But they are deleted, under regular operations, when database connections are closed. Precisely speaking, they *may* be deleted: it depends on the SQLite and the operating system versions ([source](https://github.com/groue/GRDB.swift/issues/739#issuecomment-604363998)). And when they are deleted, readonly connections fail.
The solution is to enable the "persistent WAL mode", as shown in the sample code above, by setting the [SQLITE_FCNTL_PERSIST_WAL](https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlpersistwal) flag. This mode makes sure the `-shm` and `-wal` files are never deleted, and guarantees a database access to readonly connections.
## How to limit the `SQLITE_BUSY` error
> The SQLITE_BUSY result code indicates that the database file could not be written (or in some cases read) because of concurrent activity by some other database connection, usually a database connection in a separate process.
See https://www.sqlite.org/rescode.html#busy for more information about this error.
If several processes want to write in the database, configure the database pool of each process that wants to write:
```swift
var configuration = Configuration()
configuration.busyMode = .timeout(/* a TimeInterval */)
configuration.defaultTransactionKind = .immediate
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
With such a setup, you may still get `SQLITE_BUSY` (5, "database is locked") errors from all write operations. They will occur if the database remains locked by another process for longer than the specified timeout.
```swift
do {
try dbPool.write { db in ... }
} catch let error as DatabaseError where error.resultCode == .SQLITE_BUSY {
// Another process won't let you write. Deal with it.
}
```
> :bulb: **Tip**: In order to be nice to other processes, measure the duration of your longest writes, and attempt at optimizing the ones that last for too long. See the [How do I monitor the duration of database statements execution?] FAQ.
## How to limit the `0xDEAD10CC` exception
> The exception code 0xDEAD10CC indicates that an application has been terminated by the OS because it held on to a file lock or sqlite database lock during suspension.
See https://developer.apple.com/library/archive/technotes/tn2151/_index.html for more information about this exception.
1. If you use SQLCipher, use SQLCipher 4+, and call the `cipher_plaintext_header_size` pragma from your database preparation function:
```swift
var configuration = Configuration()
configuration.prepareDatabase = { (db: Database) in
try db.usePassphrase("secret")
try db.execute(sql: "PRAGMA cipher_plaintext_header_size = 32")
}
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
This will avoid https://github.com/sqlcipher/sqlcipher/issues/255.
2. [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features) In each process that wants to write in the database:
Set the `observesSuspensionNotifications` configuration flag:
```swift
var configuration = Configuration()
configuration.observesSuspensionNotifications = true
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
Post `Database.suspendNotification` when the application is about to be [suspended](https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle). You can for example post this notification from `UIApplicationDelegate.applicationDidEnterBackground(_:)`, or in the expiration handler of a [background task](https://forums.developer.apple.com/thread/85066).
```swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func applicationDidEnterBackground(_ application: UIApplication) {
// Suspend databases
NotificationCenter.default.post(name: Database.suspendNotification, object: self)
}
}
```
Post `Database.resumeNotification` from `UIApplicationDelegate.applicationWillEnterForeground(_:)` (or `SceneDelegate.sceneWillEnterForeground(_:)` for scene-based applications):
```swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func applicationWillEnterForeground(_ application: UIApplication) {
// Resume databases
NotificationCenter.default.post(name: Database.resumeNotification, object: self)
}
}
```
If the application uses the background modes supported by iOS, post `Database.resumeNotification` method from each and every background mode callback that may use the database. For example, if your application supports background fetches:
```swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// Resume databases
NotificationCenter.default.post(name: Database.resumeNotification, object: self)
// Proceed with background fetch
...
}
}
```
Suspended databases greatly reduce the odds of `0xDEAD10CC` exception are greatly reduced. If you see one in your crash logs, please open an issue!
In exchange, you will get `SQLITE_INTERRUPT` (9) or `SQLITE_ABORT` (4) errors, with messages "Database is suspended", "Transaction was aborted", or "interrupted", for any attempt at writing in the database when it is suspended.
You can catch those errors:
```swift
do {
try dbPool.write { db in ... }
} catch let error as DatabaseError where error.isInterruptionError {
// Oops, the database is suspended.
// Maybe try again after database is resumed?
}
```
## How to perform cross-process database observation
GRDB [Database Observation] features, as well as [GRDBCombine] and [RxGRDB], are not able to notify 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]:
```swift
// Notify all changes made to the "player" and "team" database tables
let observation = DatabaseRegionObservation(tracking: Player.all(), Team.all())
let observer = try observation.start(in: dbPool) { (db: Database) in
// Notify other processes
}
// Notify all changes made to the database
let observation = DatabaseRegionObservation(tracking: DatabaseRegion.fullDatabase)
let observer = try observation.start(in: dbPool) { (db: Database) in
// Notify other processes
}
```
[Use a Database Pool]: #use-a-database-pool
[How to limit the `SQLITE_BUSY` error]: #how-to-limit-the-sqlite_busy-error
[How to limit the `0xDEAD10CC` exception]: #how-to-limit-the-0xdead10cc-exception
[How to perform cross-process database observation]: #how-to-perform-cross-process-database-observation
[Database Pool]: ../README.md#database-pools
[Database Observation]: ../README.md#database-changes-observation
[GRDBCombine]: http://github.com/groue/GRDBCombine
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
[NSFileCoordinator]: https://developer.apple.com/documentation/foundation/nsfilecoordinator
[CFNotificationCenterGetDarwinNotifyCenter]: https://developer.apple.com/documentation/corefoundation/1542572-cfnotificationcentergetdarwinnot
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
[WAL mode]: https://www.sqlite.org/wal.html
[How do I monitor the duration of database statements execution?]: ../README.md#how-do-i-monitor-the-duration-of-database-statements-execution
+3 -3
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '4.14.0'
s.version = '5.0.0-beta.5'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
@@ -10,7 +10,7 @@ Pod::Spec.new do |s|
s.module_name = 'GRDB'
s.swift_versions = ['5.2']
s.ios.deployment_target = '9.0'
s.ios.deployment_target = '10.0'
s.osx.deployment_target = '10.10'
s.watchos.deployment_target = '2.0'
s.tvos.deployment_target = '9.0'
@@ -23,7 +23,7 @@ Pod::Spec.new do |s|
end
s.subspec 'SQLCipher' do |ss|
ss.source_files = 'GRDB/**/*.swift', 'Support/grdb_config.h'
ss.source_files = 'GRDB/**/*.swift', 'Support/SQLCipher_config.h'
ss.framework = 'Foundation'
ss.dependency 'SQLCipher', '>= 3.4.0'
ss.xcconfig = {
+28 -2
View File
@@ -166,6 +166,9 @@
563B071621862C4700B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */; };
563B071821862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
563B071921862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
563C67B324628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; };
563C67B424628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; };
563C67B524628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; };
563DE4F3231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */; };
563DE4F4231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */; };
563DE4F5231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */; };
@@ -796,6 +799,10 @@
56F26C1C1CEE3F32007969C4 /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; };
56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
56F3E74D1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
56F409212465C8D400A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409202465C8D400A7A152 /* SQLRequestProtocol.swift */; };
56F409222465C8D500A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409202465C8D400A7A152 /* SQLRequestProtocol.swift */; };
56F409232465C8D500A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409202465C8D400A7A152 /* SQLRequestProtocol.swift */; };
56F409242465C8D500A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409202465C8D400A7A152 /* SQLRequestProtocol.swift */; };
56F5ABD91D814330001F60CB /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C33F1D23E82A00E59934 /* Data.swift */; };
56F5ABDA1D814330001F60CB /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; };
56F5ABDC1D814330001F60CB /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; };
@@ -807,6 +814,9 @@
56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; };
56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; };
56FDECE31BB32DFD009AD709 /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; };
56FEB8F8248403000081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */; };
56FEB8F9248403010081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */; };
56FEB8FA248403020081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */; };
56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; };
56FEE7FF1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; };
56FF45441D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; };
@@ -1235,6 +1245,7 @@
563B0704218627F700B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = "<group>"; };
563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = "<group>"; };
563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = "<group>"; };
563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.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>"; };
@@ -1494,9 +1505,11 @@
56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizerTests.swift; sourceTree = "<group>"; };
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = "<group>"; };
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = "<group>"; };
56F409202465C8D400A7A152 /* SQLRequestProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequestProtocol.swift; sourceTree = "<group>"; };
56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = "<group>"; };
56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = "<group>"; };
56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.swift; sourceTree = "<group>"; };
56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = "<group>"; };
56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = "<group>"; };
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = "<group>"; };
@@ -1640,6 +1653,7 @@
560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */,
569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */,
56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */,
563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */,
);
name = DatabasePool;
sourceTree = "<group>";
@@ -2043,6 +2057,7 @@
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */,
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */,
56A238131B9C74A90082EB20 /* DatabaseTests.swift */,
56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */,
564FCE5D20F7E11A00202B90 /* DatabaseValueConversionErrorTests.swift */,
56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */,
56A238191B9C74A90082EB20 /* DatabaseValueConvertible */,
@@ -2153,6 +2168,7 @@
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */,
56E9FAD7221053DC00C703A8 /* SQLLiteral.swift */,
56FBFED82210731A00945324 /* SQLRequest.swift */,
56F409202465C8D400A7A152 /* SQLRequestProtocol.swift */,
56A238781B9C75030082EB20 /* Statement.swift */,
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
@@ -2315,10 +2331,10 @@
567DAF141EAB61ED00FC0928 /* grdb_config.h */,
DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */,
DC3773F819C8CBB3004FCF85 /* GRDB.h */,
56C48E731C9A9923005DF1D9 /* module.modulemap */,
DC3773F719C8CBB3004FCF85 /* Info.plist */,
56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */,
56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */,
DC3773F719C8CBB3004FCF85 /* Info.plist */,
56C48E731C9A9923005DF1D9 /* module.modulemap */,
);
name = "Supporting Files";
path = ../Support;
@@ -2803,6 +2819,7 @@
56F5ABD91D814330001F60CB /* Data.swift in Sources */,
565490D41D5AE252005622CB /* (null) in Sources */,
566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
56F409232465C8D500A7A152 /* SQLRequestProtocol.swift in Sources */,
565490B61D5AE236005622CB /* Configuration.swift in Sources */,
565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */,
56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */,
@@ -2908,6 +2925,7 @@
56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
56DDDDF5242F87C60025E381 /* ValueObservationScheduler.swift in Sources */,
560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */,
56F409222465C8D500A7A152 /* SQLRequestProtocol.swift in Sources */,
56A2FA3B24424F4700E97D23 /* Export.swift in Sources */,
569BBA4F229170F900478429 /* Inflections+English.swift in Sources */,
5656A81F2295B12F001FF3FF /* SQLAssociation.swift in Sources */,
@@ -3031,6 +3049,7 @@
56B14E831D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */,
562393341DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */,
5698AC841DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */,
563C67B424628BEA00E94EDC /* DatabasePoolTests.swift in Sources */,
5653EAE320944B4F00F46237 /* AssociationHasOneSQLTests.swift in Sources */,
566AD8CA1D531BEC002EC1A8 /* TableDefinitionTests.swift in Sources */,
56A238541B9C74A90082EB20 /* RecordPrimaryKeyMultipleTests.swift in Sources */,
@@ -3101,6 +3120,7 @@
56176C701EACCCC9000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */,
56FEE7FF1F47253700D930EA /* TableRecordTests.swift in Sources */,
56057C562291B16A00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */,
56FEB8F9248403010081AF83 /* DatabaseTraceTests.swift in Sources */,
56A2386A1B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */,
56A2383E1B9C74A90082EB20 /* DatabaseValueTests.swift in Sources */,
567156181CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */,
@@ -3237,6 +3257,7 @@
56D496891D81316E008276D7 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
56D4967C1D8130DB008276D7 /* CGFloatTests.swift in Sources */,
56D496631D81304E008276D7 /* FoundationURLTests.swift in Sources */,
563C67B324628BEA00E94EDC /* DatabasePoolTests.swift in Sources */,
56D496B71D81344B008276D7 /* RecordUniqueIndexTests.swift in Sources */,
5653EAE220944B4F00F46237 /* AssociationHasOneSQLTests.swift in Sources */,
56D496671D813086008276D7 /* Record+QueryInterfaceRequestTests.swift in Sources */,
@@ -3307,6 +3328,7 @@
5674A72A1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */,
566A84402041914000E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */,
56057C552291B16A00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */,
56FEB8F8248403000081AF83 /* DatabaseTraceTests.swift in Sources */,
56176C5E1EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */,
56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */,
56D496641D81304E008276D7 /* FoundationUUIDTests.swift in Sources */,
@@ -3449,6 +3471,7 @@
AAA4DCA6230F1E0600C74B15 /* FetchableRecord+TableRecord.swift in Sources */,
56DDDDF7242F87C70025E381 /* ValueObservationScheduler.swift in Sources */,
AAA4DCA7230F1E0600C74B15 /* TableRecord.swift in Sources */,
56F409242465C8D500A7A152 /* SQLRequestProtocol.swift in Sources */,
56A2FA3D24424F4800E97D23 /* Export.swift in Sources */,
AAA4DCA8230F1E0600C74B15 /* Inflections+English.swift in Sources */,
AAA4DCA9230F1E0600C74B15 /* SQLAssociation.swift in Sources */,
@@ -3572,6 +3595,7 @@
AAA4DD33230F262000C74B15 /* RowFromDictionaryLiteralTests.swift in Sources */,
AAA4DD34230F262000C74B15 /* AnyCursorTests.swift in Sources */,
AAA4DD35230F262000C74B15 /* VirtualTableModuleTests.swift in Sources */,
563C67B524628BEA00E94EDC /* DatabasePoolTests.swift in Sources */,
AAA4DD36230F262000C74B15 /* AssociationHasOneSQLTests.swift in Sources */,
AAA4DD37230F262000C74B15 /* TableDefinitionTests.swift in Sources */,
AAA4DD38230F262000C74B15 /* RecordPrimaryKeyMultipleTests.swift in Sources */,
@@ -3642,6 +3666,7 @@
AAA4DD76230F262000C74B15 /* FTS5WrapperTokenizerTests.swift in Sources */,
AAA4DD77230F262000C74B15 /* TableRecordTests.swift in Sources */,
AAA4DD78230F262000C74B15 /* AssociationHasManyRowScopeTests.swift in Sources */,
56FEB8FA248403020081AF83 /* DatabaseTraceTests.swift in Sources */,
AAA4DD79230F262000C74B15 /* RecordSubClassTests.swift in Sources */,
AAA4DD7A230F262000C74B15 /* DatabaseValueTests.swift in Sources */,
AAA4DD7B230F262000C74B15 /* DatabaseQueueReadOnlyTests.swift in Sources */,
@@ -3784,6 +3809,7 @@
5656A81E2295B12F001FF3FF /* SQLAssociation.swift in Sources */,
5617294E223533F40006E219 /* EncodableRecord.swift in Sources */,
5698AD181DAAD17A0056AF8C /* FTS5Tokenizer.swift in Sources */,
56F409212465C8D400A7A152 /* SQLRequestProtocol.swift in Sources */,
56A2FA3624424D2A00E97D23 /* Export.swift in Sources */,
56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
+37 -36
View File
@@ -16,7 +16,7 @@ public struct Configuration {
/// Default: false
public var readonly: Bool = false
/// The database label.
/// The configuration label.
///
/// You can query this label at runtime:
///
@@ -28,46 +28,43 @@ public struct Configuration {
/// print(db.configuration.label) // Prints "MyDatabase"
/// }
///
/// The database label is also used to name the various dispatch queues
/// created by GRDB, visible in debugging sessions and crash logs. However
/// those dispatch queue labels are intended for debugging only. Their
/// format may change between GRDB releases. Applications should not depend
/// on the GRDB dispatch queue labels.
/// The configuration label is also used to name Database connections (the
/// `Database.description` property), and the various dispatch queues
/// created by GRDB, visible in debugging sessions and crash logs.
///
/// If the database label is nil, the current GRDB implementation uses the
/// following dispatch queue labels:
/// Those connection names and dispatch queue labels are intended for
/// debugging only. Their format may change between GRDB releases.
/// Applications should not depend on connection names and dispatch
/// queue labels.
///
/// - `GRDB.DatabaseQueue`: the (unique) dispatch queue of a DatabaseQueue
/// - `GRDB.DatabasePool.writer`: the (unique) writer dispatch queue of
/// If the configuration label is nil, the current GRDB implementation uses
/// the following names:
///
/// - `GRDB.DatabaseQueue`: the (unique) connection of a DatabaseQueue
/// - `GRDB.DatabasePool.writer`: the (unique) writer connection of
/// a DatabasePool
/// - `GRDB.DatabasePool.reader.N`, where N is 1, 2, ...: one of the reader
/// dispatch queue(s) of a DatabasePool. N grows with the number of SQLite
/// connections: it may get bigger than the maximum number of concurrent
/// readers, as SQLite connections get closed and new ones are opened.
/// - `GRDB.DatabasePool.snapshot.N`: the dispatch queue of a
/// DatabaseSnapshot. N grows with the number of snapshots.
/// connection(s) of a DatabasePool. N may get bigger than the maximum
/// number of concurrent readers, as SQLite connections get closed and new
/// ones are opened.
/// - `GRDB.DatabasePool.snapshot.N`: the connection of a DatabaseSnapshot.
/// N grows with the number of snapshots.
///
/// If the database label is not nil, for example "MyDatabase", the current
/// GRDB implementation uses the following dispatch queue labels:
/// If the configuration label is not nil, for example "MyDatabase", the
/// current GRDB implementation uses the following names:
///
/// - `MyDatabase`: the (unique) dispatch queue of a DatabaseQueue
/// - `MyDatabase.writer`: the (unique) writer dispatch queue of
/// a DatabasePool
/// - `MyDatabase`: the (unique) connection of a DatabaseQueue
/// - `MyDatabase.writer`: the (unique) writer connection of a DatabasePool
/// - `MyDatabase.reader.N`, where N is 1, 2, ...: one of the reader
/// dispatch queue(s) of a DatabasePool. N grows with the number of SQLite
/// connections: it may get bigger than the maximum number of concurrent
/// readers, as SQLite connections get closed and new ones are opened.
/// - `MyDatabase.snapshot.N`: the dispatch queue of a
/// DatabaseSnapshot. N grows with the number of snapshots.
/// connection(s) of a DatabasePool. N may get bigger than the maximum
/// number of concurrent readers, as SQLite connections get closed and new
/// ones are opened.
/// - `MyDatabase.snapshot.N`: the connection of a DatabaseSnapshot. N grows
/// with the number of snapshots.
///
/// The default label is nil.
/// The default configuration label is nil.
public var label: String? = nil
/// A function that is called on every statement executed by the database.
///
/// Default: nil
public var trace: TraceFunction?
/// If false, SQLite from version 3.29.0 will not interpret a double-quoted
/// string as a string literal if it does not match any valid identifier.
///
@@ -164,6 +161,10 @@ public struct Configuration {
/// Default: immediateError
public var busyMode: Database.BusyMode = .immediateError
/// The behavior in case of SQLITE_BUSY error, for read-only connections.
/// If nil, GRDB picks a default one.
var readonlyBusyMode: Database.BusyMode? = nil
/// The maximum number of concurrent readers (applies to database
/// pools only).
///
@@ -206,8 +207,11 @@ public struct Configuration {
return threadingMode.SQLiteOpenFlags | readWriteFlags
}
func makeDispatchQueue(defaultLabel: String, purpose: String? = nil) -> DispatchQueue {
let label = (self.label ?? defaultLabel) + (purpose.map { "." + $0 } ?? "")
func identifier(defaultLabel: String, purpose: String? = nil) -> String {
(self.label ?? defaultLabel) + (purpose.map { "." + $0 } ?? "")
}
func makeDispatchQueue(label: String) -> DispatchQueue {
if let targetQueue = targetQueue {
return DispatchQueue(label: label, target: targetQueue)
} else {
@@ -215,6 +219,3 @@ public struct Configuration {
}
}
}
/// A tracing function that takes an SQL string.
public typealias TraceFunction = (String) -> Void
+7 -3
View File
@@ -344,23 +344,27 @@ extension Database {
throws -> [String]?
where T.Iterator.Element == String
{
// Check primaryKey first, so that we fail early if the table does not exist
let lowercasedColumns = Set(columns.map { $0.lowercased() })
if lowercasedColumns.isEmpty {
// Don't hit the database for trivial case
return nil
}
// Assume "rowid" is a primary key
if lowercasedColumns == ["rowid"] {
return ["rowid"]
}
// Check primaryKey.
let primaryKey = try self.primaryKey(tableName)
if Set(primaryKey.columns.map { $0.lowercased() }) == lowercasedColumns {
if Set(primaryKey.columns.map { $0.lowercased() }).isSubset(of: lowercasedColumns) {
return primaryKey.columns
}
// Is there is an explicit unique index on the columns?
let indexes = try self.indexes(on: tableName)
let matchingIndex = indexes.first { index in
index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns
index.isUnique && Set(index.columns.map { $0.lowercased() }).isSubset(of: lowercasedColumns)
}
if let index = matchingIndex {
return index.columns
+25 -7
View File
@@ -6,9 +6,9 @@ extension Database {
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?")
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
/// let statement = try db.makeSelectStatement(sql: "SELECT * FROM player WHERE id = ?")
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
///
/// - parameter sql: An SQL query.
/// - returns: A SelectStatement.
@@ -17,6 +17,24 @@ extension Database {
try makeSelectStatement(sql: sql, prepFlags: 0)
}
// TODO: remove when FetchRequest is a closed protocol.
/// Returns a new prepared statement.
///
/// let id = 1
/// let literal: SQLLiteral = "SELECT * FROM player WHERE id = \(id)"
/// let statement = try db.makeSelectStatement(literal: literal)
/// let player = try Player.fetchOne(statement)!
///
/// - parameter sql: An SQL query.
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func makeSelectStatement(literal: SQLLiteral) throws -> SelectStatement {
let (sql, arguments) = try literal.build(self)
let statement = try makeSelectStatement(sql: sql, prepFlags: 0)
statement.arguments = arguments
return statement
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0)
@@ -158,8 +176,8 @@ extension Database {
//
// And before we return, we'll check that all arguments were consumed.
var context = SQLGenerationContext.sqlLiteralContext
let sql = sqlLiteral.sql(&context)
let context = SQLGenerationContext(self)
let sql = try sqlLiteral.sql(context)
var arguments = context.arguments
let initialValuesCount = arguments.values.count
@@ -222,7 +240,7 @@ extension Database {
try checkForSuspensionViolation(from: statement)
if _isRecordingSelectedRegion {
_selectedRegion.formUnion(statement.selectedRegion)
_selectedRegion.formUnion(statement.databaseRegion)
}
let authorizer = observationBroker.updateStatementWillExecute(statement)
@@ -299,7 +317,7 @@ extension Database {
try checkForSuspensionViolation(from: statement)
if _isRecordingSelectedRegion {
_selectedRegion.formUnion(statement.selectedRegion)
_selectedRegion.formUnion(statement.databaseRegion)
}
}
+331 -81
View File
@@ -19,7 +19,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// try dbQueue.write { db in
/// try Player(...).insert(db)
/// }
public final class Database {
public final class Database: CustomStringConvertible, CustomDebugStringConvertible {
// The Database class is not thread-safe. An instance should always be
// used through a SerializedDatabase.
@@ -59,6 +59,11 @@ public final class Database {
/// The database configuration
public let configuration: Configuration
/// See `Configuration.label`
public let description: String
public var debugDescription: String { "<Database: \(description)>" }
// MARK: - Database Information
/// The rowID of the most recently inserted row.
@@ -144,7 +149,7 @@ public final class Database {
var isInsideTransactionBlock = false
/// Support for checkForSuspensionViolation(from:)
var isSuspended = LockedBox<Bool>(value: false)
@LockedBox var isSuspended = false
/// Support for checkForSuspensionViolation(from:)
/// This cache is never cleared: we assume journal mode never changes.
@@ -153,7 +158,7 @@ public final class Database {
// MARK: - Private properties
private var busyCallback: BusyCallback?
private var trace: ((TraceEvent) -> Void)?
private var functions = Set<DatabaseFunction>()
private var collations = Set<DatabaseCollation>()
private var _readOnlyDepth = 0 // Modify with beginReadOnly/endReadOnly
@@ -161,8 +166,14 @@ public final class Database {
// MARK: - Initializer
init(path: String, configuration: Configuration, schemaCache: DatabaseSchemaCache) throws {
init(
path: String,
description: String,
configuration: Configuration,
schemaCache: DatabaseSchemaCache) throws
{
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
self.description = description
self.configuration = configuration
self.schemaCache = schemaCache
}
@@ -200,11 +211,9 @@ public final class Database {
/// This method must be called after database initialization
func setup() throws {
// Setup trace first, so that setup queries are traced.
setupTrace()
setupBusyMode()
setupDoubleQuotedStringLiterals()
try setupForeignKeys()
setupBusyMode()
setupDefaultFunctions()
setupDefaultCollations()
setupAuthorizer()
@@ -222,69 +231,6 @@ public final class Database {
configuration.SQLiteConnectionDidOpen?()
}
private func setupTrace() {
guard configuration.trace != nil else {
return
}
// sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0
// http://www.sqlite.org/changes.html#version_3_14
// It is available from iOS 10.0 and OS X 10.12
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(
sqliteConnection,
UInt32(SQLITE_TRACE_STMT),
{ (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql)
},
dbPointer)
#elseif os(Linux)
setupTrace_v1()
#else
if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(
sqliteConnection,
UInt32(SQLITE_TRACE_STMT),
{ (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql)
},
dbPointer)
} else {
setupTrace_v1()
}
#endif
}
// Precondition: configuration.trace != nil
private func setupTrace_v1() {
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
guard let sql = sql.map(String.init) else { return }
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.configuration.trace!(sql)
}, dbPointer)
}
// Precondition: configuration.trace != nil
private static func trace_v2(
_ mask: UInt32,
_ dbPointer: UnsafeMutableRawPointer?,
_ stmt: UnsafeMutableRawPointer?,
_ unexpandedSQL: UnsafeMutableRawPointer?,
_ sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
-> Int32
{
guard let stmt = stmt else { return SQLITE_OK }
guard let expandedSQLCString = sqlite3_expanded_sql(OpaquePointer(stmt)) else { return SQLITE_OK }
let sql = String(cString: expandedSQLCString)
sqlite3_free(expandedSQLCString)
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.configuration.trace!(sql)
return SQLITE_OK
}
private func setupDoubleQuotedStringLiterals() {
if configuration.acceptsDoubleQuotedStringLiterals {
enableDoubleQuotedStringLiterals(sqliteConnection)
@@ -301,7 +247,10 @@ public final class Database {
}
private func setupBusyMode() {
switch configuration.busyMode {
let busyMode = configuration.readonly
? configuration.readonlyBusyMode ?? configuration.busyMode
: configuration.busyMode
switch busyMode {
case .immediateError:
break
@@ -328,7 +277,7 @@ public final class Database {
add(function: .lowercase)
add(function: .uppercase)
if #available(iOS 9.0, OSX 10.11, watchOS 3.0, *) {
if #available(OSX 10.11, watchOS 3.0, *) {
add(function: .localizedCapitalize)
add(function: .localizedLowercase)
add(function: .localizedUppercase)
@@ -431,6 +380,25 @@ public final class Database {
}
}
// MARK: - Limits
/// The maximum number of arguments accepted by an SQLite statement.
///
/// For example, requests such as the one below must make sure the `ids`
/// array does not contain more than `maximumStatementArgumentCount`
/// elements:
///
/// let ids: [Int] = ...
/// try dbQueue.write { db in
/// try Player.deleteAll(db, keys: ids)
/// }
///
/// See https://www.sqlite.org/limits.html
/// and `SQLITE_LIMIT_VARIABLE_NUMBER`.
public var maximumStatementArgumentCount: Int {
Int(sqlite3_limit(sqliteConnection, SQLITE_LIMIT_VARIABLE_NUMBER, -1))
}
// MARK: - Functions
/// Add or redefine an SQL function.
@@ -517,6 +485,38 @@ public final class Database {
finally: endReadOnly)
}
// MARK: - Snapshots
/// Returns a snapshot that must be freed with `grdb_snapshot_free`.
///
/// See https://www.sqlite.org/c3ref/snapshot.html
func takeVersionSnapshot() throws -> UnsafeMutablePointer<sqlite3_snapshot> {
var snapshot: UnsafeMutablePointer<sqlite3_snapshot>?
let code = withUnsafeMutablePointer(to: &snapshot) {
grdb_snapshot_get(sqliteConnection, "main", $0)
}
guard code == SQLITE_OK else {
// Don't grab `lastErrorMessage`, because grdb_snapshot_get may be a
// shim that does not call the missing sqlite3_snapshot_get.
throw DatabaseError(resultCode: code)
}
if let snapshot = snapshot {
return snapshot
} else {
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
}
}
func wasChanged(since initialSnapshot: UnsafeMutablePointer<sqlite3_snapshot>) throws -> Bool {
let secondSnapshot = try takeVersionSnapshot()
defer {
grdb_snapshot_free(secondSnapshot)
}
let cmp = grdb_snapshot_cmp(initialSnapshot, secondSnapshot)
assert(cmp <= 0, "Unexpected snapshot ordering")
return cmp < 0
}
// MARK: - Authorizer
func withAuthorizer<T>(_ authorizer: StatementAuthorizer?, _ block: () throws -> T) rethrows -> T {
@@ -550,11 +550,157 @@ public final class Database {
return try block()
}
// MARK: - Checkpoints
// MARK: - Trace
func checkpoint(_ kind: Database.CheckpointMode) throws {
let code = sqlite3_wal_checkpoint_v2(sqliteConnection, nil, kind.rawValue, nil, nil)
guard code == SQLITE_OK else {
/// Registers a tracing function.
///
/// For example:
///
/// // Trace all SQL statements executed by the database
/// var configuration = Configuration()
/// configuration.prepareDatabase = { db in
/// db.trace(options: .statement) { event in
/// print("SQL: \(event)")
/// }
/// }
/// let dbQueue = try DatabaseQueue(path: "...", configuration: configuration)
///
/// Pass an empty options set in order to stop database tracing:
///
/// // Stop tracing
/// db.trace(options: [])
///
/// See https://www.sqlite.org/c3ref/trace_v2.html for more information.
///
/// - parameter options: The set of desired event kinds. Defaults to
/// `.statement`, which notifies all executed database statements.
/// - parameter trace: the tracing function.
public func trace(options: TracingOptions = .statement, _ trace: ((TraceEvent) -> Void)? = nil) {
SchedulingWatchdog.preconditionValidQueue(self)
self.trace = trace
if options.isEmpty || trace == nil {
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
sqlite3_trace_v2(sqliteConnection, 0, nil, nil)
#elseif os(Linux)
sqlite3_trace(sqliteConnection, nil)
#else
if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
sqlite3_trace_v2(sqliteConnection, 0, nil, nil)
} else {
sqlite3_trace(sqliteConnection, 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
// It is available from macOS 10.12, tvOS 10.0, watchOS 3.0
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(sqliteConnection, UInt32(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)
#elseif os(Linux)
setupTrace_v1()
#else
if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(sqliteConnection, UInt32(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)
} else {
setupTrace_v1()
}
#endif
}
#if !(GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS))
private func setupTrace_v1() {
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)
}
#endif
// Precondition: configuration.trace != nil
private func trace_v2(
_ mask: CInt,
_ p: UnsafeMutableRawPointer?,
_ x: UnsafeMutableRawPointer?,
_ sqlite3_expanded_sql: @escaping @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
{
guard let trace = trace else { return }
switch mask {
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))
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))
let duration = TimeInterval(durationP.pointee) / 1.0e9
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
trace(TraceEvent.profile(statement: statement, duration: duration))
#elseif os(Linux)
#else
if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
trace(TraceEvent.profile(statement: statement, duration: duration))
}
#endif
}
default:
break
}
}
// MARK: - WAL Checkpoints
/// Runs a WAL checkpoint.
///
/// See https://www.sqlite.org/wal.html and
/// https://www.sqlite.org/c3ref/wal_checkpoint_v2.html for
/// more information.
///
/// - parameter kind: The checkpoint mode (default passive)
/// - parameter dbName: The database name (default "main")
/// - returns: A tuple:
/// - `walFrameCount`: the total number of frames in the log file
/// - `checkpointedFrameCount`: the total number of checkpointed frames
/// in the log file
@discardableResult
public func checkpoint(_ kind: Database.CheckpointMode = .passive, on dbName: String? = "main") throws
-> (walFrameCount: Int, checkpointedFrameCount: Int)
{
SchedulingWatchdog.preconditionValidQueue(self)
var walFrameCount: CInt = -1
var checkpointedFrameCount: CInt = -1
let code = sqlite3_wal_checkpoint_v2(sqliteConnection, dbName, kind.rawValue,
&walFrameCount, &checkpointedFrameCount)
switch code {
case SQLITE_OK:
return (walFrameCount: Int(walFrameCount), checkpointedFrameCount: Int(checkpointedFrameCount))
case SQLITE_MISUSE:
throw DatabaseError(resultCode: code)
default:
throw DatabaseError(resultCode: code, message: lastErrorMessage)
}
}
@@ -593,7 +739,7 @@ public final class Database {
///
/// Suspension ends with resume().
func suspend() {
isSuspended.write { isSuspended in
$isSuspended.update { isSuspended in
if isSuspended {
return
}
@@ -620,9 +766,7 @@ public final class Database {
///
/// See suspend().
func resume() {
isSuspended.write { isSuspended in
isSuspended = false
}
isSuspended = false
}
/// Support for checkForSuspensionViolation(from:)
@@ -650,7 +794,7 @@ public final class Database {
/// the database, in order to avoid the [`0xdead10cc`
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
func checkForSuspensionViolation(from statement: Statement) throws {
try isSuspended.read { isSuspended in
try $isSuspended.read { isSuspended in
guard isSuspended else {
return
}
@@ -1305,6 +1449,112 @@ extension Database {
/// log function that takes an error message.
public typealias LogErrorFunction = (_ resultCode: ResultCode, _ message: String) -> Void
/// An option for `Database.trace(options:_:)`
public struct TracingOptions: OptionSet {
public let rawValue: CInt
public init(rawValue: CInt) {
self.rawValue = rawValue
}
/// Reports executed statements
public static let statement = TracingOptions(rawValue: SQLITE_TRACE_STMT)
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
/// Reports executed statements and the estimated duration that the
/// statement took to run.
public static let profile = TracingOptions(rawValue: SQLITE_TRACE_PROFILE)
#elseif os(Linux)
#else
/// Reports executed statements and the estimated duration that the
/// statement took to run.
@available(OSX 10.12, tvOS 10.0, watchOS 3.0, *)
public static let profile = TracingOptions(rawValue: SQLITE_TRACE_PROFILE)
#endif
}
/// An event reported by `Database.trace(options:_:)`
public enum TraceEvent: CustomStringConvertible {
/// Information about a statement reported by `Database.trace(options:_:)`
public struct Statement {
enum Impl {
case trace_v1(String)
case trace_v2(
sqliteStatement: SQLiteStatement,
unexpandedSQL: UnsafePointer<CChar>?,
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
}
let impl: Impl
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
/// The executed SQL.
public var sql: String { _sql }
#elseif os(Linux)
#else
/// The executed SQL.
@available(OSX 10.12, tvOS 10.0, watchOS 3.0, *)
public var sql: String { _sql }
#endif
var _sql: String {
switch impl {
case .trace_v1:
// Likely a GRDB bug
fatalError("Not get statement SQL")
case let .trace_v2(sqliteStatement, unexpandedSQL, _):
if let unexpandedSQL = unexpandedSQL {
return String(cString: unexpandedSQL)
.trimmingCharacters(in: .sqlStatementSeparators)
} else {
return String(cString: sqlite3_sql(sqliteStatement))
.trimmingCharacters(in: .sqlStatementSeparators)
}
}
}
/// The executed SQL, with bound parameters expanded.
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)
.trimmingCharacters(in: .sqlStatementSeparators)
}
}
}
/// An event reported by `TracingOptions.statement`.
case statement(Statement)
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
/// An event reported by `TracingOptions.profile`.
case profile(statement: Statement, duration: TimeInterval)
#elseif os(Linux)
#else
/// An event reported by `TracingOptions.profile`.
@available(OSX 10.12, tvOS 10.0, watchOS 3.0, *)
case profile(statement: Statement, duration: TimeInterval)
#endif
public var description: String {
switch self {
case let .statement(statement):
return statement.expandedSQL
case let .profile(statement: statement, duration: duration):
let durationString = String(format: "%.3f", duration)
return "\(durationString)s \(statement.expandedSQL)"
}
}
}
/// The end of a transaction: Commit, or Rollback
public enum TransactionCompletion {
case commit
+3 -6
View File
@@ -223,6 +223,9 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
/// The SQL query that yielded the error (if relevant).
public let sql: String?
/// The query arguments that yielded the error (if relevant).
public let arguments: StatementArguments?
/// Creates a Database Error
public init(
resultCode: ResultCode = .SQLITE_ERROR,
@@ -243,12 +246,6 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
init(resultCode: Int32, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
self.init(resultCode: ResultCode(rawValue: resultCode), message: message, sql: sql, arguments: arguments)
}
// MARK: Not public
/// The query arguments that yielded the error (if relevant).
/// Not public because the StatementArguments class has no public method.
let arguments: StatementArguments?
}
// Support for `catch DatabaseError.SQLITE_XXX`
+121 -72
View File
@@ -12,7 +12,7 @@ public final class DatabasePool: DatabaseWriter {
private var collations = Set<DatabaseCollation>()
private var tokenizerRegistrations: [(Database) -> Void] = []
var databaseSnapshotCount = LockedBox(value: 0)
@LockedBox var databaseSnapshotCount = 0
// MARK: - Database Information
@@ -80,7 +80,9 @@ public final class DatabasePool: DatabaseWriter {
// setup a busy handler for pool readers, in order to workaround those
// "obscure cases" that may happen when the database is shared between
// multiple processes.
readerConfiguration.busyMode = .timeout(10)
if readerConfiguration.readonlyBusyMode == nil {
readerConfiguration.readonlyBusyMode = .timeout(10)
}
var readerCount = 0
readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in
@@ -137,8 +139,12 @@ public final class DatabasePool: DatabaseWriter {
// Undo job done in setupMemoryManagement()
//
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
// Explicit unregistration is required before iOS 9 and OS X 10.11.
// Explicit unregistration is required before OS X 10.11.
NotificationCenter.default.removeObserver(self)
// Close reader connections before the writer connection.
// Context: https://github.com/groue/GRDB.swift/issues/739
readerPool = nil
}
private func setupDatabase(_ db: Database) {
@@ -161,24 +167,6 @@ public final class DatabasePool: DatabaseWriter {
}
}
extension DatabasePool {
// MARK: - WAL Checkpoints
/// Runs a WAL checkpoint
///
/// See https://www.sqlite.org/wal.html and
/// https://www.sqlite.org/c3ref/wal_checkpoint_v2.html) for
/// more information.
///
/// - parameter kind: The checkpoint mode (default passive)
public func checkpoint(_ kind: Database.CheckpointMode = .passive) throws {
try writer.sync { db in
try db.checkpoint(kind)
}
}
}
extension DatabasePool {
// MARK: - Memory management
@@ -366,8 +354,11 @@ extension DatabasePool: DatabaseReader {
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
// First async jump in order to grab a reader connection.
// Honor configuration dispatching (qos/targetQueue).
let label = configuration.identifier(
defaultLabel: "GRDB.DatabasePool",
purpose: "asyncRead")
configuration
.makeDispatchQueue(defaultLabel: "GRDB.DatabasePool", purpose: "asyncRead")
.makeDispatchQueue(label: label)
.async {
do {
let (reader, releaseReader) = try self.readerPool.get()
@@ -400,8 +391,11 @@ extension DatabasePool: DatabaseReader {
public func _weakAsyncRead(_ block: @escaping (Result<Database, Error>?) -> Void) {
// First async jump in order to grab a reader connection.
// Honor configuration dispatching (qos/targetQueue).
let label = configuration.identifier(
defaultLabel: "GRDB.DatabasePool",
purpose: "asyncRead")
configuration
.makeDispatchQueue(defaultLabel: "GRDB.DatabasePool", purpose: "asyncRead")
.makeDispatchQueue(label: label)
.async { [weak self] in
guard let self = self else {
block(nil)
@@ -860,78 +854,133 @@ extension DatabasePool: DatabaseReader {
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
assert(!observation.requiresWriteAccess, "Use _addWriteOnly(observation:) instead")
let reduceQueueLabel = configuration.identifier(
defaultLabel: "GRDB",
purpose: "ValueObservation")
let observer = ValueObserver<Reducer>(
requiresWriteAccess: observation.requiresWriteAccess,
writer: self,
reducer: observation.makeReducer(),
scheduling: scheduler,
reduceQueue: configuration.makeDispatchQueue(defaultLabel: "GRDB", purpose: "ValueObservation.reducer"),
reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel),
onError: onError,
onChange: onChange)
// Starting a concurrent observation means that we'll fetch the initial
// value right away, without waiting for an access to the writer queue,
// and the opportunity to install a transaction observer.
//
// This is how DatabasePool can start an observation and promptly notify
// an initial value, even when there is a long-running write transaction
// in the background.
//
// We thus have to deal with the fact that between this initial fetch,
// and the beginning of transaction tracking, any number of untracked
// writes may occur.
//
// We must notify changes that happen during this untracked window. But
// how do we spot them, since we're not tracking database changes yet?
//
// A safe solution is to always perform a second fetch. We may fetch the
// same initial value, if no change did happen. But we don't miss
// possible changes.
//
// We can avoid this second fetch when SQLite is compiled with the
// SQLITE_ENABLE_SNAPSHOT option:
//
// 1. Perform the initial fetch in a DatabaseSnapshot. The snapshot
// acquires a lock that will prevent checkpointing until we get a writer
// access, so that we can reliably compare database versions with
// `sqlite3_snapshot`: https://www.sqlite.org/c3ref/snapshot.html.
//
// 2. Get a writer access, and compare the versions of the initial
// snapshot, and the current state of the database: if versions are
// identical, we can avoid the second fetch. If they are not, we perform
// the second fetch, even if the actual changes are unrelated to the
// tracked database region (we have no way to know).
//
// 3. Install the transaction observer.
if scheduler.immediateInitialValue() {
do {
// Fetch the initial value without waiting for the writer.
let initialValue = try unsafeReentrantRead(observer.fetchInitialValue)
let initialSnapshot = try makeSnapshot()
let initialValue = try initialSnapshot.read(observer.fetchInitialValue)
onChange(initialValue)
// Now wait for the writer
_weakAsyncWriteWithoutTransaction { db in
guard let db = db else { return }
if observer.isCompleted { return }
do {
// Don't miss eventual changes between the
// initial fetch and the writer access.
if let value = try observer.fetchValue(db) {
observer.notifyChange(value)
}
// Now we can start observation
db.add(transactionObserver: observer, extent: .observerLifetime)
} catch {
observer.notifyErrorAndComplete(error)
}
}
add(observer: observer, from: initialSnapshot)
} catch {
observer.cancel()
onError(error)
}
} else {
// Fetch the initial value without waiting for the writer.
_weakAsyncRead { [weak self] dbResult in
guard let dbResult = dbResult else { return }
guard let self = self else { return }
if observer.isCompleted { return }
do {
let initialValue = try observer.fetchInitialValue(dbResult.get())
observer.notifyChange(initialValue)
let label = configuration.identifier(
defaultLabel: "GRDB.DatabasePool",
purpose: "ValueObservation")
configuration
.makeDispatchQueue(label: label)
.async { [weak self] in
guard let self = self else { return }
if observer.isCompleted { return }
// Now wait for the writer
self._weakAsyncWriteWithoutTransaction { db in
guard let db = db else { return }
if observer.isCompleted { return }
do {
// Don't miss eventual changes between the
// initial fetch and the writer access.
if let value = try observer.fetchValue(db) {
observer.notifyChange(value)
}
// Now we can start observation
db.add(transactionObserver: observer, extent: .observerLifetime)
} catch {
observer.notifyErrorAndComplete(error)
}
do {
let initialSnapshot = try self.makeSnapshot()
let initialValue = try initialSnapshot.read(observer.fetchInitialValue)
observer.notifyChange(initialValue)
self.add(observer: observer, from: initialSnapshot)
} catch {
observer.notifyErrorAndComplete(error)
}
} catch {
observer.notifyErrorAndComplete(error)
}
}
}
return observer
}
// Support for _addConcurrent(observation:)
private func add<Reducer: _ValueReducer>(
observer: ValueObserver<Reducer>,
from initialSnapshot: DatabaseSnapshot)
{
_weakAsyncWriteWithoutTransaction { db in
guard let db = db else { return }
if observer.isCompleted { return }
do {
// Transaction is needed for version snapshotting
try db.inTransaction(.deferred) {
// Keep DatabaseSnaphot alive until we have compared
// database versions. It prevents database checkpointing,
// and keeps versions (`sqlite3_snapshot`) valid
// and comparable.
let fetchNeeded: Bool = withExtendedLifetime(initialSnapshot) {
// Version is nil if SQLite is not compiled with
// SQLITE_ENABLE_SNAPSHOT, or if the DatabaseSnaphot
// could not grab its version. In this case, we don't
// care, and just fetch a fresh value.
guard let initialVersion = initialSnapshot.version else {
return true
}
do {
return try db.wasChanged(since: initialVersion)
} catch {
// ignore: we'll just re-fetch
return true
}
}
if fetchNeeded, let value = try observer.fetchValue(db) {
observer.notifyChange(value)
}
return .commit
}
// Now we can start observation
db.add(transactionObserver: observer, extent: .observerLifetime)
} catch {
observer.notifyErrorAndComplete(error)
}
}
}
// MARK: - Custom FTS5 Tokenizers
#if SQLITE_ENABLE_FTS5
@@ -1025,7 +1074,7 @@ extension DatabasePool {
path: path,
configuration: writer.configuration,
defaultLabel: "GRDB.DatabasePool",
purpose: "snapshot.\(databaseSnapshotCount.increment())")
purpose: "snapshot.\($databaseSnapshotCount.increment())")
snapshot.read { setupDatabase($0) }
return snapshot
}
+1 -1
View File
@@ -68,7 +68,7 @@ public final class DatabaseQueue: DatabaseWriter {
// Undo job done in setupMemoryManagement()
//
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
// Explicit unregistration is required before iOS 9 and OS X 10.11.
// Explicit unregistration is required before OS X 10.11.
NotificationCenter.default.removeObserver(self)
}
}
+8 -1
View File
@@ -14,6 +14,9 @@ public class DatabaseSnapshot: DatabaseReader {
serializedDatabase.configuration
}
/// Not nil iff SQLite was compiled with `SQLITE_ENABLE_SNAPSHOT`.
private(set) var version: UnsafeMutablePointer<sqlite3_snapshot>?
init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws {
var configuration = configuration
configuration.readonly = true
@@ -33,12 +36,16 @@ public class DatabaseSnapshot: DatabaseReader {
throw DatabaseError(message: "WAL mode is not activated at path: \(path)")
}
try db.beginSnapshotTransaction()
version = try? db.takeVersionSnapshot()
}
}
deinit {
// Leave snapshot isolation
serializedDatabase.sync { db in
serializedDatabase.reentrantSync { db in
if let version = version {
grdb_snapshot_free(version)
}
try? db.commit()
}
}
+6 -8
View File
@@ -224,18 +224,16 @@ extension DatabaseValue {
extension DatabaseValue {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
// fast path for NULL
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
if isNull {
// fast path for NULL
return "NULL"
}
if context.append(arguments: [self]) {
} else if context.append(arguments: [self]) {
// Use statement arguments
return "?"
} else {
// Correctness above all: use SQLite to quote the value.
// Assume that the Quote function always succeeds
return DatabaseQueue().inDatabase { try! String.fetchOne($0, sql: "SELECT QUOTE(?)", arguments: [self])! }
// Quoting needed: just use SQLite, which knows better.
return try String.fetchOne(context.db, sql: "SELECT QUOTE(?)", arguments: [self])!
}
}
+1 -1
View File
@@ -26,7 +26,7 @@ struct ValueConversionContext: Refinable {
case .columnIndex(let index):
return index
case .columnName(let name):
return row?.index(ofColumn: name)
return row?.index(forColumn: name)
}
}
+4 -1
View File
@@ -318,12 +318,15 @@ extension DatabaseWriter {
{
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
let reduceQueueLabel = configuration.identifier(
defaultLabel: "GRDB",
purpose: "ValueObservation")
let observer = ValueObserver<Reducer>(
requiresWriteAccess: observation.requiresWriteAccess,
writer: self,
reducer: observation.makeReducer(),
scheduling: scheduler,
reduceQueue: configuration.makeDispatchQueue(defaultLabel: "GRDB", purpose: "ValueObservation.reducer"),
reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel),
onError: onError,
onChange: onChange)
+132 -42
View File
@@ -11,6 +11,7 @@ public struct PreparedRequest {
/// Support for eager loading of hasMany associations.
var supplementaryFetch: (([Row]) throws -> Void)?
// TODO: remove when FetchRequest is a closed protocol.
/// Creates a PreparedRequest.
///
/// - parameter statement: A prepared statement that is ready to
@@ -33,8 +34,21 @@ public struct PreparedRequest {
self.adapter = adapter
self.supplementaryFetch = supplementaryFetch
}
// TODO: remove when FetchRequest is a closed protocol.
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns the request SQL.
///
/// - parameter context: An SQL generation context.
/// - returns: An SQL string.
public func requestSQL(_ context: SQLGenerationContext) throws -> String {
try SQLLiteral(sql: statement.sql, arguments: statement.arguments).sql(context)
}
}
extension PreparedRequest: Refinable { }
// MARK: - FetchRequest
/// The protocol for all requests that fetch database rows, and tell how those
@@ -45,7 +59,27 @@ public struct PreparedRequest {
/// try request.fetchCursor(db) // Cursor of Player
/// try request.fetchAll(db) // [Player]
/// try request.fetchOne(db) // Player?
public protocol FetchRequest: DatabaseRegionConvertible {
/// try request.fetchCount(db) // Int
///
/// To build a custom FetchRequest, declare a type with the `RowDecoder`
/// associated type, and implement the `requestSQL(_:forSingleResult:)` method
/// with the help of SQLLiteral.
///
/// For example:
///
/// struct PlayerRequest: FetchRequest {
/// typealias RowDecoder = Player
/// var id: Int64
/// func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
/// let query: SQLLiteral = "SELECT * FROM player WHERE id = \(id)"
/// return try query.sql(context)
/// }
/// }
///
/// let player = try dbQueue.read { db in
/// try PlayerRequest(id: 42).fetchOne(db)
/// }
public protocol FetchRequest: SQLRequestProtocol, DatabaseRegionConvertible {
/// The type that tells how fetched database rows should be interpreted.
associatedtype RowDecoder
@@ -53,57 +87,79 @@ public protocol FetchRequest: DatabaseRegionConvertible {
///
/// - parameter db: A database connection.
/// - parameter singleResult: A hint that a single result row will be
/// consumed. Implementations can optionally use this to optimize the
/// prepared statement.
/// consumed. Implementations can optionally use it to optimize the
/// prepared statement, for example by adding a `LIMIT 1` SQL clause.
///
/// // Calls makePreparedRequest(db, forSingleResult: true)
/// try request.fetchOne(db)
///
/// // Calls makePreparedRequest(db, forSingleResult: false)
/// try request.fetchAll(db)
/// - returns: A prepared request.
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
/// Returns the number of rows fetched by the request.
///
/// The default implementation builds a naive SQL query based on the
/// statement returned by the `prepare` method:
/// `SELECT COUNT(*) FROM (...)`.
///
/// Adopting types can refine this method in order to use more
/// efficient SQL.
///
/// - parameter db: A database connection.
func fetchCount(_ db: Database) throws -> Int
}
extension FetchRequest {
/// Returns an adapted request.
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest<Self> {
AdaptedFetchRequest(self, adapter)
}
/// Returns the number of rows fetched by the request.
///
/// This default implementation builds a naive SQL query based on the
/// statement returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`.
/// The default implementation builds a naive SQL query based on the
/// statement returned by the `requestSQL(_:forSingleResult:)` method:
/// `SELECT COUNT(*) FROM (...)`.
///
/// - parameter db: A database connection.
public func fetchCount(_ db: Database) throws -> Int {
let request = try makePreparedRequest(db, forSingleResult: false)
let sql = "SELECT COUNT(*) FROM (\(request.statement.sql))"
return try Int.fetchOne(db, sql: sql, arguments: request.statement.arguments)!
let context = SQLGenerationContext(db)
let sql = try requestSQL(context, forSingleResult: false)
let countSQL = "SELECT COUNT(*) FROM (\(sql))"
return try Int.fetchOne(db, sql: countSQL, arguments: context.arguments)!
}
/// Returns the database region that the request looks into.
///
/// This default implementation returns a region built from the statement
/// returned by the `prepare` method.
/// returned by the `requestSQL(_:forSingleResult)` method.
///
/// - parameter db: A database connection.
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
let request = try makePreparedRequest(db, forSingleResult: false)
return request.statement.selectedRegion
let context = SQLGenerationContext(db)
let sql = try requestSQL(context, forSingleResult: false)
let statement = try db.makeSelectStatement(sql: sql)
return statement.databaseRegion
}
/// Returns a PreparedRequest that is ready to be executed.
///
/// This default implementation returns a request built from the
/// `requestSQL(_:forSingleResult)` method.
///
/// - parameter db: A database connection.
/// - parameter singleResult: A hint that a single result row will be
/// consumed. Implementations can optionally use this to optimize the
/// prepared statement.
/// - returns: A prepared request.
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
let context = SQLGenerationContext(db)
let sql = try requestSQL(context, forSingleResult: singleResult)
let statement = try db.makeSelectStatement(sql: sql)
statement.arguments = context.arguments
return PreparedRequest(statement: statement)
}
}
// MARK: - AdaptedFetchRequest
extension FetchRequest {
/// Returns an adapted request.
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest<Self> {
AdaptedFetchRequest(self, adapter)
}
}
/// An adapted request.
public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
public typealias RowDecoder = Base.RowDecoder
@@ -118,6 +174,12 @@ public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
self.adapter = adapter
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
try base.requestSQL(context, forSingleResult: singleResult)
}
/// :nodoc:
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
var request = try base.makePreparedRequest(db, forSingleResult: singleResult)
@@ -146,32 +208,60 @@ public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
///
/// An AnyFetchRequest forwards its operations to an underlying request,
/// hiding its specifics.
public struct AnyFetchRequest<T>: FetchRequest {
public typealias RowDecoder = T
private let _preparedRequest: (Database, _ singleResult: Bool) throws -> PreparedRequest
private let _fetchCount: (Database) throws -> Int
public struct AnyFetchRequest<RowDecoder>: FetchRequest {
// DatabaseRegionConvertible
private let _databaseRegion: (Database) throws -> DatabaseRegion
/// Creates a request that wraps and forwards operations to `request`.
public init<Request: FetchRequest>(_ request: Request) {
_preparedRequest = request.makePreparedRequest
_fetchCount = request.fetchCount
_databaseRegion = request.databaseRegion
}
// SQLRequestProtocol
private let _requestSQL: (SQLGenerationContext, _ singleResult: Bool) throws -> String
/// :nodoc:
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
try _preparedRequest(db, singleResult)
}
// FetchRequest
private let _makePreparedRequest: (Database, _ singleResult: Bool) throws -> PreparedRequest
private let _fetchCount: (Database) throws -> Int
/// :nodoc:
public func fetchCount(_ db: Database) throws -> Int {
try _fetchCount(db)
/// Creates a request bound to type RowDecoder.
///
/// - parameter type: The fetched type RowDecoder
/// - returns: A request bound to type RowDecoder.
public func asRequest<RowDecoder>(of type: RowDecoder.Type) -> AnyFetchRequest<RowDecoder> {
AnyFetchRequest<RowDecoder>(
_databaseRegion: _databaseRegion,
_requestSQL: _requestSQL,
_makePreparedRequest: _makePreparedRequest,
_fetchCount: _fetchCount)
}
/// :nodoc:
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
try _databaseRegion(db)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
try _requestSQL(context, singleResult)
}
/// :nodoc:
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
try _makePreparedRequest(db, singleResult)
}
/// :nodoc:
public func fetchCount(_ db: Database) throws -> Int {
try _fetchCount(db)
}
}
extension AnyFetchRequest {
/// Creates a request that wraps and forwards operations to `request`.
public init<Request: FetchRequest>(_ request: Request)
where Request.RowDecoder == RowDecoder
{
self.init(
_databaseRegion: request.databaseRegion,
_requestSQL: request.requestSQL,
_makePreparedRequest: request.makePreparedRequest,
_fetchCount: request.fetchCount)
}
}
+15 -15
View File
@@ -140,12 +140,12 @@ extension Row {
///
/// This method is case-insensitive.
public func hasColumn(_ columnName: String) -> Bool {
index(ofColumn: columnName) != nil
index(forColumn: columnName) != nil
}
@usableFromInline
func index(ofColumn name: String) -> Int? {
impl.index(ofColumn: name)
func index(forColumn name: String) -> Int? {
impl.index(forColumn: name)
}
}
@@ -282,7 +282,7 @@ extension Row {
// if row["foo"] != nil { ... }
//
// Without this method, the code above would not compile.
guard let index = index(ofColumn: columnName) else {
guard let index = index(forColumn: columnName) else {
return nil
}
return impl.databaseValue(atUncheckedIndex: index).storage.value
@@ -298,7 +298,7 @@ extension Row {
/// `Value`. Should this conversion fail, a fatal error is raised.
@inlinable
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value? {
guard let index = index(ofColumn: columnName) else {
guard let index = index(forColumn: columnName) else {
return nil
}
return Value.decodeIfPresent(from: self, atUncheckedIndex: index)
@@ -318,7 +318,7 @@ extension Row {
/// (see https://www.sqlite.org/datatype3.html).
@inlinable
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value? {
guard let index = index(ofColumn: columnName) else {
guard let index = index(forColumn: columnName) else {
return nil
}
return Value.fastDecodeIfPresent(from: self, atUncheckedIndex: index)
@@ -335,7 +335,7 @@ extension Row {
/// SQLite value can not be converted to `Value`.
@inlinable
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value {
guard let index = index(ofColumn: columnName) else {
guard let index = index(forColumn: columnName) else {
// No such column
fatalConversionError(to: Value.self, from: nil, in: self, atColumn: columnName)
}
@@ -357,7 +357,7 @@ extension Row {
/// (see https://www.sqlite.org/datatype3.html).
@inlinable
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value {
guard let index = index(ofColumn: columnName) else {
guard let index = index(forColumn: columnName) else {
// No such column
fatalConversionError(to: Value.self, from: nil, in: self, atColumn: columnName)
}
@@ -475,7 +475,7 @@ extension Row {
/// The returned data does not owns its bytes: it must not be used longer
/// than the row's lifetime.
public func dataNoCopy(named columnName: String) -> Data? {
guard let index = index(ofColumn: columnName) else {
guard let index = index(forColumn: columnName) else {
return nil
}
return impl.dataNoCopy(atUncheckedIndex: index)
@@ -1582,7 +1582,7 @@ protocol RowImpl {
func dataNoCopy(atUncheckedIndex index: Int) -> Data?
/// Returns the index of the leftmost column that matches *name* (case-insensitive)
func index(ofColumn name: String) -> Int?
func index(forColumn name: String) -> Int?
// row.impl is guaranteed to be self.
func unscopedRow(_ row: Row) -> Row
@@ -1665,7 +1665,7 @@ private struct ArrayRowImpl: RowImpl {
columns[index].0
}
func index(ofColumn name: String) -> Int? {
func index(forColumn name: String) -> Int? {
let lowercaseName = name.lowercased()
return columns.firstIndex { (column, _) in column.lowercased() == lowercaseName }
}
@@ -1703,7 +1703,7 @@ private struct StatementCopyRowImpl: RowImpl {
columnNames[index]
}
func index(ofColumn name: String) -> Int? {
func index(forColumn name: String) -> Int? {
let lowercaseName = name.lowercased()
return columnNames.firstIndex { $0.lowercased() == lowercaseName }
}
@@ -1777,7 +1777,7 @@ private struct StatementRowImpl: RowImpl {
statement.columnNames[index]
}
func index(ofColumn name: String) -> Int? {
func index(forColumn name: String) -> Int? {
if let index = lowercaseColumnIndexes[name] {
return index
}
@@ -1814,7 +1814,7 @@ private struct SQLiteStatementRowImpl: RowImpl {
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
}
func index(ofColumn name: String) -> Int? {
func index(forColumn name: String) -> Int? {
let name = name.lowercased()
for index in 0..<count where columnName(atUncheckedIndex: index).lowercased() == name {
return index
@@ -1839,7 +1839,7 @@ private struct EmptyRowImpl: RowImpl {
fatalError("row index out of range")
}
func index(ofColumn name: String) -> Int? { nil }
func index(forColumn name: String) -> Int? { nil }
func copiedRow(_ row: Row) -> Row { row }
}
+1 -1
View File
@@ -523,7 +523,7 @@ struct AdaptedRowImpl: RowImpl {
mapping.columnName(atMappingIndex: index)
}
func index(ofColumn name: String) -> Int? {
func index(forColumn name: String) -> Int? {
mapping.layoutIndex(ofColumn: name)
}
+38 -39
View File
@@ -14,34 +14,39 @@ public struct SQLLiteral {
/// table aliases.
enum Element {
case sql(String, StatementArguments = StatementArguments())
case subquery(SQLRequestProtocol)
// Cases below can be qualified with a table alias
case expression(SQLExpression)
case selectable(SQLSelectable)
case orderingTerm(SQLOrderingTerm)
case subQuery(SQLLiteral)
fileprivate func sql(_ context: inout SQLGenerationContext) -> String {
fileprivate func sql(_ context: SQLGenerationContext) throws -> String {
switch self {
case let .sql(sql, arguments):
if context.append(arguments: arguments) == false {
// GRDB limitation: we don't know how to look for `?` in sql and
// We don't know how to look for `?` in sql and
// replace them with literals.
fatalError("Not implemented")
fatalError("Not implemented: turning an SQL parameter into an SQL literal value")
}
return sql
case let .subquery(request):
return try request.requestSQL(context, forSingleResult: false)
case let .expression(expression):
return expression.expressionSQL(&context, wrappedInParenthesis: false)
return try expression.expressionSQL(context, wrappedInParenthesis: false)
case let .selectable(selectable):
return selectable.resultColumnSQL(&context)
return try selectable.resultColumnSQL(context)
case let .orderingTerm(orderingTerm):
return orderingTerm.orderingTermSQL(&context)
case let .subQuery(sqlLiteral):
return "(" + sqlLiteral.sql(&context) + ")"
return try orderingTerm.orderingTermSQL(context)
}
}
fileprivate func qualified(with alias: TableAlias) -> Element {
switch self {
case .sql:
// Can't qualify raw SQL string
return self
case .subquery:
// Subqueries don't need table alias
return self
case let .expression(expression):
return .expression(expression.qualifiedExpression(with: alias))
@@ -49,24 +54,10 @@ public struct SQLLiteral {
return .selectable(selectable.qualifiedSelectable(with: alias))
case let .orderingTerm(orderingTerm):
return .orderingTerm(orderingTerm.qualifiedOrdering(with: alias))
case .subQuery:
// subqueries are not requalified
return self
}
}
}
public var sql: String {
var context = SQLGenerationContext.sqlLiteralContext
return sql(&context)
}
public var arguments: StatementArguments {
var context = SQLGenerationContext.sqlLiteralContext
_ = sql(&context)
return context.arguments
}
private(set) var elements: [Element]
init(elements: [Element]) {
@@ -97,8 +88,22 @@ public struct SQLLiteral {
self.init(elements: [.expression(expression)])
}
func sql(_ context: inout SQLGenerationContext) -> String {
elements.map { $0.sql(&context) }.joined()
/// Turn a SQLLiteral into raw SQL and arguments.
///
/// - parameter db: A database connection.
/// - returns: A tuple made of a raw SQL string, and statement arguments.
public func build(_ db: Database) throws -> (sql: String, arguments: StatementArguments) {
let context = SQLGenerationContext(db)
let sql = try self.sql(context)
return (sql: sql, arguments: context.arguments)
}
// TODO: make internal when FetchRequest is a closed protocol.
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns the literal SQL string given an SQL generation context.
public func sql(_ context: SQLGenerationContext) throws -> String {
try elements.map { try $0.sql(context) }.joined()
}
fileprivate func qualified(with alias: TableAlias) -> SQLLiteral {
@@ -230,8 +235,6 @@ extension SQLLiteral: ExpressibleByStringInterpolation {
// MARK: - _SQLExpressionLiteral
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// SQLExpressionLiteral is an expression built from a raw SQL snippet.
///
/// SQLExpressionLiteral(sql: "1 + 2")
@@ -248,17 +251,13 @@ private struct _SQLExpressionLiteral: SQLExpression {
self.sqlLiteral = sqlLiteral
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
if wrappedInParenthesis {
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
}
return sqlLiteral.sql(&context)
return try sqlLiteral.sql(context)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
sqlLiteral.qualified(with: alias).sqlExpression
}
@@ -274,11 +273,11 @@ private struct _SQLSelectionLiteral: SQLSelectable {
self.sqlLiteral = sqlLiteral
}
func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
sqlLiteral.sql(&context)
func resultColumnSQL(_ context: SQLGenerationContext) throws -> String {
try sqlLiteral.sql(context)
}
func countedSQL(_ context: inout SQLGenerationContext) -> String {
func countedSQL(_ context: SQLGenerationContext) throws -> String {
fatalError("""
Selection literals can't be counted. \
To resolve this error, select one or several literal expressions instead. \
@@ -324,8 +323,8 @@ private struct _SQLOrderingLiteral: SQLOrderingTerm {
""")
}
func orderingTermSQL(_ context: inout SQLGenerationContext) -> String {
sqlLiteral.sql(&context)
func orderingTermSQL(_ context: SQLGenerationContext) throws -> String {
try sqlLiteral.sql(context)
}
func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm {
+19 -48
View File
@@ -1,5 +1,5 @@
/// A FetchRequest built from raw SQL.
public struct SQLRequest<T>: FetchRequest {
public struct SQLRequest<RowDecoder> {
/// There are two statement caches: one "public" for statements generated by
/// the user, and one "internal" for the statements generated by GRDB. Those
/// are separated so that GRDB has no opportunity to inadvertently modify
@@ -12,22 +12,6 @@ public struct SQLRequest<T>: FetchRequest {
case `internal`
}
public typealias RowDecoder = T
/// The raw SQL query
///
/// let id = 42
/// let request: SQLRequest<Player> = "SELECT * FROM player WHERE id = \(id)"
/// request.sql // "SELECT * FROM player WHERE id = ?"
public var sql: String { sqlLiteral.sql }
/// The request argument
///
/// let id = 42
/// let request: SQLRequest<Player> = "SELECT * FROM player WHERE id = \(id)"
/// request.arguments // [42]
public var arguments: StatementArguments { sqlLiteral.arguments }
/// The request adapter
public var adapter: RowAdapter?
@@ -89,28 +73,6 @@ public struct SQLRequest<T>: FetchRequest {
self.init(literal: sqlLiteral, adapter: adapter, fromCache: cached ? .public : nil)
}
/// Creates an SQL request from any other fetch request.
///
/// - parameters:
/// - db: A database connection.
/// - request: A request.
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: An SQLRequest
public init<Request>(
_ db: Database,
request: Request,
cached: Bool = false)
throws
where Request: FetchRequest, Request.RowDecoder == RowDecoder
{
let request = try request.makePreparedRequest(db, forSingleResult: false)
self.init(
literal: SQLLiteral(sql: request.statement.sql, arguments: request.statement.arguments),
adapter: request.adapter,
cached: cached)
}
/// Creates a request from an SQLLiteral, and optional row adapter.
///
/// let request = SQLRequest<String>(literal: SQLLiteral(sql: """
@@ -137,17 +99,26 @@ public struct SQLRequest<T>: FetchRequest {
self.adapter = adapter
self.cache = cache
}
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
/// - parameter singleResult: SQLRequest disregards this hint.
///
}
extension SQLRequest: SQLRequestProtocol {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
try sqlLiteral.sql(context)
}
}
extension SQLRequest: DatabaseRegionConvertible {
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
try makePreparedRequest(db, forSingleResult: false).statement.databaseRegion
}
}
extension SQLRequest: FetchRequest {
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
var context = SQLGenerationContext.sqlLiteralContext
let sql = sqlLiteral.sql(&context)
let context = SQLGenerationContext(db)
let sql = try sqlLiteral.sql(context)
let statement: SelectStatement
switch cache {
case .none:
+46
View File
@@ -0,0 +1,46 @@
/// The protocol that can generate SQL requests and subqueries.
public protocol SQLRequestProtocol: SQLExpression, SQLCollection {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns the request SQL.
///
/// - parameter context: An SQL generation context.
/// - parameter singleResult: A hint that a single result row will be
/// consumed. Implementations can optionally use it to optimize the
/// generated SQL, for example by adding a `LIMIT 1` SQL clause.
/// - returns: An SQL string.
func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String
}
// MARK: - SQLExpression
extension SQLRequestProtocol {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
let sql = try requestSQL(context, forSingleResult: false)
return "(\(sql))"
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
self
}
}
// MARK: - SQLCollection
extension SQLRequestProtocol {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func collectionSQL(_ context: SQLGenerationContext) throws -> String {
try requestSQL(context, forSingleResult: false)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func qualifiedCollection(with alias: TableAlias) -> SQLCollection {
self
}
}
+7 -2
View File
@@ -43,8 +43,13 @@ final class SerializedDatabase {
config.threadingMode = .multiThread
self.path = path
self.db = try Database(path: path, configuration: config, schemaCache: schemaCache)
self.queue = configuration.makeDispatchQueue(defaultLabel: defaultLabel, purpose: purpose)
let identifier = configuration.identifier(defaultLabel: defaultLabel, purpose: purpose)
self.db = try Database(
path: path,
description: identifier,
configuration: config,
schemaCache: schemaCache)
self.queue = configuration.makeDispatchQueue(label: identifier)
SchedulingWatchdog.allowDatabase(db, onQueue: queue)
try queue.sync {
do {
+6 -8
View File
@@ -24,11 +24,12 @@ public class Statement {
.trimmingCharacters(in: .sqlStatementSeparators)
}
// Selected region is computed during statement compilation, and maybe
// optimized for select statements compiled by QueryInterfaceRequest, in
// Database region is computed during statement compilation, and maybe
// extended for select statements compiled by QueryInterfaceRequest, in
// order to perform focused database observation. See
// SQLQueryGenerator.optimizedSelectedRegion(_:_:)
var selectedRegion = DatabaseRegion()
// SQLQueryGenerator.makeSelectStatement(_:)
/// The database region that the statement looks into.
public internal(set) var databaseRegion = DatabaseRegion()
var isReadonly: Bool {
sqlite3_stmt_readonly(sqliteStatement) != 0
@@ -87,7 +88,7 @@ public class Statement {
self.database = database
self.sqliteStatement = statement
self.selectedRegion = authorizer.selectedRegion
self.databaseRegion = authorizer.selectedRegion
}
deinit {
@@ -356,9 +357,6 @@ public final class SelectStatement: Statement {
"Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
}
/// The database region that the statement looks into.
public var databaseRegion: DatabaseRegion { selectedRegion }
/// The number of columns in the resulting rows.
public var columnCount: Int {
Int(sqlite3_column_count(self.sqliteStatement))
@@ -1,3 +1,21 @@
/// SQLExpressible is free for RawRepresentable types whose raw value
/// is itself SQLExpressible.
///
/// // If the RawValue adopts SQLExpressible...
/// enum Color : Int {
/// case red
/// case white
/// case rose
/// }
///
/// // ... then the RawRepresentable type can freely adopt SQLExpressible:
/// extension Color : SQLExpressible { /* empty */ }
extension SQLExpressible where Self: RawRepresentable, Self.RawValue: SQLExpressible {
public var sqlExpression: SQLExpression {
rawValue.sqlExpression
}
}
/// DatabaseValueConvertible is free for RawRepresentable types whose raw value
/// is itself DatabaseValueConvertible.
///
@@ -554,7 +554,7 @@ extension DatabaseFunction {
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.localizedCapitalized)
/// let names = try String.fetchAll(dbQueue, request) // [String]
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
@available(OSX 10.11, watchOS 3.0, *)
public static let localizedCapitalize =
DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
@@ -575,7 +575,7 @@ extension DatabaseFunction {
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.localizedLowercased)
/// let names = try String.fetchAll(dbQueue, request) // [String]
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
@available(OSX 10.11, watchOS 3.0, *)
public static let localizedLowercase =
DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
@@ -596,7 +596,7 @@ extension DatabaseFunction {
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.localizedUppercased)
/// let names = try String.fetchAll(dbQueue, request) // [String]
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
@available(OSX 10.11, watchOS 3.0, *)
public static let localizedUppercase =
DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
+12
View File
@@ -283,6 +283,17 @@ class DatabaseObservationBroker {
}
}
switch transactionState {
case .none:
break
default:
// May happen after "PRAGMA journal_mode = WAL" executed with a
// SelectStatement.
// TODO: Maybe this state machine should be run for *all* statements,
// not ony update statements.
transactionState = .none
}
if observesRowDeletion {
return TruncateOptimizationBlocker()
} else {
@@ -496,6 +507,7 @@ class DatabaseObservationBroker {
/// Remove transaction observers that have stopped observing transaction,
/// and uninstall SQLite update hooks if there is no remaining observers.
private func databaseDidEndTransaction() {
assert(!database.isInsideTransaction)
transactionObservations = transactionObservations.filter(\.isObserving)
// Undo disableUntilNextTransaction(transactionObserver:)
+4 -2
View File
@@ -19,8 +19,10 @@ public struct FTS3Pattern {
// that pattern.
do {
try DatabaseQueue().inDatabase { db in
try db.execute(sql: "CREATE VIRTUAL TABLE documents USING fts3()")
try db.execute(sql: "SELECT * FROM documents WHERE content MATCH ?", arguments: [rawPattern])
try db.execute(literal: """
CREATE VIRTUAL TABLE documents USING fts3();
SELECT * FROM documents WHERE content MATCH \(rawPattern);
""")
}
} catch let error as DatabaseError {
// Remove private SQL & arguments from the thrown error
+8 -8
View File
@@ -69,40 +69,40 @@ public struct FTS5: VirtualTableModule {
}
if let tokenizer = definition.tokenizer {
let tokenizerSQL = tokenizer
let tokenizerSQL = try tokenizer
.components
.joined(separator: " ")
.sqlExpression
.quotedSQL()
.quotedSQL(db)
arguments.append("tokenize=\(tokenizerSQL)")
}
switch definition.contentMode {
case let .raw(content, contentRowID):
if let content = content {
let quotedContent = content.sqlExpression.quotedSQL()
let quotedContent = try content.sqlExpression.quotedSQL(db)
arguments.append("content=\(quotedContent)")
}
if let contentRowID = contentRowID {
let quotedContentRowID = contentRowID.sqlExpression.quotedSQL()
let quotedContentRowID = try contentRowID.sqlExpression.quotedSQL(db)
arguments.append("content_rowid=\(quotedContentRowID)")
}
case let .synchronized(contentTable):
arguments.append("content=\(contentTable.sqlExpression.quotedSQL())")
try arguments.append("content=\(contentTable.sqlExpression.quotedSQL(db))")
if let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn {
let quotedRowID = rowIDColumn.sqlExpression.quotedSQL()
let quotedRowID = try rowIDColumn.sqlExpression.quotedSQL(db)
arguments.append("content_rowid=\(quotedRowID)")
}
}
if let prefixes = definition.prefixes {
let prefix = prefixes
let prefix = try prefixes
.sorted()
.map { "\($0)" }
.joined(separator: " ")
.sqlExpression
.quotedSQL()
.quotedSQL(db)
arguments.append("prefix=\(prefix)")
}
+37 -26
View File
@@ -59,14 +59,17 @@ public struct FTS5TokenizerDescriptor {
if separators.isEmpty {
components = ["ascii"]
} else {
components = [
"ascii",
"separators",
separators
.map { String($0) }
.joined()
.sqlExpression
.quotedSQL()]
components = DatabaseQueue().inDatabase { db in
// Assume quoting a string never fails
try! [
"ascii",
"separators",
separators
.map { String($0) }
.joined()
.sqlExpression
.quotedSQL(db)]
}
}
return FTS5TokenizerDescriptor(components: components)
}
@@ -126,29 +129,37 @@ public struct FTS5TokenizerDescriptor {
// TODO: test "=" and "\"", "(" and ")" as separators, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
components.append(contentsOf: [
"separators",
separators
.sorted()
.map { String($0) }
.joined()
.sqlExpression
.quotedSQL()
])
let separatorComponents = DatabaseQueue().inDatabase { db in
// Assume quoting a string never fails
try! [
"separators",
separators
.sorted()
.map { String($0) }
.joined()
.sqlExpression
.quotedSQL(db)
]
}
components.append(contentsOf: separatorComponents)
}
if !tokenCharacters.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
components.append(contentsOf: [
"tokenchars",
tokenCharacters
.sorted()
.map { String($0) }
.joined()
.sqlExpression
.quotedSQL()
])
let tokenCharactersComponents = DatabaseQueue().inDatabase { db in
// Assume quoting a string never fails
try! [
"tokenchars",
tokenCharacters
.sorted()
.map { String($0) }
.joined()
.sqlExpression
.quotedSQL(db)
]
}
components.append(contentsOf: tokenCharactersComponents)
}
return FTS5TokenizerDescriptor(components: components)
}
+68 -6
View File
@@ -7,6 +7,13 @@ import UIKit
#endif
extension AnyFetchRequest {
@available(*, unavailable, renamed: "RowDecoder")
typealias T = RowDecoder
@available(*, unavailable, message: "Use AnyFetchRequest(request).asRequest(of: SomeType.self) instead.")
public init<Request: FetchRequest>(_ request: Request)
{ preconditionFailure() }
@available(*, unavailable, message: "Define your own FetchRequest type instead.")
public init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?))
{ preconditionFailure() }
@@ -40,6 +47,14 @@ extension AssociationAggregate {
{ preconditionFailure() }
}
extension Configuration {
@available(*, unavailable, message: "Use Database.trace(options:_:) in Configuration.prepareDatabase instead.")
public var trace: TraceFunction? {
get { preconditionFailure() }
set { preconditionFailure() }
}
}
extension DatabaseFunction {
@available(*, unavailable, renamed: "callAsFunction(_:)")
public func apply(_ arguments: SQLExpressible...) -> SQLExpression
@@ -71,6 +86,9 @@ extension DatabaseMigrator {
}
extension DatabasePool {
@available(*, unavailable, message: "Use pool.writeWithoutTransaction { $0.checkpoint() } instead")
public func checkpoint(_ kind: Database.CheckpointMode = .passive) throws { preconditionFailure() }
#if os(iOS)
@available(*, unavailable, message: "Memory management is now enabled by default. This method does nothing.")
public func setupMemoryManagement(in application: UIApplication) { preconditionFailure() }
@@ -134,12 +152,23 @@ extension FetchRequest where RowDecoder == Row {
{ preconditionFailure() }
}
extension QueryInterfaceRequest {
@available(*, unavailable, renamed: "RowDecoder")
typealias T = RowDecoder
}
extension SQLExpression {
@available(*, unavailable, message: "Use SQLLiteral initializer instead")
public var sqlLiteral: SQLLiteral
{ preconditionFailure() }
}
extension FilteredRequest {
@available(*, unavailable, message: "The expectingSingleResult() hint is no longer available.")
func expectingSingleResult() -> Self
{ preconditionFailure() }
}
@available(*, unavailable, message: "Build literal expressions with SQLLiteral.sqlExpression instead.")
public struct SQLExpressionLiteral: SQLExpression {
public var sql: String { preconditionFailure() }
@@ -151,7 +180,7 @@ public struct SQLExpressionLiteral: SQLExpression {
public init(literal sqlLiteral: SQLLiteral)
{ preconditionFailure() }
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String
{ preconditionFailure() }
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression
@@ -162,11 +191,37 @@ extension SQLLiteral {
@available(*, unavailable, message: "Use SQL interpolation instead.")
public func mapSQL(_ transform: @escaping (String) -> String) -> SQLLiteral
{ preconditionFailure() }
@available(*, unavailable, message: "Use the build(_:) method instead.")
public var sql: String { preconditionFailure() }
@available(*, unavailable, message: "Use the build(_:) method instead.")
public var arguments: StatementArguments { preconditionFailure() }
}
@available(*, unavailable, renamed: "SQLAssociativeBinaryOperator")
typealias SQLLogicalBinaryOperator = SQLAssociativeBinaryOperator
extension SQLRequest {
@available(*, unavailable, renamed: "RowDecoder")
typealias T = RowDecoder
@available(*, unavailable, message: "Turning a request into SQLRequest is no longer supported.")
public init<Request>(
_ db: Database,
request: Request,
cached: Bool = false)
throws
where Request: FetchRequest, Request.RowDecoder == RowDecoder
{ preconditionFailure() }
@available(*, unavailable, message: "Use makePreparedRequest(db, forSingleResult: false).statement.sql instead")
public var sql: String { preconditionFailure() }
@available(*, unavailable, message: "Use makePreparedRequest(db, forSingleResult: false).statement.arguments instead")
public var arguments: StatementArguments { preconditionFailure() }
}
extension SQLSpecificExpressible {
@available(*, unavailable, renamed: "forKey(_:)")
public func aliased(_ name: String) -> SQLSelectable
@@ -191,6 +246,10 @@ extension TableRecord {
@available(*, unavailable, message: "Use ValueObservation.tracking(MyRecord.fetchCount) instead")
public static func observationForCount() -> ValueObservation<ValueReducers.Unavailable<Int>>
{ preconditionFailure() }
@available(*, unavailable, message: "Use SQL interpolation instead")
public static func selectionSQL(alias: String? = nil) -> String
{ preconditionFailure() }
}
extension TableRecord where Self: FetchableRecord {
@@ -203,6 +262,9 @@ extension TableRecord where Self: FetchableRecord {
{ preconditionFailure() }
}
@available(*, unavailable)
public typealias TraceFunction = (String) -> Void
extension ValueObservation {
@available(*, unavailable, message: "ValueObservation now schedules its values asynchronously on the main queue by default. See ValueObservation.start() for possible configuration")
var scheduling: ValueScheduling {
@@ -213,7 +275,7 @@ extension ValueObservation {
@available(*, unavailable, message: "Custom reducers are no longer supported. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
public static func tracking(_ regions: DatabaseRegionConvertible..., reducer: @escaping (Database) throws -> Reducer) -> ValueObservation
{ preconditionFailure() }
@available(*, unavailable, message: "Custom reducers are no longer supported. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
public static func tracking(_ regions: [DatabaseRegionConvertible], reducer: @escaping (Database) throws -> Reducer) -> ValueObservation
{ preconditionFailure() }
@@ -226,7 +288,7 @@ extension ValueObservation {
_ transform: @escaping (Reducer.Value, R1.Value) -> Combined)
-> ValueObservation<ValueReducers.Unavailable<Combined>>
{ preconditionFailure() }
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
public func combine<
R1: _ValueReducer,
@@ -237,7 +299,7 @@ extension ValueObservation {
_ transform: @escaping (Reducer.Value, R1.Value, R2.Value) -> Combined)
-> ValueObservation<ValueReducers.Unavailable<Combined>>
{ preconditionFailure() }
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
public func combine<
R1: _ValueReducer,
@@ -250,7 +312,7 @@ extension ValueObservation {
_ transform: @escaping (Reducer.Value, R1.Value, R2.Value, R3.Value) -> Combined)
-> ValueObservation<ValueReducers.Unavailable<Combined>>
{ preconditionFailure() }
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
public func combine<
R1: _ValueReducer,
@@ -284,7 +346,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto {
R2: _ValueReducer>(
_ o1: ValueObservation<R1>,
_ o2: ValueObservation<R2>)
-> ValueObservation<ValueReducers.Unavailable<(R1.Value, R2.Value)>>
-> ValueObservation<ValueReducers.Unavailable<(R1.Value, R2.Value)>>
{ preconditionFailure() }
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
+36 -19
View File
@@ -140,6 +140,7 @@ public struct DatabaseMigrator {
// migrations would involve a lot of data).
var witnessConfiguration = writer.configuration
witnessConfiguration.targetQueue = nil // Avoid deadlocks
witnessConfiguration.label = "GRDB.DatabaseMigrator.temporary"
let witness = try DatabaseQueue(path: "", configuration: witnessConfiguration)
// Grab schema of migrated witness database
@@ -170,8 +171,10 @@ public struct DatabaseMigrator {
// MARK: - Querying Migrations
/// Returns the applied migration identifiers, in the same order as
/// registered migrations.
/// Returns the identifiers of registered and applied migrations, in the
/// order of registration.
///
/// See also `appliedIdentifiers(_:)`.
///
/// - parameter db: A database connection.
/// - throws: An eventual database error.
@@ -180,6 +183,24 @@ public struct DatabaseMigrator {
return migrations.map { $0.identifier }.filter { appliedIdentifiers.contains($0) }
}
/// Returns the applied migration identifiers, even unregistered ones.
///
/// See also `appliedMigrations(_:)`.
///
/// - parameter db: A database connection.
/// - throws: An eventual database error.
public func appliedIdentifiers(_ db: Database) throws -> Set<String> {
do {
return try Set(String.fetchCursor(db, sql: "SELECT identifier FROM grdb_migrations"))
} catch {
// Rethrow if we can't prove grdb_migrations does not exist yet
if (try? !db.tableExists("grdb_migrations")) ?? false {
return []
}
throw error
}
}
/// Returns the identifiers of completed migrations, of which all previous
/// migrations have been applied.
///
@@ -200,7 +221,19 @@ public struct DatabaseMigrator {
public func hasCompletedMigrations(_ db: Database) throws -> Bool {
try completedMigrations(db).last == migrations.last?.identifier
}
/// Returns whether database contains unknown migration
/// identifiers, which is likely the sign that the database
/// has migrated further than the migrator itself supports.
///
/// - parameter db: A database connection.
/// - throws: An eventual database error.
public func hasBeenSuperseded(_ db: Database) throws -> Bool {
let appliedIdentifiers = try self.appliedIdentifiers(db)
let knownIdentifiers = migrations.map(\.identifier)
return appliedIdentifiers.contains { !knownIdentifiers.contains($0) }
}
// MARK: - Non public
private mutating func registerMigration(_ migration: Migration) {
@@ -210,22 +243,6 @@ public struct DatabaseMigrator {
migrations.append(migration)
}
/// Returns the applied migration identifiers, even unregistered ones
///
/// - parameter db: A database connection.
/// - throws: An eventual database error.
public func appliedIdentifiers(_ db: Database) throws -> Set<String> {
do {
return try Set(String.fetchCursor(db, sql: "SELECT identifier FROM grdb_migrations"))
} catch {
// Rethrow if we can't prove grdb_migrations does not exist yet
if (try? !db.tableExists("grdb_migrations")) ?? false {
return []
}
throw error
}
}
/// Returns unapplied migration identifier,
private func unappliedMigrations(upTo targetIdentifier: String, appliedIdentifiers: [String]) -> [Migration] {
var expectedMigrations: [Migration] = []
+1 -4
View File
@@ -4,10 +4,7 @@ struct Migration {
let migrate: (Database) throws -> Void
func run(_ db: Database) throws {
// PRAGMA foreign_key_check and SQLITE_CONSTRAINT_FOREIGNKEY were
// introduced in SQLite 3.7.16
// http://www.sqlite.org/changes.html#version_3_7_16
if try sqlite3_libversion_number() >= 3007016 && (Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false) {
if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false {
try runWithDeferredForeignKeysChecks(db)
} else {
try runWithoutDisabledForeignKeys(db)
@@ -113,7 +113,7 @@ extension Association {
/// // SELECT player.*, team.color
/// // FROM player
/// // JOIN team ON team.id = player.teamId
/// let association = Player.team.select([Column("color")])
/// let association = Player.team.select { db in [Column("color")]
/// var request = Player.including(required: association)
///
/// Any previous selection is replaced:
@@ -122,10 +122,10 @@ extension Association {
/// // FROM player
/// // JOIN team ON team.id = player.teamId
/// let association = Player.team
/// .select([Column("id")])
/// .select([Column("color")])
/// .select { db in [Column("id")] }
/// .select { db in [Column("color") }
/// var request = Player.including(required: association)
public func select(_ selection: [SQLSelectable]) -> Self {
public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
mapDestinationRelation { $0.select(selection) }
}
@@ -140,9 +140,9 @@ extension Association {
/// // JOIN team ON team.id = player.teamId
/// let association = Player.team
/// .select([Column("color")])
/// .annotated(with: [Column("name")])
/// .annotated(with: { db in [Column("name")] })
/// var request = Player.including(required: association)
public func annotated(with selection: [SQLSelectable]) -> Self {
public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
mapDestinationRelation { $0.annotated(with: selection) }
}
@@ -321,164 +321,3 @@ extension AssociationToMany {
return .init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey))
}
}
extension AssociationToMany {
private func makeAggregate(_ expression: SQLExpression) -> AssociationAggregate<OriginRowDecoder> {
AssociationAggregate { request in
let tableAlias = TableAlias()
let request = request
.joining(optional: self.aliased(tableAlias))
.groupByPrimaryKey()
let expression = tableAlias[expression]
return (request: request, expression: expression)
}
}
/// The number of associated records.
///
/// It has a default name, which is "[key]Count", where key is the key of
/// the association. For example:
///
/// For example:
///
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var playerCount: Int
/// }
/// let request = Team.annotated(with: Team.players.count())
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
///
/// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db)
public var count: AssociationAggregate<OriginRowDecoder> {
makeAggregate(SQLExpressionCountDistinct(Column.rowID))
.forKey("\(key.singularizedName)Count")
}
/// Creates an aggregate that is true if there exists no associated records.
///
/// It has a default name, which is "hasNo[Key]", where key is the key of
/// the association. For example:
///
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var hasNoPlayer: Bool
/// }
/// let request = Team.annotated(with: Team.players.isEmpty())
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
///
/// let teams: [Team] = try Team.having(Team.players.isEmpty()).fetchAll(db)
/// let teams: [Team] = try Team.having(!Team.players.isEmpty())
/// let teams: [Team] = try Team.having(Team.players.isEmpty() == false)
public var isEmpty: AssociationAggregate<OriginRowDecoder> {
makeAggregate(SQLExpressionIsEmpty(SQLExpressionCountDistinct(Column.rowID)))
.forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)")
}
/// Creates an aggregate which evaluate to the average value of the given
/// expression in associated records.
///
/// When the averaged expression is a column, the aggregate has a default
/// name which is "average[Key][Column]", where key is the key of the
/// association. For example:
///
/// For example:
///
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var averagePlayerScore: Double
/// }
/// let request = Team.annotated(with: Team.players.average(Column("score")))
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
///
/// let teams: [Team] = try Team.having(Team.players.average(Column("score")) > 100).fetchAll(db)
public func average(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(SQLExpressionFunction(.avg, arguments: expression))
if let column = expression as? ColumnExpression {
let name = key.singularizedName
return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
} else {
return aggregate
}
}
/// Creates an aggregate which evaluate to the maximum value of the given
/// expression in associated records.
///
/// When the maximized expression is a column, the aggregate has a default
/// name which is "maximum[Key][Column]", where key is the key of the
/// association. For example:
///
/// For example:
///
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var maxPlayerScore: Double
/// }
/// let request = Team.annotated(with: Team.players.max(Column("score")))
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
///
/// let teams: [Team] = try Team.having(Team.players.max(Column("score")) < 100).fetchAll(db)
public func max(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(SQLExpressionFunction(.max, arguments: expression))
if let column = expression as? ColumnExpression {
let name = key.singularizedName
return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
} else {
return aggregate
}
}
/// Creates an aggregate which evaluate to the minimum value of the given
/// expression in associated records.
///
/// When the minimized expression is a column, the aggregate has a default
/// name which is "minimum[Key][Column]", where key is the key of the
/// association. For example:
///
/// For example:
///
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var minPlayerScore: Double
/// }
/// let request = Team.annotated(with: Team.players.min(Column("score")))
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
///
/// let teams: [Team] = try Team.having(Team.players.min(Column("score")) > 100).fetchAll(db)
public func min(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(SQLExpressionFunction(.min, arguments: expression))
if let column = expression as? ColumnExpression {
let name = key.singularizedName
return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
} else {
return aggregate
}
}
/// Creates an aggregate which evaluate to the sum of the given expression
/// in associated records.
///
/// When the summed expression is a column, the aggregate has a default
/// name which is "[key][Column]Sum", where key is the key of the
/// association. For example:
///
/// For example:
///
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var playerScoreSum: Double
/// }
/// let request = Team.annotated(with: Team.players.sum(Column("score")))
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
///
/// let teams: [Team] = try Team.having(Team.players.sum(Column("score")) > 100).fetchAll(db)
public func sum(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(SQLExpressionFunction(.sum, arguments: expression))
if let column = expression as? ColumnExpression {
let name = key.singularizedName
return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum")
} else {
return aggregate
}
}
}
@@ -1,8 +1,180 @@
import Foundation
typealias AssociationAggregatePreparation<RowDecoder> =
(QueryInterfaceRequest<RowDecoder>)
-> (request: QueryInterfaceRequest<RowDecoder>, expression: SQLExpression)
(inout QueryInterfaceRequest<RowDecoder>)
-> DatabasePromise<SQLExpression>
extension AssociationToMany {
private func makeAggregate(_ expressionPromise: DatabasePromise<SQLExpression>)
-> AssociationAggregate<OriginRowDecoder>
{
AssociationAggregate { request in
let tableAlias = TableAlias()
request = request
.joining(optional: self.aliased(tableAlias))
.groupByPrimaryKey()
return expressionPromise.map { tableAlias[$0] }
}
}
// Convenience
private func makeAggregate(_ expression: SQLExpression) -> AssociationAggregate<OriginRowDecoder> {
makeAggregate(DatabasePromise(value: expression))
}
/// The number of associated records.
///
/// It has a default name, which is "[key]Count", where key is the key of
/// the association. For example:
///
/// For example:
///
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var playerCount: Int
/// }
/// let request = Team.annotated(with: Team.players.count())
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
///
/// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db)
public var count: AssociationAggregate<OriginRowDecoder> {
let expression = SQLExpressionCountDistinct(
SQLPrimaryKeyExpression(
tableName: self.databaseTableName))
return makeAggregate(expression).forKey("\(key.singularizedName)Count")
}
/// Creates an aggregate that is true if there exists no associated records.
///
/// It has a default name, which is "hasNo[Key]", where key is the key of
/// the association. For example:
///
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var hasNoPlayer: Bool
/// }
/// let request = Team.annotated(with: Team.players.isEmpty())
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
///
/// let teams: [Team] = try Team.having(Team.players.isEmpty()).fetchAll(db)
/// let teams: [Team] = try Team.having(!Team.players.isEmpty())
/// let teams: [Team] = try Team.having(Team.players.isEmpty() == false)
public var isEmpty: AssociationAggregate<OriginRowDecoder> {
let expression = SQLExpressionIsEmpty(
SQLExpressionCountDistinct(
SQLPrimaryKeyExpression(
tableName: self.databaseTableName)))
return makeAggregate(expression).forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)")
}
/// Creates an aggregate which evaluate to the average value of the given
/// expression in associated records.
///
/// When the averaged expression is a column, the aggregate has a default
/// name which is "average[Key][Column]", where key is the key of the
/// association. For example:
///
/// For example:
///
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var averagePlayerScore: Double
/// }
/// let request = Team.annotated(with: Team.players.average(Column("score")))
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
///
/// let teams: [Team] = try Team.having(Team.players.average(Column("score")) > 100).fetchAll(db)
public func average(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(SQLExpressionFunction(.avg, arguments: expression))
if let column = expression as? ColumnExpression {
let name = key.singularizedName
return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
} else {
return aggregate
}
}
/// Creates an aggregate which evaluate to the maximum value of the given
/// expression in associated records.
///
/// When the maximized expression is a column, the aggregate has a default
/// name which is "maximum[Key][Column]", where key is the key of the
/// association. For example:
///
/// For example:
///
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var maxPlayerScore: Double
/// }
/// let request = Team.annotated(with: Team.players.max(Column("score")))
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
///
/// let teams: [Team] = try Team.having(Team.players.max(Column("score")) < 100).fetchAll(db)
public func max(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(SQLExpressionFunction(.max, arguments: expression))
if let column = expression as? ColumnExpression {
let name = key.singularizedName
return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
} else {
return aggregate
}
}
/// Creates an aggregate which evaluate to the minimum value of the given
/// expression in associated records.
///
/// When the minimized expression is a column, the aggregate has a default
/// name which is "minimum[Key][Column]", where key is the key of the
/// association. For example:
///
/// For example:
///
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var minPlayerScore: Double
/// }
/// let request = Team.annotated(with: Team.players.min(Column("score")))
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
///
/// let teams: [Team] = try Team.having(Team.players.min(Column("score")) > 100).fetchAll(db)
public func min(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(SQLExpressionFunction(.min, arguments: expression))
if let column = expression as? ColumnExpression {
let name = key.singularizedName
return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
} else {
return aggregate
}
}
/// Creates an aggregate which evaluate to the sum of the given expression
/// in associated records.
///
/// When the summed expression is a column, the aggregate has a default
/// name which is "[key][Column]Sum", where key is the key of the
/// association. For example:
///
/// For example:
///
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var playerScoreSum: Double
/// }
/// let request = Team.annotated(with: Team.players.sum(Column("score")))
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
///
/// let teams: [Team] = try Team.having(Team.players.sum(Column("score")) > 100).fetchAll(db)
public func sum(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(SQLExpressionFunction(.sum, arguments: expression))
if let column = expression as? ColumnExpression {
let name = key.singularizedName
return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum")
} else {
return aggregate
}
}
}
/// An AssociationAggregate is able to compute aggregated values from a
/// population of associated records.
@@ -27,9 +199,9 @@ typealias AssociationAggregatePreparation<RowDecoder> =
/// // Won't compile because Fruit is not Author.
/// let request = Fruit.annotated(with: bookCount)
public struct AssociationAggregate<RowDecoder> {
/// Given a request, returns a tuple made of a request extended with the
/// associated records used to compute the aggregate, and an expression
/// whose value is the aggregated value.
/// Extend the request with the associated records used to compute the
/// aggregate, and return an expression promise which resolves to the
/// aggregated value.
///
/// For example:
///
@@ -38,22 +210,22 @@ public struct AssociationAggregate<RowDecoder> {
/// }
///
/// // SELECT * FROM author
/// let request = Author.all()
/// var request = Author.all()
///
/// let aggregate = Author.books.count
/// let tuple = aggregate.prepare(request)
/// let expressionPromise = aggregate.prepare(&request)
///
/// // The request extended with associated records:
/// // The request has been extended with associated records:
/// //
/// // SELECT author.* FROM author
/// // LEFT JOIN book ON book.authorId = author.id
/// // GROUP BY author.id
/// tuple.request
/// request
///
/// // The aggregated value:
/// //
/// // COUNT(DISTINCT book.rowid)
/// tuple.expression
/// // COUNT(DISTINCT book.id)
/// try expressionPromise.resolve(db)
///
/// The aggregated value is not right away embedded in the extended request:
///
@@ -98,6 +270,31 @@ extension AssociationAggregate: Refinable {
public func forKey(_ key: CodingKey) -> Self {
forKey(key.stringValue)
}
/// Transforms the expression, and does not preserve key.
fileprivate func map(_ transform: @escaping (SQLExpression) throws -> SQLExpression) -> Self {
AssociationAggregate { request in
self.prepare(&request).map(transform)
}
}
}
/// Combines the expression of two aggregates.
private func combine<RowDecoder>(
_ lhs: AssociationAggregate<RowDecoder>,
_ rhs: AssociationAggregate<RowDecoder>,
with combineExpressions : @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let lhsPromise = lhs.prepare(&request)
let rhsPromise = rhs.prepare(&request)
return DatabasePromise { db in
try combineExpressions(
lhsPromise.resolve(db),
rhsPromise.resolve(db))
}
}
}
// MARK: - Logical Operators (AND, OR, NOT)
@@ -108,10 +305,7 @@ extension AssociationAggregate: Refinable {
///
/// Author.having(!Author.books.isEmpty)
public prefix func ! <RowDecoder>(aggregate: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
AssociationAggregate { request in
let (request, expression) = aggregate.prepare(request)
return (request: request, expression: !expression)
}
aggregate.map { !$0 }
}
/// Groups two aggregates with the `AND` SQL operator.
@@ -124,11 +318,7 @@ public func && <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression && rExpression)
}
combine(lhs, rhs, with: &&)
}
// TODO: test
@@ -138,10 +328,7 @@ public func && <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression && rhs)
}
lhs.map { $0 && rhs }
}
// TODO: test
@@ -151,10 +338,7 @@ public func && <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs && expression)
}
rhs.map { lhs && $0 }
}
@@ -168,11 +352,7 @@ public func || <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression || rExpression)
}
combine(lhs, rhs, with: ||)
}
// TODO: test
@@ -182,10 +362,7 @@ public func || <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression || rhs)
}
lhs.map { $0 || rhs }
}
// TODO: test
@@ -195,10 +372,7 @@ public func || <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs || expression)
}
rhs.map { lhs || $0 }
}
// MARK: - Egality and Identity Operators (=, <>, IS, IS NOT)
@@ -213,11 +387,7 @@ public func == <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression == rExpression)
}
combine(lhs, rhs, with: ==)
}
/// Returns an aggregate that compares an aggregate with the `=` SQL operator.
@@ -230,10 +400,7 @@ public func == <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression == rhs)
}
lhs.map { $0 == rhs }
}
/// Returns an aggregate that compares an aggregate with the `=` SQL operator.
@@ -246,10 +413,7 @@ public func == <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs == expression)
}
rhs.map { lhs == $0 }
}
/// Returns an aggregate that checks the boolean value of an aggregate.
@@ -258,10 +422,7 @@ public func == <RowDecoder>(
///
/// Author.having(Author.books.isEmpty == false)
public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) -> AssociationAggregate<RowDecoder> {
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression == rhs)
}
lhs.map { $0 == rhs }
}
/// Returns an aggregate that checks the boolean value of an aggregate.
@@ -270,10 +431,7 @@ public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) ->
///
/// Author.having(false == Author.books.isEmpty)
public func == <RowDecoder>(lhs: Bool, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs == expression)
}
rhs.map { lhs == $0 }
}
/// Returns an aggregate that compares two aggregates with the `<>` SQL operator.
@@ -286,11 +444,7 @@ public func != <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression != rExpression)
}
combine(lhs, rhs, with: !=)
}
/// Returns an aggregate that compares an aggregate with the `<>` SQL operator.
@@ -303,10 +457,7 @@ public func != <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression != rhs)
}
lhs.map { $0 != rhs }
}
/// Returns an aggregate that compares an aggregate with the `<>` SQL operator.
@@ -319,10 +470,7 @@ public func != <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs != expression)
}
rhs.map { lhs != $0 }
}
/// Returns an aggregate that checks the boolean value of an aggregate.
@@ -331,10 +479,7 @@ public func != <RowDecoder>(
///
/// Author.having(Author.books.isEmpty != true)
public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) -> AssociationAggregate<RowDecoder> {
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression != rhs)
}
lhs.map { $0 != rhs }
}
/// Returns an aggregate that checks the boolean value of an aggregate.
@@ -343,10 +488,7 @@ public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) ->
///
/// Author.having(true != Author.books.isEmpty)
public func != <RowDecoder>(lhs: Bool, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs != expression)
}
rhs.map { lhs != $0 }
}
/// Returns an aggregate that compares two aggregates with the `IS` SQL operator.
@@ -359,11 +501,7 @@ public func === <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression === rExpression)
}
combine(lhs, rhs, with: ===)
}
/// Returns an aggregate that compares an aggregate with the `IS` SQL operator.
@@ -376,10 +514,7 @@ public func === <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression === rhs)
}
lhs.map { $0 === rhs }
}
/// Returns an aggregate that compares an aggregate with the `IS` SQL operator.
@@ -392,10 +527,7 @@ public func === <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs === expression)
}
rhs.map { lhs === $0 }
}
/// Returns an aggregate that compares two aggregates with the `IS NOT` SQL operator.
@@ -408,11 +540,7 @@ public func !== <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression !== rExpression)
}
combine(lhs, rhs, with: !==)
}
/// Returns an aggregate that compares an aggregate with the `IS NOT` SQL operator.
@@ -425,10 +553,7 @@ public func !== <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression !== rhs)
}
lhs.map { $0 !== rhs }
}
/// Returns an aggregate that compares an aggregate with the `IS NOT` SQL operator.
@@ -441,10 +566,7 @@ public func !== <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs !== expression)
}
rhs.map { lhs !== $0 }
}
// MARK: - Comparison Operators (<, >, <=, >=)
@@ -459,11 +581,7 @@ public func <= <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression <= rExpression)
}
combine(lhs, rhs, with: <=)
}
/// Returns an aggregate that compares an aggregate with the `<=` SQL operator.
@@ -476,10 +594,7 @@ public func <= <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression <= rhs)
}
lhs.map { $0 <= rhs }
}
/// Returns an aggregate that compares an aggregate with the `<=` SQL operator.
@@ -492,10 +607,7 @@ public func <= <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs <= expression)
}
rhs.map { lhs <= $0 }
}
/// Returns an aggregate that compares two aggregates with the `<` SQL operator.
@@ -508,11 +620,7 @@ public func < <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression < rExpression)
}
combine(lhs, rhs, with: <)
}
/// Returns an aggregate that compares an aggregate with the `<` SQL operator.
@@ -525,10 +633,7 @@ public func < <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression < rhs)
}
lhs.map { $0 < rhs }
}
/// Returns an aggregate that compares an aggregate with the `<` SQL operator.
@@ -541,10 +646,7 @@ public func < <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs < expression)
}
rhs.map { lhs < $0 }
}
/// Returns an aggregate that compares two aggregates with the `>` SQL operator.
@@ -557,11 +659,7 @@ public func > <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression > rExpression)
}
combine(lhs, rhs, with: >)
}
/// Returns an aggregate that compares an aggregate with the `>` SQL operator.
@@ -574,10 +672,7 @@ public func > <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression > rhs)
}
lhs.map { $0 > rhs }
}
/// Returns an aggregate that compares an aggregate with the `>` SQL operator.
@@ -590,10 +685,7 @@ public func > <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs > expression)
}
rhs.map { lhs > $0 }
}
/// Returns an aggregate that compares two aggregates with the `>=` SQL operator.
@@ -606,11 +698,7 @@ public func >= <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression >= rExpression)
}
combine(lhs, rhs, with: >=)
}
/// Returns an aggregate that compares an aggregate with the `>=` SQL operator.
@@ -623,10 +711,7 @@ public func >= <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression >= rhs)
}
lhs.map { $0 >= rhs }
}
/// Returns an aggregate that compares an aggregate with the `>=` SQL operator.
@@ -639,10 +724,7 @@ public func >= <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs >= expression)
}
rhs.map { lhs >= $0 }
}
// MARK: - Arithmetic Operators (+, -, *, /)
@@ -653,10 +735,7 @@ public func >= <RowDecoder>(
///
/// Author.annotated(with: -Author.books.count)
public prefix func - <RowDecoder>(aggregate: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
AssociationAggregate { request in
let (request, expression) = aggregate.prepare(request)
return (request: request, expression:-expression)
}
aggregate.map { -$0 }
}
/// Returns an aggregate that sums two aggregates with the `+` SQL operator.
@@ -669,11 +748,7 @@ public func + <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression + rExpression)
}
combine(lhs, rhs, with: +)
}
/// Returns an aggregate that sums an aggregate with the `+` SQL operator.
@@ -686,10 +761,7 @@ public func + <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression + rhs)
}
lhs.map { $0 + rhs }
}
/// Returns an aggregate that sums an aggregate with the `+` SQL operator.
@@ -702,10 +774,7 @@ public func + <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs + expression)
}
rhs.map { lhs + $0 }
}
/// Returns an aggregate that substracts two aggregates with the `-` SQL operator.
@@ -718,11 +787,7 @@ public func - <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression - rExpression)
}
combine(lhs, rhs, with: -)
}
/// Returns an aggregate that substracts an aggregate with the `-` SQL operator.
@@ -735,10 +800,7 @@ public func - <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression - rhs)
}
lhs.map { $0 - rhs }
}
/// Returns an aggregate that substracts an aggregate with the `-` SQL operator.
@@ -751,10 +813,7 @@ public func - <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs - expression)
}
rhs.map { lhs - $0 }
}
/// Returns an aggregate that multiplies two aggregates with the `*` SQL operator.
@@ -767,11 +826,7 @@ public func * <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression * rExpression)
}
combine(lhs, rhs, with: *)
}
/// Returns an aggregate that substracts an aggregate with the `*` SQL operator.
@@ -784,10 +839,7 @@ public func * <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression * rhs)
}
lhs.map { $0 * rhs }
}
/// Returns an aggregate that substracts an aggregate with the `*` SQL operator.
@@ -800,10 +852,7 @@ public func * <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs * expression)
}
rhs.map { lhs * $0 }
}
/// Returns an aggregate that multiplies two aggregates with the `/` SQL operator.
@@ -816,11 +865,7 @@ public func / <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression / rExpression)
}
combine(lhs, rhs, with: /)
}
/// Returns an aggregate that substracts an aggregate with the `/` SQL operator.
@@ -833,10 +878,7 @@ public func / <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression / rhs)
}
lhs.map { $0 / rhs }
}
/// Returns an aggregate that substracts an aggregate with the `/` SQL operator.
@@ -849,10 +891,7 @@ public func / <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs / expression)
}
rhs.map { lhs / $0 }
}
// MARK: - IFNULL(...)
@@ -865,14 +904,8 @@ public func ?? <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
var aggregate = AssociationAggregate<RowDecoder> { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression ?? rhs)
}
// Preserve key
aggregate.key = lhs.key
return aggregate
lhs.map { $0 ?? rhs }.with(\.key, lhs.key)
}
// TODO: add support for ABS(aggregate)
@@ -96,7 +96,7 @@ public struct BelongsToAssociation<Origin: TableRecord, Destination: TableRecord
sqlAssociation = SQLAssociation(
key: associationKey,
condition: condition,
relation: Destination.all().relation,
relation: Destination.relationForAll,
cardinality: .toOne)
}
}
@@ -96,7 +96,7 @@ public struct HasManyAssociation<Origin: TableRecord, Destination: TableRecord>:
sqlAssociation = SQLAssociation(
key: associationKey,
condition: condition,
relation: Destination.all().relation,
relation: Destination.relationForAll,
cardinality: .toMany)
}
}
@@ -98,7 +98,7 @@ public struct HasOneAssociation<Origin: TableRecord, Destination: TableRecord>:
sqlAssociation = SQLAssociation(
key: associationKey,
condition: condition,
relation: Destination.all().relation,
relation: Destination.relationForAll,
cardinality: .toOne)
}
}
@@ -3,17 +3,18 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
// MARK: - Association Aggregates
private func annotated(with aggregate: AssociationAggregate<RowDecoder>) -> QueryInterfaceRequest {
let (request, expression) = aggregate.prepare(self)
var request = self
let expressionPromise = aggregate.prepare(&request)
if let key = aggregate.key {
return request.annotated(with: [expression.forKey(key)])
return request.annotated(with: { db in try [expressionPromise.resolve(db).forKey(key)] })
} else {
return request.annotated(with: [expression])
return request.annotated(with: { db in try [expressionPromise.resolve(db)] })
}
}
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.all()
/// request = request.annotated(with: Player.books.count)
@@ -23,7 +24,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.all()
/// request = request.annotated(with: [Player.books.count])
@@ -38,11 +39,12 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
///
/// // SELECT player.*
/// // FROM player LEFT JOIN book ...
/// // HAVING COUNT(DISTINCT book.rowid) = 0
/// // HAVING COUNT(DISTINCT book.id) = 0
/// var request = Player.all()
/// request = request.having(Player.books.isEmpty)
public func having(_ predicate: AssociationAggregate<RowDecoder>) -> QueryInterfaceRequest {
let (request, expression) = predicate.prepare(self)
return request.having(expression)
var request = self
let expressionPromise = predicate.prepare(&request)
return request.having(expressionPromise.resolve)
}
}
@@ -5,13 +5,13 @@
//
// It wraps an SQLQuery, and has an attached type.
//
// The attached type helps decoding raw database values:
// The attached RowDecoder type helps decoding raw database values:
//
// try dbQueue.read { db in
// try playerRequest.fetchAll(db) // [Player]
// }
//
// The attached type also helps the compiler validate associated requests:
// RowDecoder also helps the compiler validate associated requests:
//
// playerRequest.including(required: Player.team) // OK
// fruitRequest.including(required: Player.team) // Does not compile
@@ -28,7 +28,7 @@
/// }
///
/// See https://github.com/groue/GRDB.swift#the-query-interface
public struct QueryInterfaceRequest<T> {
public struct QueryInterfaceRequest<RowDecoder> {
var query: SQLQuery
}
@@ -38,98 +38,67 @@ extension QueryInterfaceRequest {
}
}
extension QueryInterfaceRequest: FetchRequest {
public typealias RowDecoder = T
/// Returns a tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
/// - parameter singleResult: A hint as to whether the query should be optimized for a single result.
/// - returns: A prepared statement and an eventual row adapter.
/// :nodoc:
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
var query = self.query
// Optimize query by setting a limit of 1 when appropriate
if singleResult && !query.expectsSingleResult {
query.limit = SQLLimit(limit: 1, offset: query.limit?.offset)
}
let (statement, adapter) = try SQLQueryGenerator(query).prepare(db)
let associations = query.relation.prefetchedAssociations
if associations.isEmpty {
return PreparedRequest(statement: statement, adapter: adapter)
} else {
// Eager loading of prefetched associations
return PreparedRequest(
statement: statement,
adapter: adapter,
supplementaryFetch: { rows in
try prefetch(db, associations: associations, in: rows)
})
}
}
/// Returns the number of rows fetched by the request.
///
/// - parameter db: A database connection.
/// :nodoc:
public func fetchCount(_ db: Database) throws -> Int {
try query.fetchCount(db)
}
/// Returns the database region that the request looks into.
///
/// - parameter db: A database connection.
/// :nodoc:
extension QueryInterfaceRequest: Refinable { }
// MARK: - DatabaseRegionConvertible
extension QueryInterfaceRequest: DatabaseRegionConvertible {
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
var region = try SQLQueryGenerator(query).makeSelectStatement(db).selectedRegion
// Iterate all prefetched associations
var fifo = query.relation.prefetchedAssociations
while !fifo.isEmpty {
let association = fifo.removeFirst()
// Build the query for prefetched rows.
// CAUTION: Keep this code in sync with prefetch(_:associations:in:)
let pivotMappings = try association.pivot.condition.columnMappings(db)
let pivotColumns = pivotMappings.map(\.right)
let pivotAlias = TableAlias()
let prefetchedRelation = association
.map(\.pivot.relation, { $0.qualified(with: pivotAlias) })
.destinationRelation(fromOriginRows: { _ in [] /* no origin row */ })
.annotated(with: pivotColumns.map { pivotAlias[Column($0)].forKey("grdb_\($0)") })
let prefetchedQuery = SQLQuery(relation: prefetchedRelation)
// Union region
try region.formUnion(SQLQueryGenerator(prefetchedQuery).makeSelectStatement(db).selectedRegion)
// Append nested prefetched associations (support for
// A.including(all: A.bs.including(all: B.cs))
fifo.append(contentsOf: prefetchedRelation.prefetchedAssociations)
}
return region
try SQLQueryGenerator(query: query)
.makeSelectStatement(db)
.databaseRegion
}
}
extension QueryInterfaceRequest: SelectionRequest {
// MARK: Request Derivation
// MARK: - SQLRequestProtocol
extension QueryInterfaceRequest: SQLRequestProtocol {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
let generator = SQLQueryGenerator(query: query, forSingleResult: singleResult)
return try generator.requestSQL(context)
}
}
// MARK: - FetchRequest
extension QueryInterfaceRequest: FetchRequest {
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
let generator = SQLQueryGenerator(query: query, forSingleResult: singleResult)
let preparedRequest = try generator.makePreparedRequest(db)
let associations = query.relation.prefetchedAssociations
if associations.isEmpty {
return preparedRequest
} else {
// Eager loading of prefetched associations
return preparedRequest.with(\.supplementaryFetch) { rows in
try prefetch(db, associations: associations, in: rows)
}
}
}
/// Creates a request which selects *selection*.
public func fetchCount(_ db: Database) throws -> Int {
try query.fetchCount(db)
}
}
// MARK: - Request Derivation
extension QueryInterfaceRequest: SelectionRequest {
/// Creates a request which selects *selection promise*.
///
/// // SELECT id, email FROM player
/// var request = Player.all()
/// request = request.select([Column("id"), Column("email")])
/// request = request.select { db in [Column("id"), Column("email")] }
///
/// Any previous selection is replaced:
///
/// // SELECT email FROM player
/// request
/// .select([Column("id")])
/// .select([Column("email")])
public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest {
/// .select { db in [Column("id")] }
/// .select { db in [Column("email")] }
public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest {
map(\.query) { $0.select(selection) }
}
@@ -213,21 +182,43 @@ extension QueryInterfaceRequest: SelectionRequest {
select(sqlLiteral.sqlSelectable, as: type)
}
/// Creates a request which appends *selection*.
/// Creates a request which appends *selection promise*.
///
/// // SELECT id, email, name FROM player
/// var request = Player.all()
/// request = request
/// .select([Column("id"), Column("email")])
/// .annotated(with: [Column("name")])
public func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest {
/// .annotated(with: { db in [Column("name")] })
public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest {
map(\.query) { $0.annotated(with: selection) }
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Creates a request which selects the primary key of the table.
///
/// For example:
///
/// struct Player: TableRecord { ... }
///
/// let playerIds = dbQueue.read { db in
/// try Player.all().selectPrimaryKey(as: Int64.self).fetchAll(db)
/// }
///
/// For tables that have no explicit primary key, the request selects the
/// `rowid` column.
///
/// For tables whose primary key spans several columns, the current
/// implementation also returns a request that selects the `rowid` column.
/// Future GRDB versions may return a [row value](https://www.sqlite.org/rowvalue.html).
public func selectPrimaryKey<RowDecoder>(as type: RowDecoder.Type = RowDecoder.self)
-> QueryInterfaceRequest<RowDecoder>
{
select(SQLPrimaryKeyExpression(tableName: databaseTableName), as: RowDecoder.self)
}
}
extension QueryInterfaceRequest: FilteredRequest {
// MARK: Request Derivation
/// Creates a request with the provided *predicate promise* added to the
/// eventual set of already applied predicates.
///
@@ -240,8 +231,6 @@ extension QueryInterfaceRequest: FilteredRequest {
}
extension QueryInterfaceRequest: OrderedRequest {
// MARK: Request Derivation
/// Creates a request with the provided *orderings promise*.
///
/// // SELECT * FROM player ORDER BY name
@@ -285,16 +274,14 @@ extension QueryInterfaceRequest: OrderedRequest {
}
extension QueryInterfaceRequest: AggregatingRequest {
// MARK: Request Derivation
/// Creates a request grouped according to *expressions promise*.
public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceRequest {
map(\.query) { $0.group(expressions) }
}
/// Creates a request with the provided *predicate* added to the
/// Creates a request with the provided *predicate promise* added to the
/// eventual set of already applied predicates.
public func having(_ predicate: SQLExpressible) -> QueryInterfaceRequest {
public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest {
map(\.query) { $0.having(predicate) }
}
}
@@ -326,46 +313,32 @@ extension QueryInterfaceRequest: _JoinableRequest {
}
}
extension QueryInterfaceRequest: JoinableRequest where T: TableRecord { }
extension QueryInterfaceRequest: JoinableRequest where RowDecoder: TableRecord { }
extension QueryInterfaceRequest: Refinable {
// MARK: Request Derivation
/// Creates a request which returns distinct rows.
///
/// // SELECT DISTINCT * FROM player
/// var request = Player.all()
/// request = request.distinct()
///
/// // SELECT DISTINCT name FROM player
/// var request = Player.select(Column("name"))
/// request = request.distinct()
public func distinct() -> QueryInterfaceRequest {
map(\.query) { $0.distinct() }
}
/// Creates a request which expects a single result.
///
/// It is unlikely you need to call this method. Its net effect is that
/// QueryInterfaceRequest does not use any `LIMIT 1` sql clause when you
/// call a `fetchOne` method.
///
extension QueryInterfaceRequest: TableRequest {
/// :nodoc:
public func expectingSingleResult() -> QueryInterfaceRequest {
map(\.query) { $0.expectingSingleResult() }
}
/// Creates a request which fetches *limit* rows, starting at *offset*.
///
/// // SELECT * FROM player LIMIT 1
/// var request = Player.all()
/// request = request.limit(1)
///
/// Any previous limit is replaced.
public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest {
map(\.query) { $0.limit(limit, offset: offset) }
public var databaseTableName: String {
switch query.relation.source {
case .table(tableName: let tableName, alias: _):
// Use case:
//
// let request = Player.all()
// request.filter(key: ...)
// request.filter(keys: ...)
// request.orderByPrimaryKey()
return tableName
case .subquery:
// The only current use case for SQLSource.query is the
// "trivial count query" (see SQLQuery.countQuery):
//
// // SELECT COUNT(*) FROM (SELECT * FROM player LIMIT 10)
// let request = Player.limit(10)
// let count = try request.fetchCount(db)
//
// This query is currently never wrapped in a QueryInterfaceRequest
// So this fatal error can not currently happen.
fatalError("Request is not based on a database table")
}
}
/// Creates a request that allows you to define expressions that target
@@ -388,10 +361,38 @@ extension QueryInterfaceRequest: Refinable {
public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest {
map(\.query) { $0.qualified(with: alias) }
}
/// Creates a request bound to type Target.
}
extension QueryInterfaceRequest: DerivableRequest where RowDecoder: TableRecord { }
extension QueryInterfaceRequest {
/// Creates a request which returns distinct rows.
///
/// The returned request can fetch if the type Target is fetchable (Row,
/// // SELECT DISTINCT * FROM player
/// var request = Player.all()
/// request = request.distinct()
///
/// // SELECT DISTINCT name FROM player
/// var request = Player.select(Column("name"))
/// request = request.distinct()
public func distinct() -> QueryInterfaceRequest {
map(\.query) { $0.distinct() }
}
/// Creates a request which fetches *limit* rows, starting at *offset*.
///
/// // SELECT * FROM player LIMIT 1
/// var request = Player.all()
/// request = request.limit(1)
///
/// Any previous limit is replaced.
public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest {
map(\.query) { $0.limit(limit, offset: offset) }
}
/// Creates a request bound to type RowDecoder.
///
/// The returned request can fetch if the type RowDecoder is fetchable (Row,
/// value, record).
///
/// // Int?
@@ -400,68 +401,16 @@ extension QueryInterfaceRequest: Refinable {
/// .asRequest(of: Int.self) // <--
/// .fetchOne(db)
///
/// - parameter type: The fetched type Target
/// - returns: A typed request bound to type Target.
/// - parameter type: The fetched type RowDecoder
/// - returns: A request bound to type RowDecoder.
public func asRequest<RowDecoder>(of type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
QueryInterfaceRequest<RowDecoder>(query: query)
}
}
extension QueryInterfaceRequest {
/// Turns a request into a SQLRelation.
///
/// This method helps initializing associations:
///
/// struct Book: TableRecord {
/// // invokes Author.all().relation
/// static let author = belongsTo(Author.self)
/// }
var relation: SQLRelation {
let query = self.query
// Prevent information loss
GRDBPrecondition(!query.isDistinct, "Not implemented: join distinct queries")
GRDBPrecondition(query.groupPromise == nil, "Can't join aggregated queries")
GRDBPrecondition(query.havingExpressions.isEmpty, "Can't join aggregated queries")
GRDBPrecondition(query.limit == nil, "Can't join limited queries")
return query.relation
}
}
// MARK: - Batch Delete
extension QueryInterfaceRequest: TableRequest {
/// :nodoc:
public var databaseTableName: String {
switch query.relation.source {
case .table(tableName: let tableName, alias: _):
// Use case:
//
// let request = Player.all()
// request.filter(key: ...)
// request.filter(keys: ...)
// request.orderByPrimaryKey()
return tableName
case .query:
// The only current use case for SQLSource.query is the
// "trivial count query" (see SQLQuery.countQuery):
//
// // SELECT COUNT(*) FROM (SELECT * FROM player LIMIT 10)
// let request = Player.limit(10)
// let count = try request.fetchCount(db)
//
// This query is currently never wrapped in a QueryInterfaceRequest
// So this fatal error can not currently happen.
fatalError("Request is not based on a database table")
}
}
}
extension QueryInterfaceRequest: DerivableRequest where T: TableRecord { }
extension QueryInterfaceRequest where T: MutablePersistableRecord {
// MARK: Batch Delete
extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
/// Deletes matching rows; returns the number of deleted rows.
///
/// - parameter db: A database connection.
@@ -469,12 +418,14 @@ extension QueryInterfaceRequest where T: MutablePersistableRecord {
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@discardableResult
public func deleteAll(_ db: Database) throws -> Int {
try SQLQueryGenerator(query).makeDeleteStatement(db).execute()
try SQLQueryGenerator(query: query).makeDeleteStatement(db).execute()
return db.changesCount
}
// MARK: Batch Update
}
// MARK: - Batch Update
extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
/// Updates matching rows; returns the number of updated rows.
///
/// For example:
@@ -497,7 +448,7 @@ extension QueryInterfaceRequest where T: MutablePersistableRecord {
_ assignments: [ColumnAssignment]) throws -> Int
{
let conflictResolution = conflictResolution ?? RowDecoder.persistenceConflictPolicy.conflictResolutionForUpdate
guard let updateStatement = try SQLQueryGenerator(query).makeUpdateStatement(
guard let updateStatement = try SQLQueryGenerator(query: query).makeUpdateStatement(
db,
conflictResolution: conflictResolution,
assignments: assignments) else
@@ -546,7 +497,7 @@ private func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [
return
}
// CAUTION: Keep this code in sync with QueryInterfaceRequest.databaseRegion(_:)
// CAUTION: Keep this code in sync with prefetchedRegion(_:_:)
for association in associations {
let pivotMappings = try association.pivot.condition.columnMappings(db)
@@ -585,7 +536,7 @@ private func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [
// TODO: can we remove those grdb_ columns now that grouping has been done?
}
let groupingIndexes = firstRow.indexes(ofColumns: pivotMappings.map(\.left))
let groupingIndexes = firstRow.indexes(forColumns: pivotMappings.map(\.left))
for row in rows {
let groupingKey = groupingIndexes.map { row.impl.databaseValue(atUncheckedIndex: $0) }
let prefetchedRows = prefetchedRows[groupingKey, default: []]
@@ -594,6 +545,32 @@ private func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [
}
}
// Returns the region of prefetched associations
func prefetchedRegion(_ db: Database, associations: [SQLAssociation]) throws -> DatabaseRegion {
try associations.reduce(into: DatabaseRegion()) { (region, association) in
// CAUTION: Keep this code in sync with prefetch(_:associations:in:)
let pivotMappings = try association.pivot.condition.columnMappings(db)
let pivotColumns = pivotMappings.map(\.right)
let pivotAlias = TableAlias()
let prefetchedRelation = association
.map(\.pivot.relation, { $0.qualified(with: pivotAlias) })
// Use a `NullRow` in order to make sure all join condition
// columns are made visible to SQLite, and present in the
// selected region:
// ... JOIN right ON right.leftId IS NULL
// ^ content of the NullRow
.destinationRelation(fromOriginRows: { _ in [NullRow()] })
.annotated(with: pivotColumns.map { pivotAlias[Column($0)].forKey("grdb_\($0)") })
let prefetchedQuery = SQLQuery(relation: prefetchedRelation)
// Union prefetched region
let prefetchedRegion = try SQLQueryGenerator(query: prefetchedQuery)
.makeSelectStatement(db)
.databaseRegion // contains region of nested associations
region.formUnion(prefetchedRegion)
}
}
extension Array where Element == Row {
/// - precondition: Columns all exist in all rows. All rows have the same
/// columnns, in the same order.
@@ -601,7 +578,7 @@ extension Array where Element == Row {
guard let firstRow = first else {
return [:]
}
let indexes = firstRow.indexes(ofColumns: columns)
let indexes = firstRow.indexes(forColumns: columns)
return Dictionary(grouping: self, by: { row in
indexes.map { row.impl.databaseValue(atUncheckedIndex: $0) }
})
@@ -610,9 +587,9 @@ extension Array where Element == Row {
extension Row {
/// - precondition: Columns all exist in the row.
fileprivate func indexes(ofColumns columns: [String]) -> [Int] {
fileprivate func indexes(forColumns columns: [String]) -> [Int] {
columns.map { column -> Int in
guard let index = index(ofColumn: column) else {
guard let index = index(forColumn: column) else {
fatalError("Column \(column) is not selected")
}
return index
@@ -636,10 +613,10 @@ public struct ColumnAssignment {
var column: ColumnExpression
var value: SQLExpressible
func sql(_ context: inout SQLGenerationContext) -> String {
column.expressionSQL(&context, wrappedInParenthesis: false) +
func sql(_ context: SQLGenerationContext) throws -> String {
try column.expressionSQL(context, wrappedInParenthesis: false) +
" = " +
value.sqlExpression.expressionSQL(&context, wrappedInParenthesis: false)
value.sqlExpression.expressionSQL(context, wrappedInParenthesis: false)
}
}
@@ -6,6 +6,32 @@
///
/// :nodoc:
public protocol SelectionRequest {
/// Creates a request which selects *selection promise*.
///
/// // SELECT id, email FROM player
/// var request = Player.all()
/// request = request.select { db in [Column("id"), Column("email") })
///
/// Any previous selection is replaced:
///
/// // SELECT email FROM player
/// request
/// .select { db in [Column("id")] }
/// .select { db in [Column("email")] }
func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self
/// Creates a request which appends *selection promise*.
///
/// // SELECT id, email, name FROM player
/// var request = Player.all()
/// request = request
/// .select([Column("id"), Column("email")])
/// .annotated(with: { db in [Column("name")] })
func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self
}
/// :nodoc:
extension SelectionRequest {
/// Creates a request which selects *selection*.
///
/// // SELECT id, email FROM player
@@ -18,20 +44,10 @@ public protocol SelectionRequest {
/// request
/// .select([Column("id")])
/// .select([Column("email")])
func select(_ selection: [SQLSelectable]) -> Self
public func select(_ selection: [SQLSelectable]) -> Self {
select { _ in selection }
}
/// Creates a request which appends *selection*.
///
/// // SELECT id, email, name FROM player
/// var request = Player.all()
/// request = request
/// .select([Column("id"), Column("email")])
/// .annotated(with: [Column("name")])
func annotated(with selection: [SQLSelectable]) -> Self
}
/// :nodoc:
extension SelectionRequest {
/// Creates a request which selects *selection*.
///
/// // SELECT id, email FROM player
@@ -91,7 +107,18 @@ extension SelectionRequest {
/// .select(literal: SQLLiteral(sql: "email"))
public func select(literal sqlLiteral: SQLLiteral) -> Self {
// NOT TESTED
return select(sqlLiteral.sqlSelectable)
select(sqlLiteral.sqlSelectable)
}
/// Creates a request which appends *selection*.
///
/// // SELECT id, email, name FROM player
/// var request = Player.all()
/// request = request
/// .select([Column("id"), Column("email")])
/// .annotated(with: [Column("name")])
public func annotated(with selection: [SQLSelectable]) -> Self {
annotated(with: { _ in selection })
}
/// Creates a request which appends *selection*.
@@ -121,23 +148,10 @@ public protocol FilteredRequest {
/// var request = Player.all()
/// request = request.filter { db in true }
func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self
/// Creates a request which expects a single result.
///
/// Requests expecting a single result may ignore the second parameter of
/// the `FetchRequest.prepare(_:forSingleResult:)` method, in order to
/// produce sharply tailored SQL.
///
/// This method has a default implementation which returns self.
func expectingSingleResult() -> Self
}
/// :nodoc:
extension FilteredRequest {
public func expectingSingleResult() -> Self {
self
}
/// Creates a request with the provided *predicate* added to the
/// eventual set of already applied predicates.
///
@@ -174,7 +188,7 @@ extension FilteredRequest {
/// request = request.filter(literal: "name = \("O'Brien")")
public func filter(literal sqlLiteral: SQLLiteral) -> Self {
// NOT TESTED
return filter(sqlLiteral.sqlExpression)
filter(sqlLiteral.sqlExpression)
}
/// Creates a request that matches nothing.
@@ -234,19 +248,13 @@ extension TableRequest where Self: FilteredRequest {
-> Self
where Sequence.Element: DatabaseValueConvertible
{
var request = self
let keys = Array(keys)
switch keys.count {
case 0:
if keys.isEmpty {
return none()
case 1:
request = request.expectingSingleResult()
default:
break
}
let databaseTableName = self.databaseTableName
return request.filter { db in
return filter { db in
let primaryKey = try db.primaryKey(databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
@@ -271,18 +279,12 @@ extension TableRequest where Self: FilteredRequest {
/// When executed, this request raises a fatal error if there is no unique
/// index on the key columns.
public func filter(keys: [[String: DatabaseValueConvertible?]]) -> Self {
var request = self
switch keys.count {
case 0:
if keys.isEmpty {
return none()
case 1:
request = request.expectingSingleResult()
default:
break
}
let databaseTableName = self.databaseTableName
return request.filter { db in
return filter { db in
try keys
.map { key in
// Prevent filter(keys: [["foo": 1, "bar": 2]]) where
@@ -344,9 +346,9 @@ public protocol AggregatingRequest {
/// Creates a request grouped according to *expressions promise*.
func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self
/// Creates a request with the provided *predicate* added to the
/// Creates a request with the provided *predicate promise* added to the
/// eventual set of already applied predicates.
func having(_ predicate: SQLExpressible) -> Self
func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self
}
/// :nodoc:
@@ -369,7 +371,13 @@ extension AggregatingRequest {
/// Creates a request with a new grouping.
public func group(literal sqlLiteral: SQLLiteral) -> Self {
// NOT TESTED
return group(sqlLiteral.sqlExpression)
group(sqlLiteral.sqlExpression)
}
/// Creates a request with the provided *predicate* added to the
/// eventual set of already applied predicates.
public func having(_ predicate: SQLExpressible) -> Self {
having { _ in predicate }
}
/// Creates a request with the provided *sql* added to the
@@ -382,7 +390,7 @@ extension AggregatingRequest {
/// eventual set of already applied predicates.
public func having(literal sqlLiteral: SQLLiteral) -> Self {
// NOT TESTED
return having(sqlLiteral.sqlExpression)
having(sqlLiteral.sqlExpression)
}
}
@@ -496,7 +504,7 @@ extension OrderedRequest {
/// .order(sql: "name")
public func order(literal sqlLiteral: SQLLiteral) -> Self {
// NOT TESTED
return order(sqlLiteral.sqlOrderingTerm)
order(sqlLiteral.sqlOrderingTerm)
}
}
+3 -3
View File
@@ -27,7 +27,7 @@ public protocol ColumnExpression: SQLExpression {
extension ColumnExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
name.quotedDatabaseIdentifier
}
@@ -73,7 +73,7 @@ struct QualifiedColumn: ColumnExpression {
self.alias = alias
}
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
if let qualifier = context.qualifier(for: alias) {
return qualifier.quotedDatabaseIdentifier + "." + name.quotedDatabaseIdentifier
}
@@ -82,7 +82,7 @@ struct QualifiedColumn: ColumnExpression {
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
// Never requalify
return self
self
}
}
@@ -41,10 +41,4 @@ struct DatabasePromise<T> {
try transform(self.resolve(db))
}
}
func flatMap<U>(_ transform: @escaping (T) -> DatabasePromise<U>) -> DatabasePromise<U> {
DatabasePromise<U> { db in
try transform(self.resolve(db)).resolve(db)
}
}
}
+28 -15
View File
@@ -135,16 +135,16 @@ public /* TODO: internal */ struct SQLAssociation {
/// HasMany in the above examples, but also for indirect associations such
/// as HasManyThrough, which have any number of pivot relations between the
/// origin and the destination.
func destinationRelation(fromOriginRows originRows: @escaping (Database) throws -> [Row]) -> SQLRelation {
// Filter the pivot
func destinationRelation<Row>(
fromOriginRows originRows: @escaping (Database) throws -> [Row])
-> SQLRelation
where Row: ColumnAddressable
{
// Filter the pivot: `pivot.originId = 123` or `pivot.originId IN (1, 2, 3)`
let pivot = self.pivot
let pivotAlias = TableAlias()
let filteredPivotRelation = pivot.relation
.qualified(with: pivotAlias)
.filter({ db in
// `pivot.originId = 123` or `pivot.originId IN (1, 2, 3)`
try pivot.condition.filteringExpression(db, leftRows: originRows(db), rightAlias: pivotAlias)
})
let filteredPivotRelation = pivot.relation.filter { db in
try pivot.condition.filteringExpression(db, leftRows: originRows(db))
}
if steps.count == 1 {
// This is a direct join from origin to destination, without
@@ -178,7 +178,12 @@ public /* TODO: internal */ struct SQLAssociation {
// children are useless:
let relation = step.relation
.selectOnly([])
.filteringChildren { $0.kind.cardinality == .toOne }
.filteringChildren({
switch $0.kind {
case .allPrefetched, .allNotPrefetched: return false
case .oneRequired, .oneOptional: return true
}
})
// Don't interfere with user-defined keys that could be added later
let key = step.key.map(\.baseName) { "grdb_\($0)" }
@@ -203,7 +208,16 @@ struct SQLAssociationStep: Refinable {
var relation: SQLRelation
var cardinality: SQLAssociationCardinality
var keyName: String { key.name(for: cardinality) }
var isSingular: Bool {
switch cardinality {
case .toOne:
return true
case .toMany:
return false
}
}
var keyName: String { key.name(singular: isSingular) }
}
enum SQLAssociationCardinality {
@@ -319,11 +333,10 @@ enum SQLAssociationKey: Refinable {
}
}
func name(for cardinality: SQLAssociationCardinality) -> String {
switch cardinality {
case .toOne:
func name(singular: Bool) -> String {
if singular {
return singularizedName
case .toMany:
} else {
return pluralizedName
}
}
@@ -87,8 +87,8 @@ extension SQLCollatedExpression: SQLOrderingTerm {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func orderingTermSQL(_ context: inout SQLGenerationContext) -> String {
sqlExpression.orderingTermSQL(&context)
public func orderingTermSQL(_ context: SQLGenerationContext) throws -> String {
try sqlExpression.orderingTermSQL(context)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
+11 -8
View File
@@ -9,13 +9,16 @@ public protocol SQLCollection {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns an SQL string that represents the collection.
func collectionSQL(_ context: inout SQLGenerationContext) -> String
func collectionSQL(_ context: SQLGenerationContext) throws -> String
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns an expression that check whether the collection contains
/// the expression.
func contains(_ value: SQLExpressible) -> SQLExpression
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
func qualifiedCollection(with alias: TableAlias) -> SQLCollection
}
@@ -40,13 +43,9 @@ extension SQLCollection {
struct SQLExpressionsArray: SQLCollection {
let expressions: [SQLExpression]
init<S: Sequence>(_ expressions: S) where S.Iterator.Element: SQLExpressible {
self.expressions = expressions.map(\.sqlExpression)
}
func collectionSQL(_ context: inout SQLGenerationContext) -> String {
expressions
.map { $0.expressionSQL(&context, wrappedInParenthesis: false) }
func collectionSQL(_ context: SQLGenerationContext) throws -> String {
try expressions
.map { try $0.expressionSQL(context, wrappedInParenthesis: false) }
.joined(separator: ", ")
}
@@ -62,4 +61,8 @@ struct SQLExpressionsArray: SQLCollection {
// ["foo", "bar"].contains(Column("name")) => name IN ('foo', 'bar')
return SQLExpressionContains(value, self)
}
func qualifiedCollection(with alias: TableAlias) -> SQLCollection {
SQLExpressionsArray(expressions: expressions.map { $0.qualifiedExpression(with: alias) })
}
}
+6 -6
View File
@@ -64,8 +64,8 @@ extension SQLExpressible where Self: SQLOrderingTerm {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func orderingTermSQL(_ context: inout SQLGenerationContext) -> String {
sqlExpression.expressionSQL(&context, wrappedInParenthesis: false)
public func orderingTermSQL(_ context: SQLGenerationContext) throws -> String {
try sqlExpression.expressionSQL(context, wrappedInParenthesis: false)
}
}
@@ -75,14 +75,14 @@ extension SQLExpressible where Self: SQLSelectable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
sqlExpression.expressionSQL(&context, wrappedInParenthesis: false)
public func resultColumnSQL(_ context: SQLGenerationContext) throws -> String {
try sqlExpression.expressionSQL(context, wrappedInParenthesis: false)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func countedSQL(_ context: inout SQLGenerationContext) -> String {
sqlExpression.expressionSQL(&context, wrappedInParenthesis: false)
public func countedSQL(_ context: SQLGenerationContext) throws -> String {
try sqlExpression.expressionSQL(context, wrappedInParenthesis: false)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
@@ -3,10 +3,10 @@
extension SQLExpression {
/// The expression as a quoted SQL literal (not public in order to avoid abuses)
///
/// "foo'bar".databaseValue.quotedSQL() // "'foo''bar'""
func quotedSQL() -> String {
var context = SQLGenerationContext.rawSQLContext
return expressionSQL(&context, wrappedInParenthesis: false)
/// try "foo'bar".databaseValue.quotedSQL(db) // "'foo''bar'""
func quotedSQL(_ db: Database) throws -> String {
let context = SQLGenerationContext(db, argumentsSink: .forRawSQL)
return try expressionSQL(context, wrappedInParenthesis: false)
}
}
@@ -70,11 +70,13 @@ public struct SQLExpressionUnary: SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
if wrappedInParenthesis {
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
}
return op.sql + (op.needsRightSpace ? " " : "") + expression.expressionSQL(&context, wrappedInParenthesis: true)
return try op.sql
+ (op.needsRightSpace ? " " : "")
+ expression.expressionSQL(context, wrappedInParenthesis: true)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
@@ -166,14 +168,14 @@ public struct SQLExpressionBinary: SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
if wrappedInParenthesis {
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
}
return """
\(lhs.expressionSQL(&context, wrappedInParenthesis: true)) \
return try """
\(lhs.expressionSQL(context, wrappedInParenthesis: true)) \
\(op.sql) \
\(rhs.expressionSQL(&context, wrappedInParenthesis: true))
\(rhs.expressionSQL(context, wrappedInParenthesis: true))
"""
}
@@ -263,14 +265,14 @@ struct SQLExpressionBinaryReduce: SQLExpression {
}
}
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
guard let first = expressions.first else {
return op.neutralValue.sqlExpression.expressionSQL(&context, wrappedInParenthesis: false)
return try op.neutralValue.expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis)
}
if expressions.count == 1 {
return first.expressionSQL(&context, wrappedInParenthesis: wrappedInParenthesis)
return try first.expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis)
}
let expressionSQLs = expressions.map { $0.expressionSQL(&context, wrappedInParenthesis: true) }
let expressionSQLs = try expressions.map { try $0.expressionSQL(context, wrappedInParenthesis: true) }
let joiner = " \(op.sql) "
if wrappedInParenthesis {
return "(\(expressionSQLs.joined(separator: joiner)))"
@@ -309,6 +311,22 @@ struct SQLExpressionBinaryReduce: SQLExpression {
return nil
}
}
var truthComponents: [SQLExpression] {
guard let first = expressions.first else {
return op.neutralValue.truthComponents
}
if expressions.count == 1 {
return first.truthComponents
}
if op == .and {
return expressions.flatMap(\.truthComponents)
}
return [self]
}
}
extension Sequence where Element == SQLExpression {
@@ -376,14 +394,14 @@ struct SQLExpressionEqual: SQLExpression {
}
}
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
if wrappedInParenthesis {
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
}
return """
\(lhs.expressionSQL(&context, wrappedInParenthesis: true)) \
return try """
\(lhs.expressionSQL(context, wrappedInParenthesis: true)) \
\(op.rawValue) \
\(rhs.expressionSQL(&context, wrappedInParenthesis: true))
\(rhs.expressionSQL(context, wrappedInParenthesis: true))
"""
}
@@ -447,14 +465,14 @@ struct SQLExpressionContains: SQLExpression {
self.isNegated = negated
}
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
if wrappedInParenthesis {
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
}
return """
\(expression.expressionSQL(&context, wrappedInParenthesis: true)) \
return try """
\(expression.expressionSQL(context, wrappedInParenthesis: true)) \
\(isNegated ? "NOT IN" : "IN") \
(\(collection.collectionSQL(&context)))
(\(collection.collectionSQL(context)))
"""
}
@@ -463,7 +481,10 @@ struct SQLExpressionContains: SQLExpression {
}
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
SQLExpressionContains(expression.qualifiedExpression(with: alias), collection, negated: isNegated)
return SQLExpressionContains(
expression.qualifiedExpression(with: alias),
collection.qualifiedCollection(with: alias),
negated: isNegated)
}
func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
@@ -515,16 +536,16 @@ struct SQLExpressionBetween: SQLExpression {
self.isNegated = negated
}
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
if wrappedInParenthesis {
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
}
return """
\(expression.expressionSQL(&context, wrappedInParenthesis: true)) \
return try """
\(expression.expressionSQL(context, wrappedInParenthesis: true)) \
\(isNegated ? "NOT BETWEEN" : "BETWEEN") \
\(lowerBound.expressionSQL(&context, wrappedInParenthesis: true)) \
\(lowerBound.expressionSQL(context, wrappedInParenthesis: true)) \
AND \
\(upperBound.expressionSQL(&context, wrappedInParenthesis: true))
\(upperBound.expressionSQL(context, wrappedInParenthesis: true))
"""
}
@@ -608,11 +629,11 @@ public struct SQLExpressionFunction: SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
var sql = functionName.sql
sql += "("
sql += arguments
.map { $0.expressionSQL(&context, wrappedInParenthesis: false) }
sql += try arguments
.map { try $0.expressionSQL(context, wrappedInParenthesis: false) }
.joined(separator: ", ")
sql += ")"
return sql
@@ -639,8 +660,8 @@ struct SQLExpressionCount: SQLExpression {
self.counted = counted
}
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
"COUNT(" + counted.countedSQL(&context) + ")"
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
try "COUNT(" + counted.countedSQL(context) + ")"
}
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
@@ -661,8 +682,8 @@ struct SQLExpressionCountDistinct: SQLExpression {
self.counted = counted
}
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
"COUNT(DISTINCT " + counted.expressionSQL(&context, wrappedInParenthesis: false) + ")"
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
try "COUNT(DISTINCT " + counted.expressionSQL(context, wrappedInParenthesis: false) + ")"
}
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
@@ -689,12 +710,12 @@ struct SQLExpressionIsEmpty: SQLExpression {
SQLExpressionIsEmpty(countExpression, isEmpty: !isEmpty)
}
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
if wrappedInParenthesis {
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
}
return """
\(countExpression.expressionSQL(&context, wrappedInParenthesis: true)) \
return try """
\(countExpression.expressionSQL(context, wrappedInParenthesis: true)) \
\(isEmpty ? "= 0" : "> 0")
"""
}
@@ -710,14 +731,14 @@ struct TableMatchExpression: SQLExpression {
var alias: TableAlias
var pattern: SQLExpression
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
if wrappedInParenthesis {
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
}
return """
return try """
\(context.resolvedName(for: alias).quotedDatabaseIdentifier) \
MATCH \
\(pattern.expressionSQL(&context, wrappedInParenthesis: true))
\(pattern.expressionSQL(context, wrappedInParenthesis: true))
"""
}
@@ -743,12 +764,12 @@ struct SQLExpressionCollate: SQLExpression {
self.collationName = collationName
}
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
if wrappedInParenthesis {
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
}
return """
\(expression.expressionSQL(&context, wrappedInParenthesis: false)) \
return try """
\(expression.expressionSQL(context, wrappedInParenthesis: false)) \
COLLATE \
\(collationName.rawValue)
"""
@@ -758,3 +779,68 @@ struct SQLExpressionCollate: SQLExpression {
SQLExpressionCollate(expression.qualifiedExpression(with: alias), collationName: collationName)
}
}
// MARK: - SQLPrimaryKeyExpression
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// SQLPrimaryKeyExpression is the primary key of a table.
///
/// For tables that have no explicit primary key, SQLPrimaryKeyExpression is the
/// `rowid` column.
///
/// For tables whose primary key spans several columns, the current
/// implementation of SQLPrimaryKeyExpression also is the `rowid` column. Future
/// GRDB versions may return a [row value](https://www.sqlite.org/rowvalue.html).
///
/// For example:
///
/// struct Player: TableRecord { ... }
///
/// let player = dbQueue.read { db in
/// try Player.filter(Player.primaryKey == 12).fetchOne(db)
/// }
public struct SQLPrimaryKeyExpression: SQLExpression {
let tableName: String
/// Support for SQLPrimaryKeyExpression and SQLQualifiedPrimaryKeyExpression
fileprivate static func primaryKeyColumn(_ db: Database, tableName: String) throws -> Column {
let columns = try db.primaryKey(tableName).columns
if columns.count == 1 {
return Column(columns[0])
} else {
return Column.rowID
}
}
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
try SQLPrimaryKeyExpression
.primaryKeyColumn(context.db, tableName: tableName)
.expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis)
}
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
SQLQualifiedPrimaryKeyExpression(tableName: tableName, alias: alias)
}
}
struct SQLQualifiedPrimaryKeyExpression: SQLExpression {
let tableName: String
let alias: TableAlias
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
GRDBPrecondition(
tableName.lowercased() == alias.tableName.lowercased(),
"Table names don't match: \(tableName) and \(alias.tableName)")
return try SQLPrimaryKeyExpression
.primaryKeyColumn(context.db, tableName: tableName)
.qualifiedExpression(with: alias)
.expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis)
}
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
// Never requalify
self
}
}
+32 -4
View File
@@ -16,7 +16,7 @@ public protocol SQLExpression: SQLSpecificExpressible, SQLSelectable, SQLOrderin
/// statement arguments.
/// - parameter wrappedInParenthesis: If true, the returned SQL should be
/// wrapped inside parenthesis.
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -41,6 +41,27 @@ public protocol SQLExpression: SQLSpecificExpressible, SQLSelectable, SQLOrderin
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
func qualifiedExpression(with alias: TableAlias) -> SQLExpression
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The elements of the returned array, when joined with the AND operator,
/// are guaranteed to have the same truth value as the receiver.
///
/// Those truth components allow easier introspection of the expression.
/// For example:
///
/// // No change:
/// // [Column("a")]
/// Column("a").truthComponents
///
/// // Erase a SQLExpressionBinaryReduce `and` expression:
/// // [Column("a"), Column("b")]
/// [Column("a"), Column("b")].joined(operator: .and).truthComponents
///
/// // Erase a SQLExpressionBinaryReduce `or` expression:
/// // [Column("a")]
/// [Column("a")].joined(operator: .or).truthComponents
var truthComponents: [SQLExpression] { get }
}
extension SQLExpression {
@@ -83,6 +104,13 @@ extension SQLExpression {
public func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm {
qualifiedExpression(with: alias)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The default implementation returns [self]
///
/// :nodoc:
public var truthComponents: [SQLExpression] { [self] }
}
// SQLExpression: SQLExpressible
@@ -126,11 +154,11 @@ struct SQLExpressionNot: SQLExpression {
self.expression = expression
}
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
if wrappedInParenthesis {
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
}
return "NOT \(expression.expressionSQL(&context, wrappedInParenthesis: true))"
return try "NOT \(expression.expressionSQL(context, wrappedInParenthesis: true))"
}
var negated: SQLExpression {
+108 -4
View File
@@ -144,7 +144,7 @@ public func sum(_ value: SQLSpecificExpressible) -> SQLExpression {
}
// MARK: - Swift String functions
// MARK: - String functions
/// :nodoc:
extension SQLSpecificExpressible {
@@ -187,7 +187,7 @@ extension SQLSpecificExpressible {
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.localizedCapitalized)
/// let names = try String.fetchAll(dbQueue, request) // [String]
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
@available(OSX 10.11, watchOS 3.0, *)
public var localizedCapitalized: SQLExpression {
DatabaseFunction.localizedCapitalize(sqlExpression)
}
@@ -198,7 +198,7 @@ extension SQLSpecificExpressible {
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.localizedLowercased)
/// let names = try String.fetchAll(dbQueue, request) // [String]
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
@available(OSX 10.11, watchOS 3.0, *)
public var localizedLowercased: SQLExpression {
DatabaseFunction.localizedLowercase(sqlExpression)
}
@@ -209,8 +209,112 @@ extension SQLSpecificExpressible {
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.localizedUppercased)
/// let names = try String.fetchAll(dbQueue, request) // [String]
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
@available(OSX 10.11, watchOS 3.0, *)
public var localizedUppercased: SQLExpression {
DatabaseFunction.localizedUppercase(sqlExpression)
}
}
// MARK: - Date functions
/// A date modifier for SQLite date functions.
///
/// For more information, see https://www.sqlite.org/lang_datefunc.html
public enum SQLDateModifier: SQLExpression {
case day(Int)
case hour(Int)
case minute(Int)
case second(Double)
case month(Int)
case year(Int)
case startOfMonth
case startOfYear
case startOfDay
case weekday(Int)
case unixEpoch
case localTime
case utc
var rawValue: String {
switch self {
case let .day(value):
return "\(value) days"
case let .hour(value):
return "\(value) hours"
case let .minute(value):
return "\(value) minutes"
case let .second(value):
return "\(value) seconds"
case let .month(value):
return "\(value) months"
case let .year(value):
return "\(value) years"
case .startOfMonth:
return "start of month"
case .startOfYear:
return "start of year"
case .startOfDay:
return "start of day"
case let .weekday(value):
return "weekday \(value)"
case .unixEpoch:
return "unixepoch"
case .localTime:
return "localtime"
case .utc:
return "utc"
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
try rawValue.databaseValue.expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
self
}
}
// MARK: JULIANDAY(...)
extension SQLFunctionName {
/// The `JULIANDAY` function name
public static let julianDay = SQLFunctionName("JULIANDAY")
}
/// Returns an expression that evaluates the `JULIANDAY` SQL function.
///
/// // JULIANDAY(date)
/// julianDay(Column("date"))
///
/// // JULIANDAY(date, '1 days')
/// julianDay(Column("date"), .day(1))
///
/// For more information, see https://www.sqlite.org/lang_datefunc.html
public func julianDay(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression {
SQLExpressionFunction(.julianDay, arguments: [value.sqlExpression] + modifiers)
}
// MARK: DATETIME(...)
extension SQLFunctionName {
/// The `DATETIME` function name
public static let dateTime = SQLFunctionName("DATETIME")
}
/// Returns an expression that evaluates the `DATETIME` SQL function.
///
/// // DATETIME(date)
/// dateTime(Column("date"))
///
/// // DATETIME(date, '1 days')
/// dateTime(Column("date"), .day(1))
///
/// For more information, see https://www.sqlite.org/lang_datefunc.html
public func dateTime(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression {
SQLExpressionFunction(.dateTime, arguments: [value.sqlExpression] + modifiers)
}
+21 -3
View File
@@ -298,7 +298,6 @@ public func !== (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQ
SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs.sqlExpression)
}
// MARK: - Comparison Operators (<, >, <=, >=)
extension SQLBinaryOperator {
@@ -475,7 +474,6 @@ public func >= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL
SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
}
// MARK: - Inclusion Operators (BETWEEN, IN)
extension Range where Bound: SQLExpressible {
@@ -541,7 +539,27 @@ extension Sequence where Self.Iterator.Element: SQLExpressible {
/// // id IN (1,2,3)
/// [1, 2, 3].contains(Column("id"))
public func contains(_ element: SQLSpecificExpressible) -> SQLExpression {
SQLExpressionsArray(self).contains(element.sqlExpression)
SQLExpressionsArray(expressions: map(\.sqlExpression)).contains(element.sqlExpression)
}
/// An SQL expression that checks the inclusion of an expression in
/// a sequence.
///
/// // name IN ('A', 'B') COLLATE NOCASE
/// ["A", "B"].contains(Column("name").collating(.nocase))
public func contains(_ element: SQLCollatedExpression) -> SQLExpression {
SQLExpressionCollate(contains(element.expression), collationName: element.collationName)
}
}
extension Sequence where Self.Iterator.Element == SQLExpressible {
/// An SQL expression that checks the inclusion of an expression in
/// a sequence.
///
/// // id IN (1,2,3)
/// [1, 2, 3].contains(Column("id"))
public func contains(_ element: SQLSpecificExpressible) -> SQLExpression {
SQLExpressionsArray(expressions: map(\.sqlExpression)).contains(element.sqlExpression)
}
/// An SQL expression that checks the inclusion of an expression in
+6 -6
View File
@@ -15,7 +15,7 @@ public protocol SQLOrderingTerm {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns an SQL string that represents the ordering term.
func orderingTermSQL(_ context: inout SQLGenerationContext) -> String
func orderingTermSQL(_ context: SQLGenerationContext) throws -> String
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm
@@ -46,17 +46,17 @@ enum SQLOrdering: SQLOrderingTerm {
}
}
func orderingTermSQL(_ context: inout SQLGenerationContext) -> String {
func orderingTermSQL(_ context: SQLGenerationContext) throws -> String {
switch self {
case .asc(let expression):
return expression.expressionSQL(&context, wrappedInParenthesis: false) + " ASC"
return try expression.expressionSQL(context, wrappedInParenthesis: false) + " ASC"
case .desc(let expression):
return expression.expressionSQL(&context, wrappedInParenthesis: false) + " DESC"
return try expression.expressionSQL(context, wrappedInParenthesis: false) + " DESC"
#if GRDBCUSTOMSQLITE
case .ascNullsLast(let expression):
return expression.expressionSQL(&context, wrappedInParenthesis: false) + " ASC NULLS LAST"
return try expression.expressionSQL(context, wrappedInParenthesis: false) + " ASC NULLS LAST"
case .descNullsFirst(let expression):
return expression.expressionSQL(&context, wrappedInParenthesis: false) + " DESC NULLS FIRST"
return try expression.expressionSQL(context, wrappedInParenthesis: false) + " DESC NULLS FIRST"
#endif
}
}
+17 -18
View File
@@ -4,12 +4,11 @@
struct SQLQuery {
var relation: SQLRelation
var isDistinct: Bool = false
var expectsSingleResult: Bool = false
var groupPromise: DatabasePromise<[SQLExpression]>?
// Having clause is an array of expressions that we'll join with
// the AND operator. This gives nicer output in generated SQL:
// `(a AND b AND c)` instead of `((a AND b) AND c)`.
var havingExpressions: [SQLExpression] = []
var havingExpressionsPromise: DatabasePromise<[SQLExpression]> = DatabasePromise(value: [])
var limit: SQLLimit?
}
@@ -18,10 +17,6 @@ extension SQLQuery: Refinable {
with(\.isDistinct, true)
}
func expectingSingleResult() -> Self {
with(\.expectsSingleResult, true)
}
func limit(_ limit: Int, offset: Int? = nil) -> Self {
with(\.limit, SQLLimit(limit: limit, offset: offset))
}
@@ -34,11 +29,11 @@ extension SQLQuery: Refinable {
}
extension SQLQuery: SelectionRequest {
func select(_ selection: [SQLSelectable]) -> Self {
func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
map(\.relation) { $0.select(selection) }
}
func annotated(with selection: [SQLSelectable]) -> Self {
func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
map(\.relation) { $0.annotated(with: selection) }
}
}
@@ -68,8 +63,12 @@ extension SQLQuery: AggregatingRequest {
with(\.groupPromise, DatabasePromise { db in try expressions(db).map(\.sqlExpression) })
}
func having(_ predicate: SQLExpressible) -> Self {
mapInto(\.havingExpressions) { $0.append(predicate.sqlExpression) }
func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self {
map(\.havingExpressionsPromise) { havingExpressionsPromise in
DatabasePromise { db in
try havingExpressionsPromise.resolve(db) + [predicate(db).sqlExpression]
}
}
}
}
@@ -97,11 +96,10 @@ extension SQLQuery: _JoinableRequest {
extension SQLQuery {
func fetchCount(_ db: Database) throws -> Int {
let (statement, adapter) = try SQLQueryGenerator(countQuery).prepare(db)
return try Int.fetchOne(statement, adapter: adapter)!
try QueryInterfaceRequest<Int>(query: countQuery(db)).fetchOne(db)!
}
private var countQuery: SQLQuery {
private func countQuery(_ db: Database) throws -> SQLQuery {
guard groupPromise == nil && limit == nil else {
// SELECT ... GROUP BY ...
// SELECT ... LIMIT ...
@@ -118,9 +116,10 @@ extension SQLQuery {
return trivialCountQuery
}
GRDBPrecondition(!relation.selection.isEmpty, "Can't generate SQL with empty selection")
if relation.selection.count == 1 {
guard let count = relation.selection[0].count(distinct: isDistinct) else {
let selection = try relation.selectionPromise.resolve(db)
GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection")
if selection.count == 1 {
guard let count = selection[0].count(distinct: isDistinct) else {
return trivialCountQuery
}
var countQuery = self.unordered()
@@ -149,8 +148,8 @@ extension SQLQuery {
// SELECT COUNT(*) FROM (self)
private var trivialCountQuery: SQLQuery {
let relation = SQLRelation(
source: .query(unordered()),
selection: [SQLExpressionCount(AllColumns())])
source: .subquery(unordered()),
selectionPromise: DatabasePromise(value: [SQLExpressionCount(AllColumns())]))
return SQLQuery(relation: relation)
}
}
+111 -41
View File
@@ -111,12 +111,12 @@ struct SQLRelation {
// Record.including(all: associationThroughPivot)
case allNotPrefetched
var cardinality: SQLAssociationCardinality {
var isSingular: Bool {
switch self {
case .oneOptional, .oneRequired:
return .toOne
return true
case .allPrefetched, .allNotPrefetched:
return .toMany
return false
}
}
}
@@ -140,16 +140,25 @@ struct SQLRelation {
fileprivate func makeAssociationForKey(_ key: String) -> SQLAssociation {
let key = SQLAssociationKey.fixed(key)
let cardinality: SQLAssociationCardinality
switch kind {
case .oneOptional, .oneRequired:
cardinality = .toOne
case .allPrefetched, .allNotPrefetched:
cardinality = .toMany
}
return SQLAssociation(
key: key,
condition: condition,
relation: relation,
cardinality: kind.cardinality)
cardinality: cardinality)
}
}
var source: SQLSource
var selection: [SQLSelectable] = []
var selectionPromise: DatabasePromise<[SQLSelectable]> = DatabasePromise(value: [])
// Filter is an array of expressions that we'll join with the AND operator.
// This gives nicer output in generated SQL: `(a AND b AND c)` instead of
// `((a AND b) AND c)`.
@@ -178,24 +187,37 @@ struct SQLRelation {
}
extension SQLRelation: Refinable {
func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
with(\.selectionPromise, DatabasePromise(selection))
}
// Convenience
func select(_ selection: [SQLSelectable]) -> Self {
with(\.selection, selection)
select { _ in selection }
}
/// Removes all selections from chidren
func selectOnly(_ selection: [SQLSelectable]) -> Self {
self.with(\.selection, selection)
.map(\.children, { $0.mapValues { $0.map(\.relation, { $0.selectOnly([]) }) } })
select(selection).map(\.children, { $0.mapValues { $0.map(\.relation, { $0.selectOnly([]) }) } })
}
func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
map(\.selectionPromise) { selectionPromise in
DatabasePromise { db in
try selectionPromise.resolve(db) + selection(db)
}
}
}
// Convenience
func annotated(with selection: [SQLSelectable]) -> Self {
mapInto(\.selection) { $0.append(contentsOf: selection) }
annotated(with: { _ in selection })
}
func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self {
map(\.filtersPromise) { filtersPromise in
filtersPromise.flatMap { filters in
DatabasePromise { try filters + [predicate($0).sqlExpression] }
DatabasePromise { db in
try filtersPromise.resolve(db) + [predicate(db).sqlExpression]
}
}
}
@@ -254,10 +276,10 @@ extension SQLRelation {
func appendingChild(for association: SQLAssociation, kind: SQLRelation.Child.Kind) -> Self {
// Preserve association cardinality in intermediate steps of
// including(all:), and force desired cardinality otherwize
let childCardinality = (kind == .allNotPrefetched)
? association.destination.cardinality
: kind.cardinality
let childKey = association.destination.key.name(for: childCardinality)
let isSingular = (kind == .allNotPrefetched)
? association.destination.isSingular
: kind.isSingular
let childKey = association.destination.key.name(singular: isSingular)
let child = SQLRelation.Child(
kind: kind,
condition: association.destination.condition,
@@ -369,7 +391,7 @@ extension SQLRelation: _JoinableRequest {
enum SQLSource {
case table(tableName: String, alias: TableAlias?)
indirect case query(SQLQuery)
indirect case subquery(SQLQuery)
func qualified(with alias: TableAlias) -> SQLSource {
switch self {
@@ -381,8 +403,8 @@ enum SQLSource {
alias.setTableName(tableName)
return .table(tableName: tableName, alias: alias)
}
case let .query(query):
return .query(query.qualified(with: alias))
case .subquery:
return self
}
}
}
@@ -549,13 +571,11 @@ struct SQLAssociationCondition: Equatable {
/// - parameter db: A database connection.
/// - parameter leftAlias: A TableAlias for the table on the left of the
/// JOIN operator.
/// - parameter rightAlias: A TableAlias for the table on the right of the
/// JOIN operator.
/// - Returns: An array of SQL expression that should be joined with
/// the AND operator.
func expressions(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> [SQLExpression] {
/// the AND operator and qualified with the right table.
func expressions(_ db: Database, leftAlias: TableAlias) throws -> [SQLExpression] {
try columnMappings(db).map {
QualifiedColumn($0.right, alias: rightAlias) == QualifiedColumn($0.left, alias: leftAlias)
Column($0.right) == QualifiedColumn($0.left, alias: leftAlias)
}
}
@@ -564,33 +584,44 @@ struct SQLAssociationCondition: Equatable {
///
/// Given `right.a = left.b`, returns `right.a = 1` or
/// `right.a IN (1, 2, 3)`.
func filteringExpression(_ db: Database, leftRows: [Row], rightAlias: TableAlias) throws -> SQLExpression {
if leftRows.isEmpty {
func filteringExpression<Row: ColumnAddressable>(_ db: Database, leftRows: [Row]) throws -> SQLExpression {
guard let firstLeftRow = leftRows.first else {
// Degenerate case: there is no row to attach
return false.sqlExpression
}
// The (left, right) column mapping pairs
let columnMappings = try self.columnMappings(db)
guard let columnMapping = columnMappings.first else {
// We assume that all rows have the same layout, and that addressing
// rows by index is faster than addressing them by column name.
// So we use the first left row in order to convert left column names
// into row indexes.
let mappings: [(leftIndex: Row.ColumnIndex, rightColumn: Column)] = columnMappings.map { mapping in
guard let leftIndex = firstLeftRow.index(forColumn: mapping.left) else {
fatalError("Missing column: \(mapping.left)")
}
return (leftIndex: leftIndex, rightColumn: Column(mapping.right))
}
guard let mapping = mappings.first else {
// Degenerate case: no joining column
return true.sqlExpression
}
if columnMappings.count == 1 {
if mappings.count == 1 {
// Join on a single right column.
let rightColumn = QualifiedColumn(columnMapping.right, alias: rightAlias)
// Unique database values and filter out NULL:
var dbValues = Set(leftRows.map { $0[columnMapping.left] as DatabaseValue })
let leftIndex = mapping.leftIndex
var dbValues = Set(leftRows.map { $0.databaseValue(at: leftIndex) })
dbValues.remove(.null)
if dbValues.isEmpty {
// Can't join
return false.sqlExpression
return mapping.rightColumn == nil
} else {
// table.a IN (1, 2, 3, ...)
// Sort database values for nicer output.
return dbValues.sorted(by: <).contains(rightColumn)
return dbValues.sorted(by: <).contains(mapping.rightColumn)
}
} else {
// Join on a multiple columns.
@@ -598,11 +629,10 @@ struct SQLAssociationCondition: Equatable {
return leftRows
.map({ leftRow in
// (table.a = 1) AND (table.b = 2)
columnMappings
.map({ columns -> SQLExpression in
let rightColumn = QualifiedColumn(columns.right, alias: rightAlias)
let leftValue = leftRow[columns.left] as DatabaseValue
return rightColumn == leftValue
mappings
.map({ mapping -> SQLExpression in
let leftValue = leftRow.databaseValue(at: mapping.leftIndex)
return mapping.rightColumn == leftValue
})
.joined(operator: .and)
})
@@ -611,6 +641,39 @@ struct SQLAssociationCondition: Equatable {
}
}
/// A protocol for row-like containers
protocol ColumnAddressable {
associatedtype ColumnIndex
func index(forColumn column: String) -> ColumnIndex?
func databaseValue(at index: ColumnIndex) -> DatabaseValue
}
/// A "row" that contains null values for all columns
struct NullRow: ColumnAddressable {
struct DummyIndex { }
func index(forColumn column: String) -> DummyIndex? { DummyIndex() }
@inline(__always)
func databaseValue(at index: DummyIndex) -> DatabaseValue { .null }
}
/// Row has columns
extension Row: ColumnAddressable {
@inline(__always)
func databaseValue(at index: Int) -> DatabaseValue { self[index] }
}
/// PersistenceContainer has columns
extension PersistenceContainer: ColumnAddressable {
func index(forColumn column: String) -> String? { column }
@inline(__always)
func databaseValue(at column: String) -> DatabaseValue {
guard let value = self[caseInsensitive: column] else {
fatalError("Missing column: \(column)")
}
return value.databaseValue
}
}
// MARK: - Merging
//
// "Merging" is an operation that takes two relations and, if they are
@@ -634,8 +697,8 @@ extension SQLRelation {
return nil
}
let mergedFiltersPromise: DatabasePromise<[SQLExpression]> = filtersPromise.flatMap { filters in
DatabasePromise { try filters + other.filtersPromise.resolve($0) }
let mergedFiltersPromise = DatabasePromise<[SQLExpression]> { db in
try self.filtersPromise.resolve(db) + other.filtersPromise.resolve(db)
}
var mergedChildren: OrderedDictionary<String, SQLRelation.Child> = [:]
@@ -655,14 +718,21 @@ extension SQLRelation {
}
// replace selection unless empty
let mergedSelection = other.selection.isEmpty ? selection : other.selection
let mergedSelectionPromise = DatabasePromise { db -> [SQLSelectable] in
let otherSelection = try other.selectionPromise.resolve(db)
if otherSelection.isEmpty {
return try self.selectionPromise.resolve(db)
} else {
return otherSelection
}
}
// replace ordering unless empty
let mergedOrdering = other.ordering.isEmpty ? ordering : other.ordering
return SQLRelation(
source: mergedSource,
selection: mergedSelection,
selectionPromise: mergedSelectionPromise,
filtersPromise: mergedFiltersPromise,
ordering: mergedOrdering,
children: mergedChildren)
@@ -21,13 +21,13 @@ public struct AllColumns {
extension AllColumns: SQLSelectable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
public func resultColumnSQL(_ context: SQLGenerationContext) -> String {
"*"
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func countedSQL(_ context: inout SQLGenerationContext) -> String {
public func countedSQL(_ context: SQLGenerationContext) -> String {
"*"
}
@@ -70,35 +70,18 @@ struct QualifiedAllColumns {
}
extension QualifiedAllColumns: SQLSelectable {
func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
func resultColumnSQL(_ context: SQLGenerationContext) -> String {
if let qualifier = context.qualifier(for: alias) {
return qualifier.quotedDatabaseIdentifier + ".*"
}
return "*"
}
func countedSQL(_ context: inout SQLGenerationContext) -> String {
// TODO: restore the check below.
//
// It is currently disabled because of AssociationAggregateTests.testHasManyIsEmpty:
//
// let request = Team.having(Team.players.isEmpty)
// try XCTAssertEqual(request.fetchCount(db), 1)
//
// This should build the trivial count query `SELECT COUNT(*) FROM (SELECT ...)`
//
// Unfortunately, we don't support anonymous table aliases that would be
// required here. Because we don't support anonymous tables aliases,
// everything happens as if we wanted to generate
// `SELECT COUNT(team.*) FROM (SELECT ...)`, which is invalid SQL.
//
// So let's always return `*`, and fix this later.
// if context.qualifier(for: alias) != nil {
// // SELECT COUNT(t.*) is invalid SQL
// fatalError("Not implemented, or invalid query")
// }
func countedSQL(_ context: SQLGenerationContext) -> String {
if context.qualifier(for: alias) != nil {
// SELECT COUNT(t.*) is invalid SQL
fatalError("Not implemented, or invalid query")
}
return "*"
}
@@ -125,12 +108,12 @@ struct SQLAliasedExpression: SQLSelectable {
self.name = name
}
func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
expression.resultColumnSQL(&context) + " AS " + name.quotedDatabaseIdentifier
func resultColumnSQL(_ context: SQLGenerationContext) throws -> String {
try expression.resultColumnSQL(context) + " AS " + name.quotedDatabaseIdentifier
}
func countedSQL(_ context: inout SQLGenerationContext) -> String {
expression.countedSQL(&context)
func countedSQL(_ context: SQLGenerationContext) throws -> String {
try expression.countedSQL(context)
}
func count(distinct: Bool) -> SQLCount? {
+2 -2
View File
@@ -8,10 +8,10 @@
/// :nodoc:
public protocol SQLSelectable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
func resultColumnSQL(_ context: inout SQLGenerationContext) -> String
func resultColumnSQL(_ context: SQLGenerationContext) throws -> String
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
func countedSQL(_ context: inout SQLGenerationContext) -> String
func countedSQL(_ context: SQLGenerationContext) throws -> String
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
func count(distinct: Bool) -> SQLCount?
@@ -1,54 +1,84 @@
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// SQLGenerationContext is responsible for preventing SQL injection and
/// disambiguating table names when GRDB generates SQL queries.
/// SQLGenerationContext supports SQL generation:
///
/// - It provides a database connection during SQL generation, for any purpose
/// such as schema introspection.
///
/// - It provides unique table aliases in order to disambiguates table names
/// and columns.
///
/// - It gathers SQL arguments in order to prevent SQL injection.
///
/// :nodoc:
public struct SQLGenerationContext {
var arguments: StatementArguments {
_arguments ?? StatementArguments()
public final class SQLGenerationContext {
private enum Parent {
case none(db: Database, argumentsSink: StatementArgumentsSink)
case context(SQLGenerationContext)
}
private var _arguments: StatementArguments?
private var resolvedNames: [TableAlias: String]
private var qualifierNeeded: Bool
/// Used for pure SQL generation. Arguments are always empty.
static let rawSQLContext = SQLGenerationContext(
_arguments: nil,
resolvedNames: [:],
qualifierNeeded: false)
// TODO: make internal when FetchRequest is a closed protocol.
/// A database connection.
public var db: Database {
switch parent {
case let .none(db: db, argumentsSink: _): return db
case let .context(context): return context.db
}
}
/// Used for SQLLiteral generation
static let sqlLiteralContext = SQLGenerationContext(
_arguments: [],
resolvedNames: [:],
qualifierNeeded: false)
/// All gathered arguments
var arguments: StatementArguments { argumentsSink.arguments }
/// Used for TableRecord.selectionSQL
static let selectionContext = SQLGenerationContext(
_arguments: nil,
resolvedNames: [:],
qualifierNeeded: true)
/// Access to the database connection, the arguments sink, and resolved
/// names of table aliases from outer contexts (useful in case of
/// subquery generation).
private let parent: Parent
/// Used for SQLQueryGenerator
static func queryContext(aliases: [TableAlias]) -> SQLGenerationContext {
SQLGenerationContext(
_arguments: [],
resolvedNames: aliases.resolvedNames,
qualifierNeeded: aliases.count > 1)
/// The arguments sink which prevents SQL injection.
private var argumentsSink: StatementArgumentsSink {
switch parent {
case let .none(db: _, argumentsSink: argumentsSink): return argumentsSink
case let .context(context): return context.argumentsSink
}
}
private let resolvedNames: [TableAlias: String]
private let ownAliases: Set<TableAlias>
/// Creates a generation context.
///
/// - parameter db: A database connection.
/// - parameter argumentsSink: An arguments sink.
/// - parameter aliases: An array of table aliases to disambiguate.
init(
_ db: Database,
argumentsSink: StatementArgumentsSink = StatementArgumentsSink(),
aliases: [TableAlias] = [])
{
self.parent = .none(db: db, argumentsSink: argumentsSink)
self.resolvedNames = aliases.resolvedNames
self.ownAliases = Set(aliases)
}
/// Creates a generation context.
///
/// - parameter parent: A parent context.
/// - parameter aliases: An array of table aliases to disambiguate.
init(
parent: SQLGenerationContext,
aliases: [TableAlias] = [])
{
self.parent = .context(parent)
self.resolvedNames = aliases.resolvedNames
self.ownAliases = Set(aliases)
}
/// Returns whether arguments could be appended.
/// May be false for SQLGenerationContext.rawSQLContext
mutating func append(arguments newArguments: StatementArguments) -> Bool {
if newArguments.isEmpty {
return true
}
guard let arguments = _arguments else {
return false
}
self._arguments = arguments + newArguments
return true
///
/// A false result means that the generation context does not support
/// SQL arguments.
func append(arguments: StatementArguments) -> Bool {
argumentsSink.append(arguments: arguments)
}
/// May be nil, when a qualifier is not needed:
@@ -62,15 +92,26 @@ public struct SQLGenerationContext {
if alias.hasUserName {
return alias.identityName
}
if qualifierNeeded == false {
return nil
if !ownAliases.contains(alias) {
return resolvedName(for: alias)
}
return resolvedName(for: alias)
if ownAliases.count > 1 {
return resolvedName(for: alias)
}
return nil
}
/// WHERE <resolvedName> MATCH pattern
func resolvedName(for alias: TableAlias) -> String {
resolvedNames[alias] ?? alias.identityName
if let name = resolvedNames[alias] {
return name
}
switch parent {
case .none:
return alias.identityName
case let .context(context):
return context.resolvedName(for: alias)
}
}
/// FROM tableName <alias>
@@ -83,6 +124,40 @@ public struct SQLGenerationContext {
}
}
/// A class that gathers statement arguments, and can be shared between
/// several SQLGenerationContext.
class StatementArgumentsSink {
private(set) var arguments: StatementArguments
private let rawSQL: Bool
/// A sink which does not accept any arguments.
static let forRawSQL = StatementArgumentsSink(rawSQL: true)
private init(rawSQL: Bool) {
self.arguments = []
self.rawSQL = rawSQL
}
/// A sink which accepts arguments
convenience init() {
self.init(rawSQL: false)
}
// fileprivate so that SQLGenerationContext.append(arguments:) is the only
// available api.
/// Returns false for SQLGenerationContext.rawSQLContext
fileprivate func append(arguments: StatementArguments) -> Bool {
if arguments.isEmpty {
return true
}
if rawSQL {
return false
}
self.arguments += arguments
return true
}
}
// MARK: - TableAlias
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
@@ -276,6 +351,12 @@ public class TableAlias: Hashable {
expression.qualifiedExpression(with: self)
}
/// Returns a qualified ordering that is able to resolve ambiguities in
/// joined queries.
public subscript(_ ordering: SQLOrderingTerm) -> SQLOrderingTerm {
ordering.qualifiedOrdering(with: self)
}
/// :nodoc:
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(root))
@@ -1,12 +1,22 @@
/// SQLQueryGenerator is able to generate an SQL SELECT query.
struct SQLQueryGenerator {
struct SQLQueryGenerator: Refinable {
fileprivate private(set) var relation: SQLQualifiedRelation
private let isDistinct: Bool
private let groupPromise: DatabasePromise<[SQLExpression]>?
private let havingExpressions: [SQLExpression]
private let havingExpressionsPromise: DatabasePromise<[SQLExpression]>
private let limit: SQLLimit?
private let singleResult: Bool
// For database region
private let prefetchedAssociations: [SQLAssociation]
init(_ query: SQLQuery) {
/// Creates an SQL query generator.
///
/// - parameter singleResult: A hint as to whether the query should be
/// optimized for a single result.
init(
query: SQLQuery,
forSingleResult singleResult: Bool = false)
{
// To generate SQL, we need a "qualified" relation, where all tables,
// expressions, etc, are identified with table aliases.
//
@@ -34,60 +44,94 @@ struct SQLQueryGenerator {
//
// This turns `GROUP BY id` INTO `GROUP BY book.id`, and
// `HAVING MAX(year) < 2000` INTO `HAVING MAX(book.year) < 2000`.
let alias = relation.sourceAlias
groupPromise = query.groupPromise?.map { $0.map { $0.qualifiedExpression(with: alias) } }
havingExpressions = query.havingExpressions.map { $0.qualifiedExpression(with: alias) }
if let alias = relation.source.alias {
groupPromise = query.groupPromise?.map {
$0.map { $0.qualifiedExpression(with: alias) }
}
havingExpressionsPromise = query.havingExpressionsPromise.map {
$0.map { $0.qualifiedExpression(with: alias) }
}
} else {
groupPromise = query.groupPromise
havingExpressionsPromise = query.havingExpressionsPromise
}
// Preserve other flags
isDistinct = query.isDistinct
limit = query.limit
isDistinct = query.isDistinct
self.singleResult = singleResult
prefetchedAssociations = query.relation.prefetchedAssociations
}
func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String {
func requestSQL(_ context: SQLGenerationContext) throws -> String {
// Build an SQL generation context with all aliases found in the query,
// so that we can disambiguate tables that are used several times with
// SQL aliases.
let context = SQLGenerationContext(parent: context, aliases: relation.allAliases)
var sql = "SELECT"
if isDistinct {
sql += " DISTINCT"
}
let selection = relation.selection
GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection")
sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ")
let selection = try relation.selectionPromise.resolve(context.db)
GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with an empty selection")
sql += try " " + selection.map { try $0.resultColumnSQL(context) }.joined(separator: ", ")
sql += " FROM "
sql += try relation.source.sql(db, &context)
sql += try relation.source.sql(context)
for (_, join) in relation.joins {
sql += " "
sql += try join.sql(db, &context, leftAlias: relation.sourceAlias)
if relation.joins.isEmpty == false {
guard let sourceAlias = relation.source.alias else {
// This never happens as long as we only use subqueries as sources
// in the `SELECT COUNT(*) FROM (SELECT ...)` case: see
// SQLQuery.trivialCountQuery.
fatalError("Not implemented: join on a subquery")
}
for (_, join) in relation.joins {
sql += " "
sql += try join.sql(context, leftAlias: sourceAlias)
}
}
let filters = try relation.filtersPromise.resolve(db)
let filters = try relation.filtersPromise.resolve(context.db)
if filters.isEmpty == false {
sql += " WHERE "
sql += filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false)
sql += try filters.joined(operator: .and).expressionSQL(context, wrappedInParenthesis: false)
}
if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty {
let groupExpressions = try groupPromise?.resolve(context.db) ?? []
if !groupExpressions.isEmpty {
sql += " GROUP BY "
sql += groupExpressions
.map { $0.expressionSQL(&context, wrappedInParenthesis: false) }
sql += try groupExpressions
.map { try $0.expressionSQL(context, wrappedInParenthesis: false) }
.joined(separator: ", ")
}
let havingExpressions = try havingExpressionsPromise.resolve(context.db)
if havingExpressions.isEmpty == false {
sql += " HAVING "
sql += havingExpressions.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false)
sql += try havingExpressions.joined(operator: .and).expressionSQL(context, wrappedInParenthesis: false)
}
let orderings = try relation.ordering.resolve(db)
let orderings = try relation.ordering.resolve(context.db)
if !orderings.isEmpty {
sql += " ORDER BY "
sql += orderings
.map { $0.orderingTermSQL(&context) }
sql += try orderings
.map { try $0.orderingTermSQL(context) }
.joined(separator: ", ")
}
var limit = self.limit
if try singleResult && !expectsSingleResult(
context.db,
selection: selection,
filters: filters,
groupExpressions: groupExpressions)
{
limit = SQLLimit(limit: 1, offset: limit?.offset)
}
if let limit = limit {
sql += " LIMIT "
sql += limit.sql
@@ -96,8 +140,35 @@ struct SQLQueryGenerator {
return sql
}
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
try (makeSelectStatement(db), rowAdapter(db))
func makePreparedRequest(_ db: Database) throws -> PreparedRequest {
try PreparedRequest(
statement: makeSelectStatement(db),
adapter: rowAdapter(db))
}
/// Returns a select statement
func makeSelectStatement(_ db: Database) throws -> SelectStatement {
// Build
let context = SQLGenerationContext(db)
let sql = try requestSQL(context)
// Compile & set arguments
let statement = try db.makeSelectStatement(sql: sql)
statement.arguments = context.arguments
// Optimize statement region. This allows us to track individual rowids.
statement.databaseRegion = try optimizedSelectedRegion(db, statement.databaseRegion)
// Also append the prefetched region. This makes sure we observe the
// correct database region when the statement is executed, even if we
// don't execute all request statements due to lacking database content.
// For example, fetching `parent.including(all: children)` will select
// parents, but won't attempt to select any children if there is no
// parent in the database. And yet we need to observe the table for
// children. This is why we include the prefetched region.
try statement.databaseRegion.formUnion(prefetchedRegion(db, associations: prefetchedAssociations))
return statement
}
private func optimizedSelectedRegion(_ db: Database, _ selectedRegion: DatabaseRegion) throws -> DatabaseRegion {
@@ -126,6 +197,103 @@ struct SQLQueryGenerator {
return selectedRegion.tableIntersection(canonicalTableName, rowIds: rowIds)
}
/// If true, executing this query yields at most one row.
/// If false, we don't know how many rows this query returns.
private func expectsSingleResult(
_ db: Database,
selection: [SQLSelectable],
filters: [SQLExpression],
groupExpressions: [SQLExpression])
throws -> Bool
{
if relation.allAliases.count > 1 {
// Don't expect single results as soon as several tables are involved
return false
}
// Do we filter on a unique key?
if case let .table(tableName, sourceAlias) = relation.source {
let filteredColumns = filters.flatMap(\.truthComponents).compactMap { expression -> String? in
guard let equalExpression = expression as? SQLExpressionEqual,
(equalExpression.op == .equal || equalExpression.op == .is) else
{
// Not Column("foo") == value
return nil
}
if equalExpression.lhs is DatabaseValue,
let qualifiedColumn = equalExpression.rhs as? QualifiedColumn,
qualifiedColumn.alias == sourceAlias
{
// value == Column("foo")
return qualifiedColumn.name
}
if equalExpression.rhs is DatabaseValue,
let qualifiedColumn = equalExpression.lhs as? QualifiedColumn,
qualifiedColumn.alias == sourceAlias
{
// Column("foo") == value
return qualifiedColumn.name
}
return nil
}
if try db.table(tableName, hasUniqueKey: filteredColumns) {
// Filter by unique key: guaranteed single row!
return true
}
}
// Do we aggregate without grouping?
if groupExpressions.isEmpty {
// https://www.sqlite.org/lang_aggfunc.html#groupconcat
let aggregateFunctionNames: Set<String> = [
"AVG", "COUNT", "GROUP_CONCAT", "MAX", "MIN", "SUM", "TOTAL"
]
for selectable in selection {
switch selectable {
case is SQLExpressionCount:
// Selection contains COUNT(...): guaranteed single row!
return true
case is SQLExpressionCountDistinct:
// Selection contains COUNT(DISTINCT ...): guaranteed single row!
return true
case let expression as SQLExpressionFunction:
let functionName = expression.functionName.sql.uppercased()
guard aggregateFunctionNames.contains(functionName) else {
// Not an aggregate function.
// (We miss custom aggregates)
continue
}
guard expression.arguments.allSatisfy({ $0 is QualifiedColumn }) else {
// Aggregate function argument is not a column.
// (We miss expressions such as `max(column + 1)`)
continue
}
if functionName == "GROUP_CONCAT" {
switch expression.arguments.count {
case 1, 2:
// Selection contains an aggregate function: guaranteed single row!
return true
default:
break
}
} else if expression.arguments.count == 1 {
// Selection contains an aggregate function: guaranteed single row!
return true
}
default:
// Not an aggregate
// (We miss expressions such as `max(column) + 1`)
break
}
}
}
return false
}
func makeDeleteStatement(_ db: Database) throws -> UpdateStatement {
switch try grouping(db) {
case .none:
@@ -138,19 +306,22 @@ struct SQLQueryGenerator {
return try makeTrivialDeleteStatement(db)
}
var context = SQLGenerationContext.queryContext(aliases: relation.allAliases)
let context = SQLGenerationContext(db, aliases: relation.allAliases)
var sql = try "DELETE FROM " + relation.source.sql(db, &context)
var sql = try "DELETE FROM " + relation.source.sql(context)
let filters = try relation.filtersPromise.resolve(db)
if filters.isEmpty == false {
sql += " WHERE " + filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false)
sql += " WHERE "
sql += try filters
.joined(operator: .and)
.expressionSQL(context, wrappedInParenthesis: false)
}
if let limit = limit {
let orderings = try relation.ordering.resolve(db)
if !orderings.isEmpty {
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ")
sql += try " ORDER BY " + orderings.map { try $0.orderingTermSQL(context) }.joined(separator: ", ")
}
sql += " LIMIT " + limit.sql
}
@@ -168,22 +339,21 @@ struct SQLQueryGenerator {
}
}
/// DELETE FROM table WHERE rowid IN (SELECT rowid FROM table ...)
/// DELETE FROM table WHERE id IN (SELECT id FROM table ...)
private func makeTrivialDeleteStatement(_ db: Database) throws -> UpdateStatement {
guard case let .table(tableName: tableName, alias: _) = relation.source else {
// Programmer error
fatalError("Can't delete without any database table")
}
var context = SQLGenerationContext.queryContext(aliases: relation.allAliases)
let context = SQLGenerationContext(db)
let primaryKey = SQLPrimaryKeyExpression(tableName: tableName)
// SELECT rowid FROM table ...
var generator = self
generator.relation = generator.relation.selectOnly([Column.rowID])
let selectSQL = try generator.sql(db, &context)
// DELETE FROM table WHERE rowid IN (SELECT rowid FROM table ...)
let sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE rowid IN (\(selectSQL))"
var sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE "
sql += try primaryKey.expressionSQL(context, wrappedInParenthesis: false)
sql += " IN ("
sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).requestSQL(context)
sql += ")"
let statement = try db.makeUpdateStatement(sql: sql)
statement.arguments = context.arguments
@@ -217,7 +387,7 @@ struct SQLQueryGenerator {
return nil
}
var context = SQLGenerationContext.queryContext(aliases: relation.allAliases)
let context = SQLGenerationContext(db, aliases: relation.allAliases)
var sql = "UPDATE "
@@ -225,22 +395,25 @@ struct SQLQueryGenerator {
sql += "OR \(conflictResolution.rawValue) "
}
sql += try relation.source.sql(db, &context)
sql += try relation.source.sql(context)
let assignmentsSQL = assignments
.map { $0.sql(&context) }
let assignmentsSQL = try assignments
.map { try $0.sql(context) }
.joined(separator: ", ")
sql += " SET " + assignmentsSQL
let filters = try relation.filtersPromise.resolve(db)
if filters.isEmpty == false {
sql += " WHERE " + filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false)
sql += " WHERE "
sql += try filters
.joined(operator: .and)
.expressionSQL(context, wrappedInParenthesis: false)
}
if let limit = limit {
let orderings = try relation.ordering.resolve(db)
if !orderings.isEmpty {
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ")
sql += try " ORDER BY " + orderings.map { try $0.orderingTermSQL(context) }.joined(separator: ", ")
}
sql += " LIMIT " + limit.sql
}
@@ -258,7 +431,7 @@ struct SQLQueryGenerator {
}
}
/// UPDATE table SET ... WHERE rowid IN (SELECT rowid FROM table ...)
/// UPDATE table SET ... WHERE id IN (SELECT id FROM table ...)
/// Returns nil if assignments is empty
private func makeTrivialUpdateStatement(
_ db: Database,
@@ -277,7 +450,8 @@ struct SQLQueryGenerator {
return nil
}
var context = SQLGenerationContext.queryContext(aliases: relation.allAliases)
let context = SQLGenerationContext(db)
let primaryKey = SQLPrimaryKeyExpression(tableName: tableName)
// UPDATE table...
var sql = "UPDATE "
@@ -287,40 +461,23 @@ struct SQLQueryGenerator {
sql += tableName.quotedDatabaseIdentifier
// SET column = value...
let assignmentsSQL = assignments
.map { $0.sql(&context) }
let assignmentsSQL = try assignments
.map { try $0.sql(context) }
.joined(separator: ", ")
sql += " SET " + assignmentsSQL
// WHERE rowid IN (SELECT rowid FROM ...)
var generator = self
generator.relation = generator.relation.selectOnly([Column.rowID])
sql += try " WHERE rowid IN (\(generator.sql(db, &context)))"
// WHERE id IN (SELECT id FROM ...)
sql += " WHERE "
sql += try primaryKey.expressionSQL(context, wrappedInParenthesis: false)
sql += " IN ("
sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).requestSQL(context)
sql += ")"
let statement = try db.makeUpdateStatement(sql: sql)
statement.arguments = context.arguments
return statement
}
/// Returns a select statement
func makeSelectStatement(_ db: Database) throws -> SelectStatement {
// Build an SQK generation context with all aliases found in the query,
// so that we can disambiguate tables that are used several times with
// SQL aliases.
var context = SQLGenerationContext.queryContext(aliases: relation.allAliases)
// Generate SQL
let sql = try self.sql(db, &context)
// Compile & set arguments
let statement = try db.makeSelectStatement(sql: sql)
statement.arguments = context.arguments
// Optimize databaseRegion
statement.selectedRegion = try optimizedSelectedRegion(db, statement.selectedRegion)
return statement
}
/// Informs about the query grouping
private enum GroupingInfo {
/// No grouping at all: SELECT ... FROM player
@@ -409,14 +566,11 @@ struct SQLQueryGenerator {
/// | | | • filterPromise
/// | | • joins
/// | • source
/// • selection
/// • selectionPromise
private struct SQLQualifiedRelation {
/// The source alias
var sourceAlias: TableAlias { source.alias }
/// All aliases, including aliases of joined relations
var allAliases: [TableAlias] {
joins.reduce(into: source.allAliases) {
joins.reduce(into: [source.alias].compactMap { $0 }) {
$0.append(contentsOf: $1.value.relation.allAliases)
}
}
@@ -429,16 +583,20 @@ private struct SQLQualifiedRelation {
let source: SQLQualifiedSource
/// The selection from source, not including selection of joined relations
private var sourceSelection: [SQLSelectable]
private var sourceSelectionPromise: DatabasePromise<[SQLSelectable]>
/// The full selection, including selection of joined relations
///
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • selection
var selection: [SQLSelectable] {
joins.reduce(into: sourceSelection) {
$0.append(contentsOf: $1.value.relation.selection)
/// • selectionPromise
var selectionPromise: DatabasePromise<[SQLSelectable]> {
DatabasePromise { db in
let selection = try self.sourceSelectionPromise.resolve(db)
return try self.joins.values.reduce(into: selection) { selection, join in
let joinedSelection = try join.relation.selectionPromise.resolve(db)
selection.append(contentsOf: joinedSelection)
}
}
}
@@ -477,30 +635,23 @@ private struct SQLQualifiedRelation {
// SQLGenerationContext, when the SQLSelectQueryGenerator which owns
// this SQLQualifiedRelation generates SQL.
source = SQLQualifiedSource(relation.source)
let sourceAlias = source.alias
// Qualify all joins, selection, filter, and ordering, so that all
// identifiers can be correctly disambiguated and qualified.
joins = relation.children.compactMapValues { child -> SQLQualifiedJoin? in
let kind: SQLQualifiedJoin.Kind
switch child.kind {
case .oneRequired:
kind = .innerJoin
case .oneOptional:
kind = .leftJoin
case .allPrefetched, .allNotPrefetched:
// This relation child is not fetched with an SQL join.
return nil
joins = relation.children.compactMapValues { SQLQualifiedJoin($0) }
if let sourceAlias = source.alias {
sourceSelectionPromise = relation.selectionPromise.map {
$0.map { $0.qualifiedSelectable(with: sourceAlias) }
}
return SQLQualifiedJoin(
kind: kind,
condition: child.condition,
relation: SQLQualifiedRelation(child.relation))
filtersPromise = relation.filtersPromise.map {
$0.map { $0.qualifiedExpression(with: sourceAlias) }
}
sourceOrdering = relation.ordering.qualified(with: sourceAlias)
} else {
sourceSelectionPromise = relation.selectionPromise
filtersPromise = relation.filtersPromise
sourceOrdering = relation.ordering
}
sourceSelection = relation.selection.map { $0.qualifiedSelectable(with: sourceAlias) }
filtersPromise = relation.filtersPromise.map { $0.map { $0.qualifiedExpression(with: sourceAlias) } }
sourceOrdering = relation.ordering.qualified(with: sourceAlias)
}
/// See SQLQueryGenerator.rowAdapter(_:)
@@ -521,7 +672,7 @@ private struct SQLQualifiedRelation {
// The number of columns in source selection. Columns selected by joined
// relations are appended after.
let sourceSelectionWidth = try sourceSelection.reduce(0) {
let sourceSelectionWidth = try sourceSelectionPromise.resolve(db).reduce(0) {
try $0 + $1.columnCount(db)
}
@@ -565,7 +716,14 @@ private struct SQLQualifiedRelation {
/// Removes all selections from joins
func selectOnly(_ selection: [SQLSelectable]) -> Self {
self.with(\.sourceSelection, selection.map { $0.qualifiedSelectable(with: sourceAlias) })
let sourceSelectionPromise: DatabasePromise<[SQLSelectable]>
if let sourceAlias = source.alias {
sourceSelectionPromise = DatabasePromise(value: selection.map { $0.qualifiedSelectable(with: sourceAlias) })
} else {
sourceSelectionPromise = DatabasePromise(value: selection)
}
return self
.with(\.sourceSelectionPromise, sourceSelectionPromise)
.map(\.joins, { $0.mapValues { $0.selectOnly([]) } })
}
}
@@ -575,23 +733,24 @@ extension SQLQualifiedRelation: Refinable { }
/// A "qualified" source, where all tables are identified with a table alias.
private enum SQLQualifiedSource {
case table(tableName: String, alias: TableAlias)
indirect case query(SQLQueryGenerator)
indirect case subquery(SQLQueryGenerator)
var alias: TableAlias {
/// Nil for subquery sources.
///
/// Maybe one day we'll support aliased subqueries, as below:
///
/// SELECT alias.* FROM (SELECT ...) alias
///
/// But today we only use subqueries for SQLQuery.trivialCountQuery,
/// which does not need any alias:
///
/// SELECT COUNT(*) FROM (SELECT ...)
var alias: TableAlias? {
switch self {
case .table(_, let alias):
case let .table(_, alias):
return alias
case .query(let query):
return query.relation.sourceAlias
}
}
var allAliases: [TableAlias] {
switch self {
case .table(_, let alias):
return [alias]
case .query(let query):
return query.relation.allAliases
case .subquery:
return nil
}
}
@@ -600,12 +759,12 @@ private enum SQLQualifiedSource {
case let .table(tableName, alias):
let alias = alias ?? TableAlias(tableName: tableName)
self = .table(tableName: tableName, alias: alias)
case let .query(query):
self = .query(SQLQueryGenerator(query))
case let .subquery(subquery):
self = .subquery(SQLQueryGenerator(query: subquery))
}
}
func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String {
func sql(_ context: SQLGenerationContext) throws -> String {
switch self {
case let .table(tableName, alias):
if let aliasName = context.aliasName(for: alias) {
@@ -613,44 +772,61 @@ private enum SQLQualifiedSource {
} else {
return "\(tableName.quotedDatabaseIdentifier)"
}
case let .query(query):
return try "(\(query.sql(db, &context)))"
case let .subquery(generator):
let sql = try generator.requestSQL(context)
return "(\(sql))"
}
}
}
/// A "qualified" join, where all tables are identified with a table alias.
private struct SQLQualifiedJoin {
private struct SQLQualifiedJoin: Refinable {
enum Kind: String {
case leftJoin = "LEFT JOIN"
case innerJoin = "JOIN"
init?(_ kind: SQLRelation.Child.Kind) {
switch kind {
case .oneRequired:
self = .innerJoin
case .oneOptional:
self = .leftJoin
case .allPrefetched, .allNotPrefetched:
// Eager loading of to-many associations is not implemented with joins
return nil
}
}
}
let kind: Kind
let condition: SQLAssociationCondition
let relation: SQLQualifiedRelation
var kind: Kind
var condition: SQLAssociationCondition
var relation: SQLQualifiedRelation
func sql(_ db: Database, _ context: inout SQLGenerationContext, leftAlias: TableAlias) throws -> String {
try sql(db, &context, leftAlias: leftAlias, allowingInnerJoin: true)
init?(_ child: SQLRelation.Child) {
guard let kind = Kind(child.kind) else {
return nil
}
self.kind = kind
self.condition = child.condition
self.relation = SQLQualifiedRelation(child.relation)
}
func sql(_ context: SQLGenerationContext, leftAlias: TableAlias) throws -> String {
try sql(context, leftAlias: leftAlias, allowingInnerJoin: true)
}
/// Removes all selections from joins
func selectOnly(_ selection: [SQLSelectable]) -> SQLQualifiedJoin {
SQLQualifiedJoin(
kind: kind,
condition: condition,
relation: relation.selectOnly(selection))
map(\.relation) { $0.selectOnly(selection) }
}
private func sql(
_ db: Database,
_ context: inout SQLGenerationContext,
_ context: SQLGenerationContext,
leftAlias: TableAlias,
allowingInnerJoin allowsInnerJoin: Bool)
throws -> String
{
var allowsInnerJoin = allowsInnerJoin
var sql = ""
switch self.kind {
case .innerJoin:
@@ -665,17 +841,30 @@ private struct SQLQualifiedJoin {
case .leftJoin:
allowsInnerJoin = false
}
sql += try "\(kind.rawValue) \(relation.source.sql(db, &context))"
let rightAlias = relation.sourceAlias
let filters = try condition.expressions(db, leftAlias: leftAlias, rightAlias: rightAlias)
+ relation.filtersPromise.resolve(db)
// JOIN table...
var sql = try "\(kind.rawValue) \(relation.source.sql(context))"
guard let rightAlias = relation.source.alias else {
// This never happens as long as we only use subqueries as sources
// in the `SELECT COUNT(*) FROM (SELECT ...)` case: see
// SQLQuery.trivialCountQuery.
fatalError("Not implemented: join on a subquery")
}
// ... ON <join conditions> AND <other filters>
var filters = try condition.expressions(context.db, leftAlias: leftAlias)
filters += try relation.filtersPromise.resolve(context.db)
if filters.isEmpty == false {
sql += " ON \(filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false))"
let filterSQL = try filters
.joined(operator: .and)
.qualifiedExpression(with: rightAlias)
.expressionSQL(context, wrappedInParenthesis: false)
sql += " ON \(filterSQL)"
}
for (_, join) in relation.joins {
sql += try " \(join.sql(db, &context, leftAlias: rightAlias, allowingInnerJoin: allowsInnerJoin))"
// Right becomes left as we dig further
sql += try " \(join.sql(context, leftAlias: rightAlias, allowingInnerJoin: allowsInnerJoin))"
}
return sql
@@ -1,10 +1,24 @@
/// :nodoc:
extension SQLInterpolation {
// MARK: - TableRecord
/// Appends the table name of the record type.
///
/// // SELECT * FROM player
/// let request: SQLRequest<Player> = "SELECT * FROM \(Player.self)"
public mutating func appendInterpolation<T: TableRecord>(_ table: T.Type) {
public mutating func appendInterpolation<T>(_ table: T.Type)
where T: TableRecord
{
appendLiteral(table.databaseTableName.quotedDatabaseIdentifier)
}
/// Appends the table name of the record type.
///
/// // SELECT * FROM player
/// let request: SQLRequest<Player> = "SELECT * FROM \(Player.self)"
@_disfavoredOverload
public mutating func appendInterpolation(_ table: TableRecord.Type) {
appendLiteral(table.databaseTableName.quotedDatabaseIdentifier)
}
@@ -13,58 +27,127 @@ extension SQLInterpolation {
/// // INSERT INTO player ...
/// let player: Player = ...
/// let request: SQLRequest<Player> = "INSERT INTO \(tableOf: player) ..."
public mutating func appendInterpolation<T: TableRecord>(tableOf record: T) {
public mutating func appendInterpolation<T>(tableOf record: T)
where T: TableRecord
{
appendInterpolation(type(of: record))
}
/// Appends the table name of the record.
///
/// // INSERT INTO player ...
/// let player: Player = ...
/// let request: SQLRequest<Player> = "INSERT INTO \(tableOf: player) ..."
@_disfavoredOverload
public mutating func appendInterpolation(tableOf record: TableRecord) {
appendInterpolation(type(of: record))
}
/// Appends the selection of the record type.
///
/// // SELECT * FROM player
/// let player: Player = ...
/// let request: SQLRequest<Player> = "SELECT \(columnsOf: Player.self) FROM player"
///
/// // SELECT p.* FROM player p
/// let player: Player = ...
/// let request: SQLRequest<Player> = "SELECT \(columnsOf: Player.self, tableAlias: "p") FROM player p"
public mutating func appendInterpolation<T>(columnsOf record: T.Type, tableAlias: String? = nil)
where T: TableRecord
{
let alias = TableAlias(name: tableAlias ?? T.databaseTableName)
elements.append(contentsOf: T.databaseSelection
.map { CollectionOfOne(.selectable($0.qualifiedSelectable(with: alias))) }
.joined(separator: CollectionOfOne(.sql(", "))))
}
// MARK: - SQLSelectable
/// Appends the selectable SQL.
///
/// // SELECT * FROM player
/// let request: SQLRequest<Player> = """
/// SELECT \(AllColumns()) FROM player
/// """
public mutating func appendInterpolation(_ selection: SQLSelectable) {
public mutating func appendInterpolation<T>(_ selection: T)
where T: SQLSelectable
{
elements.append(.selectable(selection))
}
/// Appends the selectable SQL, or NULL if it is nil.
///
/// // SELECT * FROM player
/// let request: SQLRequest<Player> = """
/// SELECT \(AllColumns()) FROM player
/// """
@_disfavoredOverload
public mutating func appendInterpolation(_ selection: SQLSelectable?) {
if let selection = selection {
elements.append(.selectable(selection))
} else {
appendLiteral("NULL")
}
}
// MARK: - SQLOrderingTerm
/// Appends the ordering SQL.
///
/// // SELECT name FROM player ORDER BY name DESC
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player ORDER BY \(Column("name").desc)
/// """
public mutating func appendInterpolation<T>(_ orderingTerm: T)
where T: SQLOrderingTerm
{
elements.append(.orderingTerm(orderingTerm))
}
/// Appends the ordering SQL.
///
/// // SELECT name FROM player ORDER BY name DESC
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player ORDER BY \(Column("name").desc)
/// """
@_disfavoredOverload
public mutating func appendInterpolation(_ orderingTerm: SQLOrderingTerm) {
elements.append(.orderingTerm(orderingTerm))
}
// MARK: - SQLExpressible
/// Appends the expression SQL.
///
/// // SELECT name FROM player
/// let request: SQLRequest<String> = """
/// SELECT \(Column("name")) FROM player
/// """
public mutating func appendInterpolation<T>(_ expressible: T)
where T: SQLExpressible
{
elements.append(.expression(expressible.sqlExpression))
}
/// Appends the expression SQL.
///
/// // SELECT name FROM player
/// let request: SQLRequest<String> = """
/// SELECT \(Column("name")) FROM player
/// """
public mutating func appendInterpolation(_ expressible: SQLExpressible & SQLSelectable & SQLOrderingTerm) {
elements.append(.expression(expressible.sqlExpression))
}
/// Appends the name of the coding key.
///
/// // SELECT name FROM player
/// let request: SQLRequest<String> = "
/// SELECT \(CodingKey.name) FROM player
/// """
public mutating func appendInterpolation(
_ codingKey: SQLExpressible & SQLSelectable & SQLOrderingTerm & CodingKey)
public mutating func appendInterpolation<T>(_ expressible: T)
where T: SQLExpressible & SQLSelectable & SQLOrderingTerm
{
elements.append(.expression(codingKey.sqlExpression))
elements.append(.expression(expressible.sqlExpression))
}
/// Appends the expression SQL, or NULL if it is nil.
///
/// // SELECT score + ? FROM player
/// let bonus = 1000
/// let request: SQLRequest<Int> = """
/// SELECT score + \(bonus) FROM player
/// // SELECT name FROM player
/// let request: SQLRequest<String> = """
/// SELECT \(Column("name")) FROM player
/// """
///
/// You can also derive literal expressions from other expressions:
///
/// func date(_ value: SQLExpressible) -> SQLExpression {
/// SQLLiteral("DATE(\(value))").sqlExpression
/// }
///
/// // SELECT * FROM player WHERE DATE(createdAt) = '2020-02-25'
/// let request = Player.filter(date(Column("createdAt")) == "2020-02-25")
@_disfavoredOverload
public mutating func appendInterpolation(_ expressible: SQLExpressible?) {
if let expressible = expressible {
elements.append(.expression(expressible.sqlExpression))
@@ -73,25 +156,78 @@ extension SQLInterpolation {
}
}
// MARK: - CodingKey
/// Appends the name of the coding key.
///
/// // SELECT name FROM player
/// let request: SQLRequest<String> = """
/// let request: SQLRequest<String> = "
/// SELECT \(CodingKey.name) FROM player
/// """
public mutating func appendInterpolation(_ codingKey: CodingKey) {
appendInterpolation(Column(codingKey.stringValue))
public mutating func appendInterpolation<T>(_ key: T)
where T: CodingKey
{
appendInterpolation(Column(key.stringValue))
}
// When a value is both an expression and a sequence of expressions,
// favor the expression side. Use case: Foundation.Data interpolation.
/// :nodoc:
public mutating func appendInterpolation<T>(_ expressible: T)
where T: Sequence, T.Element: SQLExpressible, T: SQLExpressible
/// Appends the name of the coding key.
///
/// // SELECT name FROM player
/// let request: SQLRequest<String> = "
/// SELECT \(CodingKey.name) FROM player
/// """
public mutating func appendInterpolation<T>(_ key: T)
where T: CodingKey & SQLExpressible & SQLSelectable & SQLOrderingTerm
{
elements.append(.expression(expressible.sqlExpression))
appendInterpolation(Column(key.stringValue))
}
/// Appends the name of the coding key.
///
/// // SELECT name FROM player
/// let request: SQLRequest<String> = "
/// SELECT \(CodingKey.name) FROM player
/// """
@_disfavoredOverload
public mutating func appendInterpolation(_ key: CodingKey) {
appendInterpolation(Column(key.stringValue))
}
// MARK: - SQLRequestProtocol
/// Appends the request SQL (not wrapped inside parentheses).
///
/// let subquery = Player.select(max(Column("score")))
/// // or
/// let subQuery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
///
/// // SELECT name FROM player WHERE score = (SELECT MAX(score) FROM player)
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE score = (\(subquery))
/// """
public mutating func appendInterpolation<T>(_ request: T)
where T: SQLRequestProtocol
{
elements.append(.subquery(request))
}
/// Appends the request SQL (not wrapped inside parentheses).
///
/// let subquery = Player.select(max(Column("score")))
/// // or
/// let subQuery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
///
/// // SELECT name FROM player WHERE score = (SELECT MAX(score) FROM player)
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE score = (\(subquery))
/// """
@_disfavoredOverload
public mutating func appendInterpolation(_ request: SQLRequestProtocol) {
elements.append(.subquery(request))
}
// MARK: - Sequence
/// Appends a sequence of expressions, wrapped in parentheses.
///
/// // SELECT * FROM player WHERE id IN (?,?,?)
@@ -107,7 +243,9 @@ extension SQLInterpolation {
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE id IN \(ids)
/// """
public mutating func appendInterpolation<S>(_ sequence: S) where S: Sequence, S.Element: SQLExpressible {
public mutating func appendInterpolation<T>(_ sequence: T)
where T: Sequence, T.Element: SQLExpressible
{
appendInterpolation(sequence.lazy.map(\.sqlExpression))
}
@@ -126,7 +264,9 @@ extension SQLInterpolation {
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE a IN \(expressions)
/// """
public mutating func appendInterpolation<S>(_ sequence: S) where S: Sequence, S.Element == SQLExpression {
public mutating func appendInterpolation<T>(_ sequence: T)
where T: Sequence, T.Element == SQLExpression
{
let e: [SQLLiteral.Element] = sequence.map { .expression($0.sqlExpression) }
if e.isEmpty {
appendLiteral("(SELECT NULL WHERE NULL)")
@@ -137,24 +277,12 @@ extension SQLInterpolation {
}
}
/// Appends the ordering SQL.
///
/// // SELECT name FROM player ORDER BY name DESC
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player ORDER BY \(Column("name").desc)
/// """
public mutating func appendInterpolation(_ ordering: SQLOrderingTerm) {
elements.append(.orderingTerm(ordering))
}
/// Appends the request SQL, wrapped in parentheses
///
/// // SELECT name FROM player WHERE score = (SELECT MAX(score) FROM player)
/// let subQuery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE score = \(subQuery)
/// """
public mutating func appendInterpolation<T>(_ request: SQLRequest<T>) {
elements.append(.subQuery(request.sqlLiteral))
// When a value is both an expression and a sequence of expressions,
// favor the expression side. Use case: Foundation.Data interpolation.
/// :nodoc:
public mutating func appendInterpolation<T>(_ expressible: T)
where T: Sequence, T: SQLExpressible, T.Element: SQLExpressible
{
elements.append(.expression(expressible.sqlExpression))
}
}
@@ -115,7 +115,7 @@ extension Database {
unique: unique,
ifNotExists: ifNotExists,
condition: condition?.sqlExpression)
let sql = definition.sql()
let sql = try definition.sql(self)
try execute(sql: sql)
}
@@ -457,7 +457,7 @@ public final class TableDefinition {
for checkExpression in checkConstraints {
var chunks: [String] = []
chunks.append("CHECK (\(checkExpression.quotedSQL()))")
try chunks.append("CHECK (\(checkExpression.quotedSQL(db)))")
items.append(chunks.joined(separator: " "))
}
@@ -470,9 +470,9 @@ public final class TableDefinition {
statements.append(chunks.joined(separator: " "))
}
let indexStatements = columns
let indexStatements = try columns
.compactMap { $0.indexDefinition(in: name) }
.map { $0.sql() }
.map { try $0.sql(db) }
statements.append(contentsOf: indexStatements)
return statements.joined(separator: "; ")
}
@@ -571,7 +571,7 @@ public final class TableAlteration {
statements.append(statement)
if let indexDefinition = column.indexDefinition(in: name) {
statements.append(indexDefinition.sql())
try statements.append(indexDefinition.sql(db))
}
case let .rename(oldName, newName):
var chunks: [String] = []
@@ -884,11 +884,11 @@ public final class ColumnDefinition {
}
for checkConstraint in checkConstraints {
chunks.append("CHECK (\(checkConstraint.quotedSQL()))")
try chunks.append("CHECK (\(checkConstraint.quotedSQL(db)))")
}
if let defaultExpression = defaultExpression {
chunks.append("DEFAULT \(defaultExpression.quotedSQL())")
try chunks.append("DEFAULT \(defaultExpression.quotedSQL(db))")
}
if let collationName = collationName {
@@ -958,7 +958,7 @@ private struct IndexDefinition {
let ifNotExists: Bool
let condition: SQLExpression?
func sql() -> String {
func sql(_ db: Database) throws -> String {
var chunks: [String] = []
chunks.append("CREATE")
if unique {
@@ -976,7 +976,7 @@ private struct IndexDefinition {
)
""")
if let condition = condition {
chunks.append("WHERE \(condition.quotedSQL())")
try chunks.append("WHERE \(condition.quotedSQL(db))")
}
return chunks.joined(separator: " ")
}
@@ -487,7 +487,7 @@ extension TableRecord where Self: EncodableRecord {
where A.OriginRowDecoder == Self
{
let destinationRelation = association.sqlAssociation.destinationRelation(fromOriginRows: { db in
try [Row(PersistenceContainer(db, self))]
try [PersistenceContainer(db, self)]
})
return QueryInterfaceRequest(relation: destinationRelation)
}
@@ -549,7 +549,7 @@ extension TableRecord {
/// Creates a request with *aggregates* appended to the selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.annotated(with: Player.books.count)
public static func annotated(with aggregates: AssociationAggregate<Self>...) -> QueryInterfaceRequest<Self> {
@@ -558,7 +558,7 @@ extension TableRecord {
/// Creates a request with *aggregates* appended to the selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.annotated(with: [Player.books.count])
public static func annotated(with aggregates: [AssociationAggregate<Self>]) -> QueryInterfaceRequest<Self> {
@@ -569,7 +569,7 @@ extension TableRecord {
///
/// // SELECT player.*
/// // FROM player LEFT JOIN book ...
/// // HAVING COUNT(DISTINCT book.rowid) = 0
/// // HAVING COUNT(DISTINCT book.id) = 0
/// var request = Player.all()
/// request = request.having(Player.books.isEmpty)
///
@@ -2,6 +2,12 @@ extension TableRecord {
// MARK: Request Derivation
static var relationForAll: SQLRelation {
SQLRelation(
source: .table(tableName: databaseTableName, alias: nil),
selectionPromise: DatabasePromise(value: databaseSelection))
}
/// Creates a request which fetches all records.
///
/// // SELECT * FROM player
@@ -11,10 +17,7 @@ extension TableRecord {
/// all requests by the `TableRecord.databaseSelection` property, or
/// for individual requests with the `TableRecord.select` method.
public static func all() -> QueryInterfaceRequest<Self> {
let relation = SQLRelation(
source: .table(tableName: databaseTableName, alias: nil),
selection: databaseSelection)
return QueryInterfaceRequest(relation: relation)
QueryInterfaceRequest(relation: relationForAll)
}
/// Creates a request which fetches no record.
@@ -123,6 +126,31 @@ extension TableRecord {
all().select(literal: sqlLiteral, as: type)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Creates a request which selects the primary key of the table.
///
/// For example:
///
/// struct Player: TableRecord { ... }
///
/// let playerIds = dbQueue.read { db in
/// try Player.selectPrimaryKey(as: Int64.self).fetchAll(db)
/// }
///
/// For tables that have no explicit primary key, the request selects the
/// `rowid` column.
///
/// For tables whose primary key spans several columns, the current
/// implementation also returns a request that selects the `rowid` column.
/// Future GRDB versions may return a [row value](https://www.sqlite.org/rowvalue.html).
public static func selectPrimaryKey<RowDecoder>(
as type: RowDecoder.Type = RowDecoder.self)
-> QueryInterfaceRequest<RowDecoder>
{
all().selectPrimaryKey(as: type)
}
/// Creates a request which appends *selection*.
///
/// // SELECT id, email, name FROM player
+2 -2
View File
@@ -320,7 +320,7 @@ extension JSONRequiredEncoder: UnkeyedEncodingContainer {
mutating func superEncoder() -> Encoder { self }
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *)
private var iso8601Formatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = .withInternetDateTime
@@ -342,7 +342,7 @@ extension DatabaseDateEncodingStrategy {
case .secondsSince1970:
return Int64(floor(date.timeIntervalSince1970))
case .iso8601:
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
return iso8601Formatter.string(from: date)
} else {
fatalError("ISO8601DateFormatter is unavailable on this platform.")
+1 -1
View File
@@ -348,7 +348,7 @@ public enum DatabaseDateEncodingStrategy {
case millisecondsSince1970
/// Encodes dates according to the ISO 8601 and RFC 3339 standards
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *)
case iso8601
/// Encodes a String, according to the provided formatter
+21 -18
View File
@@ -45,7 +45,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
throw DecodingError.keyNotFound(
codingKey,
DecodingError.Context(
codingPath: Array(codingPath.dropLast()), // TODO: remove Array initializer when Swift >= 5
codingPath: Array(codingPath.dropLast()),
debugDescription: debugDescription))
}
@@ -53,7 +53,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
guard let key = codingPath.last else {
fatalError("single value decoding from database row is not supported")
}
guard let index = row.index(ofColumn: key.stringValue) else {
guard let index = row.index(forColumn: key.stringValue) else {
// Don't use DecodingError.keyNotFound:
// We need to specifically recognize missing columns in order to
// provide correct feedback.
@@ -73,20 +73,24 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
self.decoder = decoder
}
var allKeys: [Key] {
lazy var allKeys: [Key] = {
let row = decoder.row
return Set(row.columnNames)
.union(Set(row.scopesTree.names))
.union(Set(row.prefetchedRows.keys))
.compactMap { Key(stringValue: $0) }
}
.union(row.scopesTree.names)
.union(row.prefetchedRows.keys)
.compactMap(Key.init(stringValue:))
}()
func contains(_ key: Key) -> Bool {
let row = decoder.row
return row.hasColumn(key.stringValue) || (row.scopesTree[key.stringValue] != nil)
return row.hasColumn(key.stringValue)
|| (row.scopesTree[key.stringValue] != nil)
|| (row.prefetchedRows[key.stringValue] != nil)
}
func decodeNil(forKey key: Key) throws -> Bool {
// Nil is only possible for columns and scopes (optional
// associations), not for prefetched rows.
let row = decoder.row
return row[key.stringValue] == nil && (row.scopesTree[key.stringValue] == nil)
}
@@ -113,7 +117,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
let keyName = key.stringValue
// Column?
if let index = row.index(ofColumn: keyName) {
if let index = row.index(forColumn: keyName) {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
if type == Date.self {
@@ -143,7 +147,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
let keyName = key.stringValue
// Column?
if let index = row.index(ofColumn: keyName) {
if let index = row.index(forColumn: keyName) {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
if type == Date.self {
@@ -196,15 +200,14 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
// Our current strategy is to assume that a missing key (such as
// "book", which is not the name of a column, and not the name of a
// scope) has to be decoded right from the base row.
//
// Yeah, there may be better ways to handle this.
if let decodedRootKey = decodedRootKey {
throw DecodingError.keyNotFound(decodedRootKey, DecodingError.Context(
codingPath: codingPath,
debugDescription: "No such key: \(decodedRootKey.stringValue)")) // TODO: better error message
debugDescription: "No such key: \(decodedRootKey.stringValue)"))
} else {
decodedRootKey = key
return try decode(type, fromRow: row, codingPath: codingPath + [key])
}
decodedRootKey = key
return try decode(type, fromRow: row, codingPath: codingPath + [key])
}
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key)
@@ -409,7 +412,7 @@ private struct MissingColumnError: Error {
var column: String
}
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *)
private var iso8601Formatter: ISO8601DateFormatter = {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = .withInternetDateTime
@@ -458,7 +461,7 @@ extension DatabaseDateDecodingStrategy {
let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index)
return Date(timeIntervalSince1970: timeInterval / 1000.0)
case .iso8601:
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
let string = String(sqliteStatement: sqliteStatement, index: index)
guard let date = iso8601Formatter.date(from: string) else {
fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
@@ -537,7 +540,7 @@ extension DatabaseDateDecodingStrategy {
.fromDatabaseValue(dbValue)
.map { Date(timeIntervalSince1970: $0 / 1000.0) }
case .iso8601:
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
return String
.fromDatabaseValue(dbValue)
.flatMap { iso8601Formatter.date(from: $0) }
+1 -1
View File
@@ -497,7 +497,7 @@ public enum DatabaseDateDecodingStrategy {
case millisecondsSince1970
/// Decodes dates according to the ISO 8601 standards
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *)
case iso8601
/// Decodes a String, according to the provided formatter
+3 -4
View File
@@ -103,7 +103,7 @@ public final class FetchedRecordsController<Record: FetchableRecord> {
where Request: FetchRequest, Request.RowDecoder == Record
{
self.itemsAreIdenticalFactory = itemsAreIdenticalFactory
self.request = ItemRequest(request)
self.request = AnyFetchRequest(request).asRequest(of: Item<Record>.self)
(self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
let region = try request.databaseRegion(db)
let itemsAreIdentical = try itemsAreIdenticalFactory(db)
@@ -166,7 +166,7 @@ public final class FetchedRecordsController<Record: FetchableRecord> {
throws
where Request: FetchRequest, Request.RowDecoder == Record
{
self.request = ItemRequest(request)
self.request = AnyFetchRequest(request).asRequest(of: Item<Record>.self)
(self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
let region = try request.databaseRegion(db)
let itemsAreIdentical = try itemsAreIdenticalFactory(db)
@@ -389,8 +389,7 @@ public final class FetchedRecordsController<Record: FetchableRecord> {
private let itemsAreIdenticalFactory: ItemComparatorFactory<Record>
/// The request
fileprivate typealias ItemRequest = AnyFetchRequest<Item<Record>>
fileprivate var request: ItemRequest
fileprivate var request: AnyFetchRequest<Item<Record>>
/// The observed database region
private var region: DatabaseRegion
+6 -6
View File
@@ -975,9 +975,9 @@ private struct InsertQuery: Hashable {
}
extension InsertQuery {
static let sqlCache = ReadWriteBox(value: [InsertQuery: String]())
@ReadWriteBox private static var sqlCache: [InsertQuery: String] = [:]
var sql: String {
if let sql = InsertQuery.sqlCache.read({ $0[self] }) {
if let sql = Self.sqlCache[self] {
return sql
}
let columnsSQL = insertedColumns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")
@@ -996,7 +996,7 @@ extension InsertQuery {
VALUES (\(valuesSQL))
"""
}
InsertQuery.sqlCache.write { $0[self] = sql }
Self.sqlCache[self] = sql
return sql
}
}
@@ -1012,9 +1012,9 @@ private struct UpdateQuery: Hashable {
}
extension UpdateQuery {
static let sqlCache = ReadWriteBox(value: [UpdateQuery: String]())
@ReadWriteBox private static var sqlCache: [UpdateQuery: String] = [:]
var sql: String {
if let sql = UpdateQuery.sqlCache.read({ $0[self] }) {
if let sql = Self.sqlCache[self] {
return sql
}
let updateSQL = updatedColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: ", ")
@@ -1034,7 +1034,7 @@ extension UpdateQuery {
WHERE \(whereSQL)
"""
}
UpdateQuery.sqlCache.write { $0[self] = sql }
Self.sqlCache[self] = sql
return sql
}
}
+26 -22
View File
@@ -114,28 +114,6 @@ extension TableRecord {
// MARK: - SQL Generation
/// The selection as an SQL String.
///
/// For example:
///
/// struct Player: TableRecord {
/// static let databaseTableName = "player"
/// }
///
/// // SELECT "player".* FROM player
/// let sql = "SELECT \(Player.selectionSQL()) FROM player"
///
/// // SELECT "p".* FROM player AS p
/// let sql = "SELECT \(Player.selectionSQL(alias: "p")) FROM player p"
public static func selectionSQL(alias: String? = nil) -> String {
let alias = TableAlias(tableName: databaseTableName, userName: alias)
let selection = databaseSelection.map { $0.qualifiedSelectable(with: alias) }
var context = SQLGenerationContext.selectionContext
return selection
.map { $0.resultColumnSQL(&context) }
.joined(separator: ", ")
}
/// Returns the number of selected columns.
///
/// For example:
@@ -162,6 +140,32 @@ extension TableRecord {
}
}
extension TableRecord {
// MARK: - Primary Key
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The primary key of the table.
///
/// For example:
///
/// struct Player: TableRecord { ... }
///
/// let player = dbQueue.read { db in
/// try Player.filter(Player.primaryKey == 12).fetchOne(db)
/// }
///
/// For tables that have no explicit primary key, this property returns the
/// `rowid` column.
///
/// For tables whose primary key spans several columns, the current
/// implementation also returns the `rowid` column. Future GRDB versions
/// may return a [row value](https://www.sqlite.org/rowvalue.html).
public static var primaryKey: SQLPrimaryKeyExpression {
SQLPrimaryKeyExpression(tableName: databaseTableName)
}
}
/// Calculating `defaultDatabaseTableName` is somewhat expensive due to the regular expression evaluation
///
/// This cache mitigates the cost of the calculation by storing the name for later retrieval
+13 -10
View File
@@ -1,36 +1,39 @@
import Foundation
/// A LockedBox protects a value with an NSLock.
@propertyWrapper
final class LockedBox<T> {
private var _value: T
private var _wrappedValue: T
private var lock = NSLock()
var value: T {
var wrappedValue: T {
get { read { $0 } }
set { write { $0 = newValue } }
set { update { $0 = newValue } }
}
init(value: T) {
_value = value
var projectedValue: LockedBox<T> { self }
init(wrappedValue: T) {
_wrappedValue = wrappedValue
}
func read<U>(_ block: (T) throws -> U) rethrows -> U {
lock.lock()
defer { lock.unlock() }
return try block(_value)
return try block(_wrappedValue)
}
func write<U>(_ block: (inout T) throws -> U) rethrows -> U {
func update<U>(_ block: (inout T) throws -> U) rethrows -> U {
lock.lock()
defer { lock.unlock() }
return try block(&_value)
return try block(&_wrappedValue)
}
}
extension LockedBox where T: Numeric {
@discardableResult
func increment() -> T {
write { n in
update { n in
n += 1
return n
}
@@ -38,7 +41,7 @@ extension LockedBox where T: Numeric {
@discardableResult
func decrement() -> T {
write { n in
update { n in
n -= 1
return n
}
+5 -7
View File
@@ -47,7 +47,7 @@ final class Pool<T> {
}
private let makeElement: () throws -> T
private var items: ReadWriteBox<[Item]> = ReadWriteBox(value: [])
@ReadWriteBox private var items: [Item] = []
private let itemsSemaphore: DispatchSemaphore // limits the number of elements
private let itemsGroup: DispatchGroup // knows when no element is used
private let barrierQueue: DispatchQueue
@@ -67,7 +67,7 @@ final class Pool<T> {
itemsSemaphore.wait()
itemsGroup.enter()
do {
let item = try items.write { items -> Item in
let item = try $items.update { items -> Item in
if let item = items.first(where: \.isAvailable) {
item.isAvailable = false
return item
@@ -96,7 +96,7 @@ final class Pool<T> {
}
private func release(_ item: Item) {
items.write { _ in
$items.update { _ in
// This is why Item is a class, not a struct: so that we can
// release it without having to find in it the items array.
item.isAvailable = true
@@ -108,7 +108,7 @@ final class Pool<T> {
/// Performs a block on each pool element, available or not.
/// The block is run is some arbitrary dispatch queue.
func forEach(_ body: (T) throws -> Void) rethrows {
try items.read { items in
try $items.read { items in
for item in items {
try body(item.element)
}
@@ -118,9 +118,7 @@ final class Pool<T> {
/// Removes all elements from the pool.
/// Currently used elements won't be reused.
func removeAll() {
items.write {
$0.removeAll()
}
items = []
}
/// Blocks until no element is used, and runs the `barrier` function before
+15 -11
View File
@@ -1,29 +1,33 @@
import Dispatch
/// A ReadWriteBox grants multiple readers and single-writer guarantees on a value.
/// A ReadWriteBox grants multiple readers and single-writer guarantees on a
/// value. It is backed by a concurrent DispatchQueue.
@propertyWrapper
final class ReadWriteBox<T> {
private var _value: T
private var _wrappedValue: T
private var queue: DispatchQueue
var value: T {
var wrappedValue: T {
get { read { $0 } }
set { write { $0 = newValue } }
set { update { $0 = newValue } }
}
init(value: T) {
_value = value
var projectedValue: ReadWriteBox<T> { self }
init(wrappedValue: T) {
_wrappedValue = wrappedValue
queue = DispatchQueue(label: "GRDB.ReadWriteBox", attributes: [.concurrent])
}
func read<U>(_ block: (T) throws -> U) rethrows -> U {
try queue.sync {
try block(_value)
try block(_wrappedValue)
}
}
func write<U>(_ block: (inout T) throws -> U) rethrows -> U {
func update<U>(_ block: (inout T) throws -> U) rethrows -> U {
try queue.sync(flags: [.barrier]) {
try block(&_value)
try block(&_wrappedValue)
}
}
}
@@ -31,7 +35,7 @@ final class ReadWriteBox<T> {
extension ReadWriteBox where T: Numeric {
@discardableResult
func increment() -> T {
write { n in
update { n in
n += 1
return n
}
@@ -39,7 +43,7 @@ extension ReadWriteBox where T: Numeric {
@discardableResult
func decrement() -> T {
write { n in
update { n in
n -= 1
return n
}
+29 -17
View File
@@ -87,6 +87,8 @@
563B071321862C3E00B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */; };
563B071B21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
563B071C21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
563C67B824628C0C00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */; };
563C67B924628C0C00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */; };
563DE4F8231A91F6005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */; };
563DE4F9231A91F6005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */; };
563EF420215F8A76007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF41E215F8A76007DAACD /* OrderedDictionary.swift */; };
@@ -311,8 +313,6 @@
56781B09243F7B5300650A83 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = 56781B06243F7B4B00650A83 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; };
567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; };
567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; };
567DAF1E1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
567DAF211EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
567DAF3C1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
567E4209242AB3CB00CAAD2C /* FailableTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567E4207242AB3CB00CAAD2C /* FailableTestCase.swift */; };
@@ -424,6 +424,8 @@
56C0539D22ACEECD0029D27D /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538F22ACEECD0029D27D /* RemoveDuplicates.swift */; };
56C0539E22ACEECD0029D27D /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538F22ACEECD0029D27D /* RemoveDuplicates.swift */; };
56C7A6AE1D2DFF6100EFB0C2 /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; };
56C9EB9B2495324700FE5D55 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 56C9EB9A2495324700FE5D55 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
56C9EB9C2495324700FE5D55 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 56C9EB9A2495324700FE5D55 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
56CC9234201E009000CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */; };
56CC9235201E009100CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */; };
56CC923B201E033400CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */; };
@@ -464,8 +466,12 @@
56ED8A801DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */; };
56F3E74C1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
56F3E7501E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
56F409282465C8F500A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409262465C8F500A7A152 /* SQLRequestProtocol.swift */; };
56F409292465C8F500A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409262465C8F500A7A152 /* SQLRequestProtocol.swift */; };
56FBFED62210731100945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED52210731000945324 /* SQLRequest.swift */; };
56FBFED72210731100945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED52210731000945324 /* SQLRequest.swift */; };
56FEB8FE248403270081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */; };
56FEB8FF248403270081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */; };
56FEE7FE1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; };
56FEE8021F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; };
56FF45431D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; };
@@ -776,6 +782,7 @@
563B0701218627DE00B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = "<group>"; };
563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = "<group>"; };
563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = "<group>"; };
563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = "<group>"; };
563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = "<group>"; };
563EF41E215F8A76007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = "<group>"; };
563EF441216131F5007DAACD /* AssociationAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationAggregateTests.swift; sourceTree = "<group>"; };
@@ -898,7 +905,6 @@
5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = "<group>"; };
56781B06243F7B4B00650A83 /* GRDB-Bridging.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "GRDB-Bridging.h"; path = "SQLiteCustom/GRDB-Bridging.h"; sourceTree = "<group>"; };
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.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>"; };
567E4207242AB3CB00CAAD2C /* FailableTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FailableTestCase.swift; sourceTree = "<group>"; };
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
@@ -987,7 +993,6 @@
56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = "<group>"; };
56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = "<group>"; };
56B86E6E220FF4C800524C16 /* SQLLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLLiteralTests.swift; sourceTree = "<group>"; };
56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDB.xcconfig; sourceTree = "<group>"; };
56B9649C1DA51B4C0002DA19 /* FTS5.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5.swift; sourceTree = "<group>"; };
56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TokenizerDescriptor.swift; sourceTree = "<group>"; };
56B964B81DA51D0A0002DA19 /* FTS5Pattern.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5Pattern.swift; sourceTree = "<group>"; };
@@ -1001,9 +1006,8 @@
56C0538E22ACEECD0029D27D /* Map.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = "<group>"; };
56C0538F22ACEECD0029D27D /* RemoveDuplicates.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RemoveDuplicates.swift; sourceTree = "<group>"; };
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSavepointTests.swift; sourceTree = "<group>"; };
56C48E731C9A9923005DF1D9 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = "<group>"; };
56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDBDeploymentTarget.xcconfig; sourceTree = "<group>"; };
56C494421ED726C500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = GRDBDeploymentTarget.xcconfig; path = SQLiteCustom/GRDBDeploymentTarget.xcconfig; sourceTree = "<group>"; };
56C9EB9A2495324700FE5D55 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = grdb_config.h; path = SQLiteCustom/grdb_config.h; sourceTree = "<group>"; };
56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropWhileCursorTests.swift; sourceTree = "<group>"; };
56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = "<group>"; };
56CC9248201E058900CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = "<group>"; };
@@ -1031,8 +1035,10 @@
56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizerTests.swift; sourceTree = "<group>"; };
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = "<group>"; };
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = "<group>"; };
56F409262465C8F500A7A152 /* SQLRequestProtocol.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestProtocol.swift; sourceTree = "<group>"; };
56FBFED52210731000945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = "<group>"; };
56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.swift; sourceTree = "<group>"; };
56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = "<group>"; };
56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = "<group>"; };
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = "<group>"; };
@@ -1156,6 +1162,7 @@
560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */,
569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */,
56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */,
563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */,
);
name = DatabasePool;
sourceTree = "<group>";
@@ -1552,6 +1559,7 @@
566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */,
564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */,
56A238131B9C74A90082EB20 /* DatabaseTests.swift */,
56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */,
5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */,
56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */,
56A238191B9C74A90082EB20 /* DatabaseValueConvertible */,
@@ -1662,6 +1670,7 @@
56E9FAC32210468500C703A8 /* SQLInterpolation.swift */,
56E9FAD42210538400C703A8 /* SQLLiteral.swift */,
56FBFED52210731000945324 /* SQLRequest.swift */,
56F409262465C8F500A7A152 /* SQLRequestProtocol.swift */,
56A238781B9C75030082EB20 /* Statement.swift */,
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
@@ -1809,13 +1818,9 @@
DC37743319C8CFCE004FCF85 /* Supporting Files */ = {
isa = PBXGroup;
children = (
567DAF141EAB61ED00FC0928 /* grdb_config.h */,
DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */,
DC3773F819C8CBB3004FCF85 /* GRDB.h */,
56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */,
56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */,
DC3773F719C8CBB3004FCF85 /* Info.plist */,
56C48E731C9A9923005DF1D9 /* module.modulemap */,
);
name = "Supporting Files";
path = ../Support;
@@ -1833,15 +1838,16 @@
F3BA7FED1CFB21F8003DC1BA /* GRDBCustomSQLite */ = {
isa = PBXGroup;
children = (
EED476F41CFD174D0026A4EC /* Customize */,
56C9EB9A2495324700FE5D55 /* grdb_config.h */,
56781B06243F7B4B00650A83 /* GRDB-Bridging.h */,
F3BA7FF11CFB23D3003DC1BA /* GRDB.h */,
F3BA7FF01CFB23C9003DC1BA /* sqlite3.h */,
F3BA7FEF1CFB23BF003DC1BA /* module.modulemap */,
F3BA7FEE1CFB23B7003DC1BA /* GRDB.xcconfig */,
F3BA813B1CFB3770003DC1BA /* GRDBCustomSQLite-Testing.xcconfig */,
56C494421ED726C500CC72AF /* GRDBDeploymentTarget.xcconfig */,
F3BA7FEF1CFB23BF003DC1BA /* module.modulemap */,
F3BA7FF01CFB23C9003DC1BA /* sqlite3.h */,
F3BA7FF11CFB23D3003DC1BA /* GRDB.h */,
56781B06243F7B4B00650A83 /* GRDB-Bridging.h */,
F3BA7FF31CFB23E4003DC1BA /* SQLiteLib.xcodeproj */,
EED476F41CFD174D0026A4EC /* Customize */,
);
name = GRDBCustomSQLite;
sourceTree = "<group>";
@@ -1862,9 +1868,9 @@
buildActionMask = 2147483647;
files = (
F3BA80381CFB2932003DC1BA /* GRDB.h in Headers */,
56C9EB9C2495324700FE5D55 /* grdb_config.h in Headers */,
56781B09243F7B5300650A83 /* GRDB-Bridging.h in Headers */,
F3BA803A1CFB293A003DC1BA /* sqlite3.h in Headers */,
567DAF211EAB61ED00FC0928 /* grdb_config.h in Headers */,
EED476F31CFD172C0026A4EC /* GRDBCustomSQLite-USER.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -1874,9 +1880,9 @@
buildActionMask = 2147483647;
files = (
F3BA80931CFB2F13003DC1BA /* GRDB.h in Headers */,
56C9EB9B2495324700FE5D55 /* grdb_config.h in Headers */,
56781B08243F7B5300650A83 /* GRDB-Bridging.h in Headers */,
F3BA80951CFB2F18003DC1BA /* sqlite3.h in Headers */,
567DAF1E1EAB61ED00FC0928 /* grdb_config.h in Headers */,
EED476F21CFD17270026A4EC /* GRDBCustomSQLite-USER.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -2190,6 +2196,7 @@
5656A87E2295BD56001FF3FF /* SQLAssociation.swift in Sources */,
F3BA80131CFB2876003DC1BA /* DatabaseValue.swift in Sources */,
56C0539822ACEECD0029D27D /* ValueReducer.swift in Sources */,
56F409292465C8F500A7A152 /* SQLRequestProtocol.swift in Sources */,
56A2FA3A24424F4200E97D23 /* Export.swift in Sources */,
56B964B61DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
F3BA80171CFB2876003DC1BA /* RowAdapter.swift in Sources */,
@@ -2313,6 +2320,7 @@
56B14E861D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */,
566AD8CD1D531BEE002EC1A8 /* TableDefinitionTests.swift in Sources */,
5653EB7B20961FB200F46237 /* AssociationParallelRowScopesTests.swift in Sources */,
563C67B924628C0C00E94EDC /* DatabasePoolTests.swift in Sources */,
5698AC871DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */,
F3BA80D11CFB2FF3003DC1BA /* MutablePersistableRecordTests.swift in Sources */,
5653EB7320961FB200F46237 /* AssociationHasOneSQLTests.swift in Sources */,
@@ -2383,6 +2391,7 @@
567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */,
5674A7291F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */,
56057C5A2291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */,
56FEB8FF248403270081AF83 /* DatabaseTraceTests.swift in Sources */,
56FEE8021F47253700D930EA /* TableRecordTests.swift in Sources */,
F3BA81211CFB3063003DC1BA /* RecordPrimaryKeyNoneTests.swift in Sources */,
F3BA80F71CFB3021003DC1BA /* SelectStatementTests.swift in Sources */,
@@ -2525,6 +2534,7 @@
5656A87D2295BD56001FF3FF /* SQLAssociation.swift in Sources */,
F3BA806F1CFB2E55003DC1BA /* DatabaseValue.swift in Sources */,
56C0539722ACEECD0029D27D /* ValueReducer.swift in Sources */,
56F409282465C8F500A7A152 /* SQLRequestProtocol.swift in Sources */,
56A2FA3924424F4200E97D23 /* Export.swift in Sources */,
56B964B31DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
F3BA80731CFB2E55003DC1BA /* RowAdapter.swift in Sources */,
@@ -2648,6 +2658,7 @@
F3BA81301CFB3064003DC1BA /* RecordPrimaryKeyRowIDTests.swift in Sources */,
56DAA2D51DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */,
5653EB7A20961FB200F46237 /* AssociationParallelRowScopesTests.swift in Sources */,
563C67B824628C0C00E94EDC /* DatabasePoolTests.swift in Sources */,
F3BA80FB1CFB3021003DC1BA /* StatementArgumentsTests.swift in Sources */,
F3BA80EE1CFB3017003DC1BA /* RowAdapterTests.swift in Sources */,
5653EB7220961FB200F46237 /* AssociationHasOneSQLTests.swift in Sources */,
@@ -2718,6 +2729,7 @@
F3BA80FA1CFB3021003DC1BA /* SelectStatementTests.swift in Sources */,
5674A7271F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */,
56057C592291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */,
56FEB8FE248403270081AF83 /* DatabaseTraceTests.swift in Sources */,
56FEE7FE1F47253700D930EA /* TableRecordTests.swift in Sources */,
F3BA81191CFB305F003DC1BA /* QueryInterfaceRequestTests.swift in Sources */,
F3BA812F1CFB3064003DC1BA /* RecordPrimaryKeyNoneTests.swift in Sources */,
+19 -12
View File
@@ -49,11 +49,18 @@ endif
TEST_ACTIONS = clean build build-for-testing test-without-building
# When adding support for an Xcode version, look for available devices with `instruments -s devices`
ifeq ($(XCODEVERSION),11.4)
ifeq ($(XCODEVERSION),11.5)
MAX_SWIFT_VERSION = 5.2
MIN_SWIFT_VERSION = # MAX_SWIFT_VERSION is the minimum supported Swift version
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=13.4"
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5,OS=10.3.1"
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=13.5"
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=10.3.1"
MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=13.4"
MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=10.2"
else ifeq ($(XCODEVERSION),11.4)
MAX_SWIFT_VERSION = 5.2
MIN_SWIFT_VERSION = # MAX_SWIFT_VERSION is the minimum supported Swift version
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=13.4.1"
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=10.3.1"
MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=13.4"
MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=10.2"
else
@@ -108,7 +115,7 @@ test_framework_GRDBOSX_maxSwift:
-scheme GRDBOSX \
SWIFT_VERSION=$(MAX_SWIFT_VERSION) \
'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \
$(TEST_ACTIONS) \
$(XCPRETTY)
@@ -119,7 +126,7 @@ ifdef MIN_SWIFT_VERSION
-scheme GRDBOSX \
SWIFT_VERSION=$(MIN_SWIFT_VERSION) \
'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \
$(TEST_ACTIONS) \
$(XCPRETTY)
endif
@@ -143,7 +150,7 @@ test_framework_GRDBiOS_maxTarget_maxSwift:
-destination $(MAX_IOS_DESTINATION) \
SWIFT_VERSION=$(MAX_SWIFT_VERSION) \
'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \
$(TEST_ACTIONS) \
$(XCPRETTY)
@@ -155,7 +162,7 @@ ifdef MIN_SWIFT_VERSION
-destination $(MAX_IOS_DESTINATION) \
SWIFT_VERSION=$(MIN_SWIFT_VERSION) \
'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \
$(TEST_ACTIONS) \
$(XCPRETTY)
endif
@@ -179,7 +186,7 @@ test_framework_GRDBtvOS_maxTarget_maxSwift:
-destination $(MAX_TVOS_DESTINATION) \
SWIFT_VERSION=$(MAX_SWIFT_VERSION) \
'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \
$(TEST_ACTIONS) \
$(XCPRETTY)
@@ -191,7 +198,7 @@ ifdef MIN_SWIFT_VERSION
-destination $(MAX_TVOS_DESTINATION) \
SWIFT_VERSION=$(MIN_SWIFT_VERSION) \
'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \
$(TEST_ACTIONS) \
$(XCPRETTY)
endif
@@ -387,10 +394,10 @@ ifdef JAZZY
--author 'Gwendal Roué' \
--author_url https://github.com/groue \
--github_url https://github.com/groue/GRDB.swift \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v4.14.0 \
--module-version 4.14.0 \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.0.0-beta.5 \
--module-version 5.0.0-beta.5 \
--module GRDB \
--root-url http://groue.github.io/GRDB.swift/docs/4.14/ \
--root-url http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/ \
--output Documentation/Reference \
--xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS
else
+1 -1
View File
@@ -6,7 +6,7 @@ import PackageDescription
let package = Package(
name: "GRDB",
platforms: [
.iOS("9.0"),
.iOS("10.0"),
.macOS("10.10"),
.tvOS("9.0"),
.watchOS("2.0"),
+396 -654
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,4 +1,4 @@
IPHONEOS_DEPLOYMENT_TARGET = 9.0
IPHONEOS_DEPLOYMENT_TARGET = 10.0
MACOSX_DEPLOYMENT_TARGET = 10.10
TVOS_DEPLOYMENT_TARGET = 9.0
WATCHOS_DEPLOYMENT_TARGET = 2.0
+91
View File
@@ -0,0 +1,91 @@
#ifndef grdb_config_h
#define grdb_config_h
typedef void(*errorLogCallback)(void *pArg, int iErrCode, const char *zMsg);
/// Wrapper around sqlite3_config(SQLITE_CONFIG_LOG, ...) which is a variadic
/// function that can't be used from Swift.
static inline void registerErrorLogCallback(errorLogCallback callback) {
sqlite3_config(SQLITE_CONFIG_LOG, callback, 0);
}
#if SQLITE_VERSION_NUMBER >= 3029000
/// Wrapper around sqlite3_db_config() which is a variadic function that can't
/// be used from Swift.
static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) {
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 0, (void *)0);
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 0, (void *)0);
}
/// Wrapper around sqlite3_db_config() which is a variadic function that can't
/// be used from Swift.
static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) {
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 1, (void *)0);
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 1, (void *)0);
}
#else
static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { }
static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { }
#endif
/*
Snapshots
=========
We have a linker/C-interop difficulty here:
- Not all SQLite versions ship with the sqlite3_snapshot_get function.
- Not all iOS/macOS versions ship a <sqlite3.h> header that contains
the declaration for sqlite3_snapshot_get(), even when SQLite is
actually compiled with SQLITE_ENABLE_SNAPSHOT.
This makes it really difficult to deal with system SQLite, custom
SQLite builds, SQLCipher, and SPM.
To avoid those problems, we add grdb_snapshot_xxx shim functions in the
following header files:
- SQLiteCustom/grdb_config.h
- Sources/CSQLite/shim.h
- Support/grdb_config.h
*/
#ifdef SQLITE_ENABLE_SNAPSHOT
static inline int grdb_snapshot_get(
sqlite3 *db,
const char *zSchema,
sqlite3_snapshot **ppSnapshot)
{
return sqlite3_snapshot_get(db, zSchema, ppSnapshot);
}
static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) {
sqlite3_snapshot_free(ppSnapshot);
}
static inline int grdb_snapshot_cmp(
sqlite3_snapshot *p1,
sqlite3_snapshot *p2)
{
return sqlite3_snapshot_cmp(p1, p2);
}
#else
static inline int grdb_snapshot_get(
sqlite3 *db,
const char *zSchema,
sqlite3_snapshot **ppSnapshot)
{
return SQLITE_MISUSE;
}
static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) {
}
static inline int grdb_snapshot_cmp(
sqlite3_snapshot *p1,
sqlite3_snapshot *p2)
{
return 0;
}
#endif /* SQLITE_ENABLE_SNAPSHOT */
#endif /* grdb_config_h */
+79
View File
@@ -26,3 +26,82 @@ static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) {
static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { }
static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { }
#endif
/*
Snapshots
=========
We have a linker/C-interop difficulty here:
- Not all SQLite versions ship with the sqlite3_snapshot_get function.
- Not all iOS/macOS versions ship a <sqlite3.h> header that contains
the declaration for sqlite3_snapshot_get(), even when SQLite is
actually compiled with SQLITE_ENABLE_SNAPSHOT.
This makes it really difficult to deal with system SQLite, custom
SQLite builds, SQLCipher, and SPM.
To avoid those problems, we add grdb_snapshot_xxx shim functions in the
following header files:
- SQLiteCustom/grdb_config.h
- Sources/CSQLite/shim.h
- Support/grdb_config.h
*/
#ifdef SQLITE_ENABLE_SNAPSHOT
static inline int grdb_snapshot_get(
sqlite3 *db,
const char *zSchema,
sqlite3_snapshot **ppSnapshot)
{
return sqlite3_snapshot_get(db, zSchema, ppSnapshot);
}
static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) {
sqlite3_snapshot_free(ppSnapshot);
}
static inline int grdb_snapshot_cmp(
sqlite3_snapshot *p1,
sqlite3_snapshot *p2)
{
return sqlite3_snapshot_cmp(p1, p2);
}
#else
// Assume snapshot apis *are* defined, but not exposed.
typedef struct sqlite3_snapshot {
unsigned char hidden[48];
} sqlite3_snapshot;
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
sqlite3 *db,
const char *zSchema,
sqlite3_snapshot **ppSnapshot
);
SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
sqlite3_snapshot *p1,
sqlite3_snapshot *p2
);
static inline int grdb_snapshot_get(
sqlite3 *db,
const char *zSchema,
sqlite3_snapshot **ppSnapshot)
{
return sqlite3_snapshot_get(db, zSchema, ppSnapshot);
}
static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) {
sqlite3_snapshot_free(ppSnapshot);
}
static inline int grdb_snapshot_cmp(
sqlite3_snapshot *p1,
sqlite3_snapshot *p2)
{
return sqlite3_snapshot_cmp(p1, p2);
}
#endif /* SQLITE_ENABLE_SNAPSHOT */
Loaded 100 of 174 files, more files were not shown because too many files have changed in this diff. Show more