Compare commits

...
Author SHA1 Message Date
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
148 changed files with 5462 additions and 3803 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
+111 -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)
#### 4.x Releases
@@ -76,14 +74,112 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
## Next Release
-->
## GRDB5 Branch
## 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
- 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.
- 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 +204,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).
+16 -16
View File
@@ -1830,7 +1830,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 +1923,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 +1942,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 +1961,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 +1999,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 +2020,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 +2040,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 +2065,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 +2101,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 +2183,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 +2218,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 +2258,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 +2422,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
@@ -19,7 +19,7 @@ struct AppDatabase {
/// The DatabaseMigrator that defines the database schema.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#migrations
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md
static var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
+6 -6
View File
@@ -6,26 +6,26 @@ 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 define a simple [Codable Record](../../../README.md#codable-records)
- how to track database changes and animate a table view with [ValueObservation](../../../README.md#valueobservation).
**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` defines the database for the whole application. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema.
- [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).
- [PlayersViewController.swift](GRDBDemoiOS/PlayersViewController.swift)
`PlayersViewController` displays a list of players. It keeps its view up-to-date with [ValueObservation](../../README.md#valueobservation).
`PlayersViewController` displays a list of players. It keeps its view up-to-date with [ValueObservation](../../../README.md#valueobservation).
- [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.3/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.3/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
+94 -27
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)
@@ -293,7 +293,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 +318,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 +393,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 +409,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 +424,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 +432,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.3/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
+288
View File
@@ -0,0 +1,288 @@
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.
## 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
+2 -2
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.3'
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'
+26
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 */,
@@ -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 */,
+4 -8
View File
@@ -63,11 +63,6 @@ public struct Configuration {
/// The default 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 +159,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).
///
@@ -215,6 +214,3 @@ public struct Configuration {
}
}
}
/// A tracing function that takes an SQL string.
public typealias TraceFunction = (String) -> Void
+2 -2
View File
@@ -353,14 +353,14 @@ extension Database {
}
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)
}
}
+238 -74
View File
@@ -144,7 +144,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 +153,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
@@ -200,8 +200,6 @@ 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()
setupDoubleQuotedStringLiterals()
try setupForeignKeys()
setupBusyMode()
@@ -222,69 +220,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 +236,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 +266,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)
@@ -550,6 +488,128 @@ public final class Database {
return try block()
}
// MARK: - Trace
/// 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: - Checkpoints
func checkpoint(_ kind: Database.CheckpointMode) throws {
@@ -593,7 +653,7 @@ public final class Database {
///
/// Suspension ends with resume().
func suspend() {
isSuspended.write { isSuspended in
$isSuspended.update { isSuspended in
if isSuspended {
return
}
@@ -620,9 +680,7 @@ public final class Database {
///
/// See suspend().
func resume() {
isSuspended.write { isSuspended in
isSuspended = false
}
isSuspended = false
}
/// Support for checkForSuspensionViolation(from:)
@@ -650,7 +708,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 +1363,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`
+10 -4
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) {
@@ -1025,7 +1031,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)
}
}
+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)
}
}
+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
}
}
+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))
@@ -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 {
+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)
}
+65 -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
@@ -134,12 +149,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 +177,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 +188,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 +243,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 +259,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 +272,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 +285,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 +296,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 +309,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 +343,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.")
+35 -19
View File
@@ -170,8 +170,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 +182,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 +220,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 +242,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,181 @@
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 = DatabasePromise<SQLExpression> { db in
let primaryKey = try db.primaryKeyExpression(self.databaseTableName)
return SQLExpressionCountDistinct(primaryKey)
}
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 = DatabasePromise<SQLExpression> { db in
let primaryKey = try db.primaryKeyExpression(self.databaseTableName)
return SQLExpressionIsEmpty(SQLExpressionCountDistinct(primaryKey))
}
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 +200,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 +211,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 +271,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 +306,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 +319,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 +329,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 +339,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 +353,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 +363,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 +373,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 +388,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 +401,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 +414,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 +423,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 +432,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 +445,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 +458,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 +471,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 +480,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 +489,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 +502,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 +515,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 +528,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 +541,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 +554,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 +567,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 +582,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 +595,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 +608,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 +621,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 +634,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 +647,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 +660,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 +673,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 +686,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 +699,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 +712,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 +725,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 +736,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 +749,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 +762,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 +775,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 +788,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 +801,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 +814,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 +827,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 +840,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 +853,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 +866,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 +879,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 +892,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 +905,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,19 @@ 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) }
}
}
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 +207,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 +250,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 +289,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 +337,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 +377,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 +394,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 +424,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 +473,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 +512,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 +521,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 +554,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 +563,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 +589,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)
"""
+51 -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 {
@@ -141,3 +169,22 @@ struct SQLExpressionNot: SQLExpression {
SQLExpressionNot(expression.qualifiedExpression(with: alias))
}
}
// MARK: -
extension Database {
/// Returns an expression for the primary key of this table.
///
/// When the table as a primary key made of several columns, we return
/// the rowid column. Eventually we'll support
/// [row values](https://www.sqlite.org/rowvalue.html) and be able to deal
/// with WITHOUT ROWID tables.
func primaryKeyExpression(_ tableName: String) throws -> SQLExpression {
let columns = try primaryKey(tableName).columns
if columns.count == 1 {
return Column(columns[0])
} else {
return Column.rowID
}
}
}
+3 -3
View File
@@ -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,7 +209,7 @@ 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)
}
+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)
}
}
+123 -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)`.
@@ -175,27 +184,52 @@ struct SQLRelation {
}
}
}
/// Returns nil if there is no way to express the primary key of the
/// relation as an expression.
func primaryKeyExpression(_ db: Database) throws -> SQLExpression? {
switch source {
case .subquery:
// No primary key for subquery
return nil
case let .table(tableName: tableName, alias: _):
return try db.primaryKeyExpression(tableName)
}
}
}
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 +288,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 +403,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 +415,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 +583,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 +596,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 +641,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 +653,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 +709,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 +730,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 = try db.primaryKeyExpression(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 = try db.primaryKeyExpression(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.
+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
}
}
-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:
+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
}
+18
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 */; };
@@ -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>"; };
@@ -1031,8 +1038,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 +1165,7 @@
560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */,
569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */,
56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */,
563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */,
);
name = DatabasePool;
sourceTree = "<group>";
@@ -1552,6 +1562,7 @@
566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */,
564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */,
56A238131B9C74A90082EB20 /* DatabaseTests.swift */,
56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */,
5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */,
56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */,
56A238191B9C74A90082EB20 /* DatabaseValueConvertible */,
@@ -1662,6 +1673,7 @@
56E9FAC32210468500C703A8 /* SQLInterpolation.swift */,
56E9FAD42210538400C703A8 /* SQLLiteral.swift */,
56FBFED52210731000945324 /* SQLRequest.swift */,
56F409262465C8F500A7A152 /* SQLRequestProtocol.swift */,
56A238781B9C75030082EB20 /* Statement.swift */,
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
@@ -2190,6 +2202,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 +2326,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 +2397,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 +2540,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 +2664,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 +2735,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 */,
+5 -5
View File
@@ -52,8 +52,8 @@ TEST_ACTIONS = clean build build-for-testing test-without-building
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"
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5,OS=10.3.1"
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
@@ -387,10 +387,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.3 \
--module-version 5.0.0-beta.3 \
--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.3/ \
--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"),
+167 -635
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
+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
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>4.14.0</string>
<string>5.0.0-beta.3</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+6 -9
View File
@@ -6,27 +6,25 @@
- [ ] deprecate ScopeAdapter(base, scopes), because base.addingScopes has a better implementation
- [ ] https://github.com/groue/GRDB.swift/issues/514
- [ ] Test NOT TESTED methods
- [ ] Cancellation of a started ValueObservation. Context: https://github.com/groue/GRDB.swift/issues/601#issuecomment-524733140
- [ ] Remove submodules
- [ ] map keypath cleanup
## Documentation
- [ ] Document that creating "too many" ValueObservation increases database contention. This also applies to database pools, because when observations create reader contention, they also create writer contention. Context: https://github.com/groue/GRDB.swift/issues/601#issuecomment-524615772
- [ ] Enhance the introduction to SQLRequest, based on the feedback in https://github.com/groue/GRDB.swift/issues/617
- [ ] Association: document how to use aggregates with inner join (testAnnotatedWithHasManyDefaultMaxJoiningRequired)
- [ ] Association: document ordered vs. non-ordered hasMany and hasManyThrough associations
## Features
- [ ] Extract one row from a hasMany association (the one with the maximum date, the one with a flag set, etc.) https://stackoverflow.com/questions/43188771/sqlite-join-query-most-recent-posts-by-each-user
- [ ] Access the database label from the tracing function
- [ ] Subqueries: request.isEmpty / request.exists
- [ ] Subqueries: request.count
- [ ] Extract one row from a hasMany association (the one with the maximum date, the one with a flag set, etc.) https://stackoverflow.com/questions/43188771/sqlite-join-query-most-recent-posts-by-each-user (failed PR: https://github.com/groue/GRDB.swift/pull/767)
- [ ] Turn a hasMany to hasOne without first/last : hasMany(Book.self).filter(Column("isBest") /* assume a single book is flagged best */).asOne()
- [ ] Support for more kinds of joins: https://github.com/groue/GRDB.swift/issues/740
- [ ] Delay SQL generation of SQLLiteral and SQLRequest: https://github.com/groue/GRDB.swift/issues/697
- [ ] HasAndBelongsToMany: https://github.com/groue/GRDB.swift/issues/711
- [ ] Close the loophole when decoding root property: https://github.com/groue/GRDB.swift/issues/664
- [ ] Support UNION https://github.com/groue/GRDB.swift/issues/671
- [ ] Support Subqueries: WHERE EXISTS (SELECT ...)
- [ ] request.exists(db) as an alternative to fetchOne(db) != nil. Can generate optimized SQL.
- [ ] Measure the duration of transactions
- [ ] Improve SQL generation for `Player.....fetchCount(db)`, especially with distinct. Try to avoid `SELECT COUNT(*) FROM (SELECT DISTINCT player.* ...)`
@@ -44,7 +42,6 @@
- [ ] Decode NSDecimalNumber from text database values
- [ ] Check https://sqlite.org/sqlar.html
- [ ] FTS: prefix queries
- [ ] A way to stop a ValueObservation observer without waiting for deinit
- [ ] More schema alterations
- [ ] DatabasePool.databaseSchemaIsLocked = true (should forbid schema changes, and never reset dbPool readers' caches). Or can we invalidate reader's cache automatically from the writer connection?
- [ ] Database.clearSchemaCache() is fine, but what about dbPool readers? Can we invalidate the cache for a whole pool?
+1 -1
View File
@@ -1,6 +1,6 @@
use_frameworks!
target 'iOS'
platform :ios, '9.0'
platform :ios, '10.0'
pod 'GRDB.swift', :path => '../../..'
post_install do |installer|
@@ -251,7 +251,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
IPHONEOS_DEPLOYMENT_TARGET = 10.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
@@ -301,7 +301,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
IPHONEOS_DEPLOYMENT_TARGET = 10.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
+1 -1
View File
@@ -1,5 +1,5 @@
target 'iOS'
platform :ios, '9.0'
platform :ios, '10.0'
pod 'GRDB.swift', :path => '../../..'
post_install do |installer|
@@ -232,7 +232,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
IPHONEOS_DEPLOYMENT_TARGET = 10.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
@@ -282,7 +282,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 9.0;
IPHONEOS_DEPLOYMENT_TARGET = 10.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_COMPILATION_MODE = wholemodule;
@@ -15,6 +15,8 @@
56057C692291D0AC00A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56057C672291D0AB00A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */; };
560714F0227DD1810091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714EF227DD1810091BB10 /* AssociationPrefetchingSQLTests.swift */; };
560714F1227DD1810091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714EF227DD1810091BB10 /* AssociationPrefetchingSQLTests.swift */; };
561017D22462968600317275 /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561017D12462968600317275 /* DatabasePoolTests.swift */; };
561017D32462968600317275 /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561017D12462968600317275 /* DatabasePoolTests.swift */; };
561CFA8323735092000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA8223735091000C8BAA /* MutablePersistableRecordUpdateTests.swift */; };
561CFA8423735092000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA8223735091000C8BAA /* MutablePersistableRecordUpdateTests.swift */; };
561CFAAE2376EFBE000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAAC2376EFBD000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; };
@@ -23,8 +25,6 @@
561CFAB12376EFBE000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAAD2376EFBE000C8BAA /* AssociationHasManyOrderingTests.swift */; };
563DE4FB231A9212005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FA231A9212005081B7 /* DatabaseConfigurationTests.swift */; };
563DE4FC231A9212005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4FA231A9212005081B7 /* DatabaseConfigurationTests.swift */; };
563F4CBA242F801A0052E96C /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563F4CB9242F801A0052E96C /* ValueObservationRecordTests.swift */; };
563F4CBB242F801A0052E96C /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563F4CB9242F801A0052E96C /* ValueObservationRecordTests.swift */; };
564A1FDE226B89E1001F64F1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F27226B89CE001F64F1 /* MutablePersistableRecordDeleteTests.swift */; };
564A1FDF226B89E1001F64F1 /* AssociationHasOneThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F28226B89CE001F64F1 /* AssociationHasOneThroughRowScopeTests.swift */; };
564A1FE0226B89E1001F64F1 /* RowCopiedFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F29226B89CF001F64F1 /* RowCopiedFromStatementTests.swift */; };
@@ -413,6 +413,7 @@
56057C5E2291B8E400A7CB10 /* AssociationHasManyRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyRowScopeTests.swift; sourceTree = "<group>"; };
56057C672291D0AB00A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughRowScopeTests.swift; sourceTree = "<group>"; };
560714EF227DD1810091BB10 /* AssociationPrefetchingSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingSQLTests.swift; sourceTree = "<group>"; };
561017D12462968600317275 /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = "<group>"; };
561CFA8223735091000C8BAA /* MutablePersistableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordUpdateTests.swift; sourceTree = "<group>"; };
561CFAAC2376EFBD000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = "<group>"; };
561CFAAD2376EFBE000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = "<group>"; };
@@ -718,6 +719,7 @@
564A1F82226B89D7001F64F1 /* DatabasePoolReadOnlyTests.swift */,
564A1F62226B89D4001F64F1 /* DatabasePoolReleaseMemoryTests.swift */,
564A1F78226B89D6001F64F1 /* DatabasePoolSchemaCacheTests.swift */,
561017D12462968600317275 /* DatabasePoolTests.swift */,
564A1F2B226B89CF001F64F1 /* DatabaseQueueBackupTests.swift */,
564A1FB1226B89DC001F64F1 /* DatabaseQueueConcurrencyTests.swift */,
564A1F2F226B89CF001F64F1 /* DatabaseQueueInMemoryTests.swift */,
@@ -931,7 +933,7 @@
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 1020;
LastUpgradeCheck = 1100;
LastUpgradeCheck = 1150;
TargetAttributes = {
564A1F1C226B876D001F64F1 = {
CreatedOnToolsVersion = 10.2.1;
@@ -1126,7 +1128,7 @@
564A202E226B89E1001F64F1 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
564A2078226B89E1001F64F1 /* ForeignKeyInfoTests.swift in Sources */,
564A2050226B89E1001F64F1 /* RecordPrimaryKeySingleTests.swift in Sources */,
563F4CBA242F801A0052E96C /* ValueObservationRecordTests.swift in Sources */,
561017D22462968600317275 /* DatabasePoolTests.swift in Sources */,
564A2091226B89E1001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */,
5676FBB022F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */,
564A208F226B89E1001F64F1 /* AssociationParallelRowScopesTests.swift in Sources */,
@@ -1329,7 +1331,7 @@
564A20CD226B8E18001F64F1 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
564A20CE226B8E18001F64F1 /* ForeignKeyInfoTests.swift in Sources */,
564A20CF226B8E18001F64F1 /* RecordPrimaryKeySingleTests.swift in Sources */,
563F4CBB242F801A0052E96C /* ValueObservationRecordTests.swift in Sources */,
561017D32462968600317275 /* DatabasePoolTests.swift in Sources */,
564A20D0226B8E18001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */,
5676FBB122F5CF04004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */,
564A20D1226B8E18001F64F1 /* AssociationParallelRowScopesTests.swift in Sources */,
@@ -15,6 +15,8 @@
56057C6C2291D0C000A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56057C6A2291D0C000A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */; };
560714F3227DD1AE0091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714F2227DD1AD0091BB10 /* AssociationPrefetchingSQLTests.swift */; };
560714F4227DD1AE0091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714F2227DD1AD0091BB10 /* AssociationPrefetchingSQLTests.swift */; };
561017D52462969D00317275 /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561017D42462969D00317275 /* DatabasePoolTests.swift */; };
561017D62462969D00317275 /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561017D42462969D00317275 /* DatabasePoolTests.swift */; };
561CFA802373507E000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7F2373507D000C8BAA /* MutablePersistableRecordUpdateTests.swift */; };
561CFA812373507E000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7F2373507D000C8BAA /* MutablePersistableRecordUpdateTests.swift */; };
561CFAA82376EFAD000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAA62376EFAD000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; };
@@ -415,6 +417,7 @@
56057C5B2291B8D600A7CB10 /* AssociationHasManyRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyRowScopeTests.swift; sourceTree = "<group>"; };
56057C6A2291D0C000A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughRowScopeTests.swift; sourceTree = "<group>"; };
560714F2227DD1AD0091BB10 /* AssociationPrefetchingSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingSQLTests.swift; sourceTree = "<group>"; };
561017D42462969D00317275 /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = "<group>"; };
561CFA7F2373507D000C8BAA /* MutablePersistableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordUpdateTests.swift; sourceTree = "<group>"; };
561CFAA62376EFAD000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = "<group>"; };
561CFAA72376EFAD000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = "<group>"; };
@@ -721,6 +724,7 @@
564A1F82226B89D7001F64F1 /* DatabasePoolReadOnlyTests.swift */,
564A1F62226B89D4001F64F1 /* DatabasePoolReleaseMemoryTests.swift */,
564A1F78226B89D6001F64F1 /* DatabasePoolSchemaCacheTests.swift */,
561017D42462969D00317275 /* DatabasePoolTests.swift */,
564A1F2B226B89CF001F64F1 /* DatabaseQueueBackupTests.swift */,
564A1FB1226B89DC001F64F1 /* DatabaseQueueConcurrencyTests.swift */,
564A1F2F226B89CF001F64F1 /* DatabaseQueueInMemoryTests.swift */,
@@ -1133,6 +1137,7 @@
564A2050226B89E1001F64F1 /* RecordPrimaryKeySingleTests.swift in Sources */,
564A2091226B89E1001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */,
5676FBAD22F5CEF6004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */,
561017D52462969D00317275 /* DatabasePoolTests.swift in Sources */,
564A208F226B89E1001F64F1 /* AssociationParallelRowScopesTests.swift in Sources */,
564B3D75239BDBED007BF308 /* DatabaseSuspensionTests.swift in Sources */,
564A2047226B89E1001F64F1 /* AnyCursorTests.swift in Sources */,
@@ -1336,6 +1341,7 @@
564A20CF226B8E18001F64F1 /* RecordPrimaryKeySingleTests.swift in Sources */,
564A20D0226B8E18001F64F1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */,
5676FBAE22F5CEF6004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */,
561017D62462969D00317275 /* DatabasePoolTests.swift in Sources */,
564A20D1226B8E18001F64F1 /* AssociationParallelRowScopesTests.swift in Sources */,
564B3D76239BDBED007BF308 /* DatabaseSuspensionTests.swift in Sources */,
564A20D2226B8E18001F64F1 /* AnyCursorTests.swift in Sources */,
+62 -62
View File
@@ -18,7 +18,7 @@ private struct Player: Codable, FetchableRecord, PersistableRecord {
}
private struct Award: Codable, FetchableRecord, PersistableRecord {
var id: Int64
var customPrimaryKey: Int64
var teamId: Int64?
var name: String
}
@@ -56,7 +56,7 @@ class AssociationAggregateTests: GRDBTestCase {
t.column("score", .integer)
}
try db.create(table: "award") { t in
t.column("id", .integer).primaryKey()
t.column("customPrimaryKey", .integer).primaryKey()
t.column("teamId", .integer).references("team")
t.column("name", .text)
}
@@ -64,16 +64,16 @@ class AssociationAggregateTests: GRDBTestCase {
try Team(id: 1, name: "Reds").insert(db)
try Player(id: 1, teamId: 1, name: "Arthur", score: 100).insert(db)
try Player(id: 2, teamId: 1, name: "Barbara", score: 1000).insert(db)
try Award(id: 1, teamId: 1, name: "World cup 2035").insert(db)
try Award(id: 2, teamId: 1, name: "World cup 2038").insert(db)
try Award(id: 3, teamId: 1, name: "European cup 2038").insert(db)
try Award(customPrimaryKey: 1, teamId: 1, name: "World cup 2035").insert(db)
try Award(customPrimaryKey: 2, teamId: 1, name: "World cup 2038").insert(db)
try Award(customPrimaryKey: 3, teamId: 1, name: "European cup 2038").insert(db)
try Team(id: 2, name: "Blues").insert(db)
try Player(id: 3, teamId: 2, name: "Craig", score: 200).insert(db)
try Player(id: 4, teamId: 2, name: "David", score: 500).insert(db)
try Player(id: 5, teamId: 2, name: "Elise", score: 800).insert(db)
try Award(id: 4, teamId: 2, name: "European cup 2036").insert(db)
try Award(customPrimaryKey: 4, teamId: 2, name: "European cup 2036").insert(db)
try Team(id: 3, name: "Greens").insert(db)
try Award(id: 5, teamId: 3, name: "World cup 2037").insert(db)
try Award(customPrimaryKey: 5, teamId: 3, name: "World cup 2037").insert(db)
try Team(id: 4, name: "Oranges").insert(db)
try Player(id: 6, teamId: 4, name: "Fiona", score: 0).insert(db)
}
@@ -88,7 +88,7 @@ class AssociationAggregateTests: GRDBTestCase {
.joining(required: Team.players.aliased(tableAlias).filter(sql: "custom.score < ?", arguments: [500]))
try assertEqualSQL(db, request, """
SELECT "team".*, COUNT(DISTINCT "custom"."rowid") AS "playerCount" \
SELECT "team".*, COUNT(DISTINCT "custom"."id") AS "playerCount" \
FROM "team" \
JOIN "player" "custom" ON ("custom"."teamId" = "team"."id") AND (custom.score < 500) \
GROUP BY "team"."id"
@@ -105,7 +105,7 @@ class AssociationAggregateTests: GRDBTestCase {
.group(Column("name"))
try assertEqualSQL(db, request, """
SELECT "team"."name", COUNT(DISTINCT "player"."rowid") AS "playerCount" \
SELECT "team"."name", COUNT(DISTINCT "player"."id") AS "playerCount" \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."name"
@@ -159,7 +159,7 @@ class AssociationAggregateTests: GRDBTestCase {
.asRequest(of: TeamInfo.self)
try assertEqualSQL(db, request, """
SELECT "team".*, COUNT(DISTINCT "player"."rowid") AS "playerCount" \
SELECT "team".*, COUNT(DISTINCT "player"."id") AS "playerCount" \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
@@ -200,7 +200,7 @@ class AssociationAggregateTests: GRDBTestCase {
.asRequest(of: PlayerInfo.self)
try assertEqualSQL(db, request, """
SELECT "player".*, COUNT(DISTINCT "award"."rowid") AS "awardCount" \
SELECT "player".*, COUNT(DISTINCT "award"."customPrimaryKey") AS "awardCount" \
FROM "player" \
LEFT JOIN "team" ON "team"."id" = "player"."teamId" \
LEFT JOIN "award" ON "award"."teamId" = "team"."id" \
@@ -396,7 +396,7 @@ class AssociationAggregateTests: GRDBTestCase {
try assertEqualSQL(db, request, """
SELECT "team".*, \
AVG("player"."score") AS "averagePlayerScore", \
COUNT(DISTINCT "player"."rowid") AS "playerCount", \
COUNT(DISTINCT "player"."id") AS "playerCount", \
MIN("player"."score") AS "minPlayerScore", \
MAX("player"."score") AS "maxPlayerScore", \
SUM("player"."score") AS "playerScoreSum" \
@@ -489,7 +489,7 @@ class AssociationAggregateTests: GRDBTestCase {
.asRequest(of: CustomTeamInfo.self)
try assertEqualSQL(db, request, """
SELECT "team".*, COUNT(DISTINCT "player"."rowid") AS "customPlayerCount" \
SELECT "team".*, COUNT(DISTINCT "player"."id") AS "customPlayerCount" \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
@@ -642,7 +642,7 @@ class AssociationAggregateTests: GRDBTestCase {
try assertEqualSQL(db, request, """
SELECT "team".*, \
AVG("player"."score") AS "averageCustomPlayerScore", \
COUNT(DISTINCT "player"."rowid") AS "customPlayerCount", \
COUNT(DISTINCT "player"."id") AS "customPlayerCount", \
MIN("player"."score") AS "minCustomPlayerScore", \
MAX("player"."score") AS "maxCustomPlayerScore", \
SUM("player"."score") AS "customPlayerScoreSum" \
@@ -702,7 +702,7 @@ class AssociationAggregateTests: GRDBTestCase {
try assertEqualSQL(db, request, """
SELECT "team".*, \
AVG("player"."score") AS "a1", \
COUNT(DISTINCT "player"."rowid") AS "a2", \
COUNT(DISTINCT "player"."id") AS "a2", \
MAX("player"."score") AS "a3", \
MIN("player"."score") AS "a4", \
SUM("player"."score") AS "a5" \
@@ -750,8 +750,8 @@ class AssociationAggregateTests: GRDBTestCase {
try assertEqualSQL(db, request, """
SELECT "team".*, \
COUNT(DISTINCT "player1"."rowid") AS "lowPlayerCount", \
COUNT(DISTINCT "player2"."rowid") AS "highPlayerCount" \
COUNT(DISTINCT "player1"."id") AS "lowPlayerCount", \
COUNT(DISTINCT "player2"."id") AS "highPlayerCount" \
FROM "team" \
LEFT JOIN "player" "player1" ON ("player1"."teamId" = "team"."id") AND ("player1"."score" < 500) \
LEFT JOIN "player" "player2" ON ("player2"."teamId" = "team"."id") AND ("player2"."score" >= 500) \
@@ -790,7 +790,7 @@ class AssociationAggregateTests: GRDBTestCase {
do {
let request = Team.annotated(with: Team.players.isEmpty)
try assertEqualSQL(db, request, """
SELECT "team".*, COUNT(DISTINCT "player"."rowid") = 0 AS "hasNoPlayer" \
SELECT "team".*, COUNT(DISTINCT "player"."id") = 0 AS "hasNoPlayer" \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id"
@@ -801,7 +801,7 @@ class AssociationAggregateTests: GRDBTestCase {
do {
let request = Team.annotated(with: !Team.players.isEmpty)
try assertEqualSQL(db, request, """
SELECT "team".*, COUNT(DISTINCT "player"."rowid") > 0 \
SELECT "team".*, COUNT(DISTINCT "player"."id") > 0 \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id"
@@ -816,7 +816,7 @@ class AssociationAggregateTests: GRDBTestCase {
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."rowid") = 0
HAVING COUNT(DISTINCT "player"."id") = 0
""")
try XCTAssertEqual(request.fetchAll(db).count, 1)
try XCTAssertEqual(request.fetchCount(db), 1)
@@ -828,7 +828,7 @@ class AssociationAggregateTests: GRDBTestCase {
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."rowid") > 0
HAVING COUNT(DISTINCT "player"."id") > 0
""")
try XCTAssertEqual(request.fetchAll(db).count, 3)
try XCTAssertEqual(request.fetchCount(db), 3)
@@ -840,7 +840,7 @@ class AssociationAggregateTests: GRDBTestCase {
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."rowid") > 0
HAVING COUNT(DISTINCT "player"."id") > 0
""")
try XCTAssertEqual(request.fetchAll(db).count, 3)
try XCTAssertEqual(request.fetchCount(db), 3)
@@ -852,7 +852,7 @@ class AssociationAggregateTests: GRDBTestCase {
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."rowid") = 0
HAVING COUNT(DISTINCT "player"."id") = 0
""")
try XCTAssertEqual(request.fetchAll(db).count, 1)
try XCTAssertEqual(request.fetchCount(db), 1)
@@ -871,7 +871,7 @@ class AssociationAggregateTests: GRDBTestCase {
LEFT JOIN "team" ON "team"."id" = "player"."teamId" \
LEFT JOIN "award" ON "award"."teamId" = "team"."id" \
GROUP BY "player"."id" \
HAVING COUNT(DISTINCT "award"."rowid") = 0
HAVING COUNT(DISTINCT "award"."customPrimaryKey") = 0
""")
try XCTAssertEqual(request.fetchAll(db).count, 1)
try XCTAssertEqual(request.fetchCount(db), 1)
@@ -884,7 +884,7 @@ class AssociationAggregateTests: GRDBTestCase {
LEFT JOIN "team" ON "team"."id" = "player"."teamId" \
LEFT JOIN "award" ON "award"."teamId" = "team"."id" \
GROUP BY "player"."id" \
HAVING COUNT(DISTINCT "award"."rowid") > 0
HAVING COUNT(DISTINCT "award"."customPrimaryKey") > 0
""")
try XCTAssertEqual(request.fetchAll(db).count, 5)
try XCTAssertEqual(request.fetchCount(db), 5)
@@ -897,7 +897,7 @@ class AssociationAggregateTests: GRDBTestCase {
LEFT JOIN "team" ON "team"."id" = "player"."teamId" \
LEFT JOIN "award" ON "award"."teamId" = "team"."id" \
GROUP BY "player"."id" \
HAVING COUNT(DISTINCT "award"."rowid") > 0
HAVING COUNT(DISTINCT "award"."customPrimaryKey") > 0
""")
try XCTAssertEqual(request.fetchAll(db).count, 5)
try XCTAssertEqual(request.fetchCount(db), 5)
@@ -910,7 +910,7 @@ class AssociationAggregateTests: GRDBTestCase {
LEFT JOIN "team" ON "team"."id" = "player"."teamId" \
LEFT JOIN "award" ON "award"."teamId" = "team"."id" \
GROUP BY "player"."id" \
HAVING COUNT(DISTINCT "award"."rowid") = 0
HAVING COUNT(DISTINCT "award"."customPrimaryKey") = 0
""")
try XCTAssertEqual(request.fetchAll(db).count, 1)
try XCTAssertEqual(request.fetchCount(db), 1)
@@ -929,7 +929,7 @@ class AssociationAggregateTests: GRDBTestCase {
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."rowid") = 2
HAVING COUNT(DISTINCT "player"."id") = 2
""")
}
do {
@@ -940,7 +940,7 @@ class AssociationAggregateTests: GRDBTestCase {
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING 2 = COUNT(DISTINCT "player"."rowid")
HAVING 2 = COUNT(DISTINCT "player"."id")
""")
}
do {
@@ -952,7 +952,7 @@ class AssociationAggregateTests: GRDBTestCase {
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
LEFT JOIN "award" ON "award"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."rowid") = COUNT(DISTINCT "award"."rowid")
HAVING COUNT(DISTINCT "player"."id") = COUNT(DISTINCT "award"."customPrimaryKey")
""")
}
}
@@ -969,7 +969,7 @@ class AssociationAggregateTests: GRDBTestCase {
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."rowid") <> 2
HAVING COUNT(DISTINCT "player"."id") <> 2
""")
}
do {
@@ -980,7 +980,7 @@ class AssociationAggregateTests: GRDBTestCase {
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING 2 <> COUNT(DISTINCT "player"."rowid")
HAVING 2 <> COUNT(DISTINCT "player"."id")
""")
}
do {
@@ -992,7 +992,7 @@ class AssociationAggregateTests: GRDBTestCase {
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
LEFT JOIN "award" ON "award"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."rowid") <> COUNT(DISTINCT "award"."rowid")
HAVING COUNT(DISTINCT "player"."id") <> COUNT(DISTINCT "award"."customPrimaryKey")
""")
}
}
@@ -1009,7 +1009,7 @@ class AssociationAggregateTests: GRDBTestCase {
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."rowid") >= 2
HAVING COUNT(DISTINCT "player"."id") >= 2
""")
}
do {
@@ -1020,7 +1020,7 @@ class AssociationAggregateTests: GRDBTestCase {
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING 2 >= COUNT(DISTINCT "player"."rowid")
HAVING 2 >= COUNT(DISTINCT "player"."id")
""")
}
do {
@@ -1032,7 +1032,7 @@ class AssociationAggregateTests: GRDBTestCase {
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
LEFT JOIN "award" ON "award"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."rowid") >= COUNT(DISTINCT "award"."rowid")
HAVING COUNT(DISTINCT "player"."id") >= COUNT(DISTINCT "award"."customPrimaryKey")
""")
}
}
@@ -1049,7 +1049,7 @@ class AssociationAggregateTests: GRDBTestCase {
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."rowid") > 2
HAVING COUNT(DISTINCT "player"."id") > 2
""")
}
do {
@@ -1060,7 +1060,7 @@ class AssociationAggregateTests: GRDBTestCase {
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING 2 > COUNT(DISTINCT "player"."rowid")
HAVING 2 > COUNT(DISTINCT "player"."id")
""")
}
do {
@@ -1072,7 +1072,7 @@ class AssociationAggregateTests: GRDBTestCase {
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
LEFT JOIN "award" ON "award"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."rowid") > COUNT(DISTINCT "award"."rowid")
HAVING COUNT(DISTINCT "player"."id") > COUNT(DISTINCT "award"."customPrimaryKey")
""")
}
}
@@ -1089,7 +1089,7 @@ class AssociationAggregateTests: GRDBTestCase {
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."rowid") <= 2
HAVING COUNT(DISTINCT "player"."id") <= 2
""")
}
do {
@@ -1100,7 +1100,7 @@ class AssociationAggregateTests: GRDBTestCase {
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING 2 <= COUNT(DISTINCT "player"."rowid")
HAVING 2 <= COUNT(DISTINCT "player"."id")
""")
}
do {
@@ -1112,7 +1112,7 @@ class AssociationAggregateTests: GRDBTestCase {
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
LEFT JOIN "award" ON "award"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."rowid") <= COUNT(DISTINCT "award"."rowid")
HAVING COUNT(DISTINCT "player"."id") <= COUNT(DISTINCT "award"."customPrimaryKey")
""")
}
}
@@ -1129,7 +1129,7 @@ class AssociationAggregateTests: GRDBTestCase {
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."rowid") < 2
HAVING COUNT(DISTINCT "player"."id") < 2
""")
}
do {
@@ -1140,7 +1140,7 @@ class AssociationAggregateTests: GRDBTestCase {
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING 2 < COUNT(DISTINCT "player"."rowid")
HAVING 2 < COUNT(DISTINCT "player"."id")
""")
}
do {
@@ -1152,7 +1152,7 @@ class AssociationAggregateTests: GRDBTestCase {
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
LEFT JOIN "award" ON "award"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."rowid") < COUNT(DISTINCT "award"."rowid")
HAVING COUNT(DISTINCT "player"."id") < COUNT(DISTINCT "award"."customPrimaryKey")
""")
}
}
@@ -1170,7 +1170,7 @@ class AssociationAggregateTests: GRDBTestCase {
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
LEFT JOIN "award" ON "award"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING (COUNT(DISTINCT "player"."rowid") = 0) AND (COUNT(DISTINCT "award"."rowid") = 0)
HAVING (COUNT(DISTINCT "player"."id") = 0) AND (COUNT(DISTINCT "award"."customPrimaryKey") = 0)
""")
}
do {
@@ -1182,7 +1182,7 @@ class AssociationAggregateTests: GRDBTestCase {
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
LEFT JOIN "award" ON "award"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING (COUNT(DISTINCT "player"."rowid") = 0) OR (COUNT(DISTINCT "award"."rowid") = 0)
HAVING (COUNT(DISTINCT "player"."id") = 0) OR (COUNT(DISTINCT "award"."customPrimaryKey") = 0)
""")
}
do {
@@ -1194,7 +1194,7 @@ class AssociationAggregateTests: GRDBTestCase {
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
LEFT JOIN "award" ON "award"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING NOT ((COUNT(DISTINCT "player"."rowid") = 0) OR (COUNT(DISTINCT "award"."rowid") = 0))
HAVING NOT ((COUNT(DISTINCT "player"."id") = 0) OR (COUNT(DISTINCT "award"."customPrimaryKey") = 0))
""")
}
do {
@@ -1206,7 +1206,7 @@ class AssociationAggregateTests: GRDBTestCase {
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
LEFT JOIN "award" ON "award"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING (NOT (COUNT(DISTINCT "player"."rowid") > 3)) OR (COUNT(DISTINCT "award"."rowid") = 0)
HAVING (NOT (COUNT(DISTINCT "player"."id") > 3)) OR (COUNT(DISTINCT "award"."customPrimaryKey") = 0)
""")
}
}
@@ -1219,7 +1219,7 @@ class AssociationAggregateTests: GRDBTestCase {
let request = Team.annotated(with: -Team.players.count)
try assertEqualSQL(db, request, """
SELECT "team".*, -COUNT(DISTINCT "player"."rowid") \
SELECT "team".*, -COUNT(DISTINCT "player"."id") \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id"
@@ -1235,7 +1235,7 @@ class AssociationAggregateTests: GRDBTestCase {
let request = Team.annotated(with: Team.players.count + 2)
try assertEqualSQL(db, request, """
SELECT "team".*, COUNT(DISTINCT "player"."rowid") + 2 \
SELECT "team".*, COUNT(DISTINCT "player"."id") + 2 \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id"
@@ -1245,7 +1245,7 @@ class AssociationAggregateTests: GRDBTestCase {
let request = Team.annotated(with: 2 + Team.players.count)
try assertEqualSQL(db, request, """
SELECT "team".*, 2 + COUNT(DISTINCT "player"."rowid") \
SELECT "team".*, 2 + COUNT(DISTINCT "player"."id") \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id"
@@ -1255,7 +1255,7 @@ class AssociationAggregateTests: GRDBTestCase {
let request = Team.annotated(with: Team.players.count + Team.awards.count)
try assertEqualSQL(db, request, """
SELECT "team".*, COUNT(DISTINCT "player"."rowid") + COUNT(DISTINCT "award"."rowid") \
SELECT "team".*, COUNT(DISTINCT "player"."id") + COUNT(DISTINCT "award"."customPrimaryKey") \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
LEFT JOIN "award" ON "award"."teamId" = "team"."id" \
@@ -1272,7 +1272,7 @@ class AssociationAggregateTests: GRDBTestCase {
let request = Team.annotated(with: Team.players.count - 2)
try assertEqualSQL(db, request, """
SELECT "team".*, COUNT(DISTINCT "player"."rowid") - 2 \
SELECT "team".*, COUNT(DISTINCT "player"."id") - 2 \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id"
@@ -1282,7 +1282,7 @@ class AssociationAggregateTests: GRDBTestCase {
let request = Team.annotated(with: 2 - Team.players.count)
try assertEqualSQL(db, request, """
SELECT "team".*, 2 - COUNT(DISTINCT "player"."rowid") \
SELECT "team".*, 2 - COUNT(DISTINCT "player"."id") \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id"
@@ -1292,7 +1292,7 @@ class AssociationAggregateTests: GRDBTestCase {
let request = Team.annotated(with: Team.players.count - Team.awards.count)
try assertEqualSQL(db, request, """
SELECT "team".*, COUNT(DISTINCT "player"."rowid") - COUNT(DISTINCT "award"."rowid") \
SELECT "team".*, COUNT(DISTINCT "player"."id") - COUNT(DISTINCT "award"."customPrimaryKey") \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
LEFT JOIN "award" ON "award"."teamId" = "team"."id" \
@@ -1309,7 +1309,7 @@ class AssociationAggregateTests: GRDBTestCase {
let request = Team.annotated(with: Team.players.count * 2)
try assertEqualSQL(db, request, """
SELECT "team".*, COUNT(DISTINCT "player"."rowid") * 2 \
SELECT "team".*, COUNT(DISTINCT "player"."id") * 2 \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id"
@@ -1319,7 +1319,7 @@ class AssociationAggregateTests: GRDBTestCase {
let request = Team.annotated(with: 2 * Team.players.count)
try assertEqualSQL(db, request, """
SELECT "team".*, 2 * COUNT(DISTINCT "player"."rowid") \
SELECT "team".*, 2 * COUNT(DISTINCT "player"."id") \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id"
@@ -1329,7 +1329,7 @@ class AssociationAggregateTests: GRDBTestCase {
let request = Team.annotated(with: Team.players.count * Team.awards.count)
try assertEqualSQL(db, request, """
SELECT "team".*, COUNT(DISTINCT "player"."rowid") * COUNT(DISTINCT "award"."rowid") \
SELECT "team".*, COUNT(DISTINCT "player"."id") * COUNT(DISTINCT "award"."customPrimaryKey") \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
LEFT JOIN "award" ON "award"."teamId" = "team"."id" \
@@ -1346,7 +1346,7 @@ class AssociationAggregateTests: GRDBTestCase {
let request = Team.annotated(with: Team.players.count / 2)
try assertEqualSQL(db, request, """
SELECT "team".*, COUNT(DISTINCT "player"."rowid") / 2 \
SELECT "team".*, COUNT(DISTINCT "player"."id") / 2 \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id"
@@ -1356,7 +1356,7 @@ class AssociationAggregateTests: GRDBTestCase {
let request = Team.annotated(with: 2 / Team.players.count)
try assertEqualSQL(db, request, """
SELECT "team".*, 2 / COUNT(DISTINCT "player"."rowid") \
SELECT "team".*, 2 / COUNT(DISTINCT "player"."id") \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id"
@@ -1366,7 +1366,7 @@ class AssociationAggregateTests: GRDBTestCase {
let request = Team.annotated(with: Team.players.count / Team.awards.count)
try assertEqualSQL(db, request, """
SELECT "team".*, COUNT(DISTINCT "player"."rowid") / COUNT(DISTINCT "award"."rowid") \
SELECT "team".*, COUNT(DISTINCT "player"."id") / COUNT(DISTINCT "award"."customPrimaryKey") \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
LEFT JOIN "award" ON "award"."teamId" = "team"."id" \
@@ -27,7 +27,7 @@ private struct PlayerWithOptionalTeam: Decodable, FetchableRecord {
static let team = Player.team.forKey(CodingKeys.team)
}
extension QueryInterfaceRequest where T == Player {
extension QueryInterfaceRequest where RowDecoder == Player {
func filter(teamName: String) -> QueryInterfaceRequest<Player> {
joining(required: PlayerWithOptionalTeam.team.filter(Column("name") == teamName))
}
@@ -128,6 +128,18 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
JOIN "b" ON ("b"."id" = "a"."bid") AND ("b"."id" IN (1, 2, 3))
""")
}
do {
let alias = TableAlias()
let request = A
.aliased(alias)
.including(required: A.b
.filter([alias[Column("id")], Column("id"), 42].contains(Column("id"))))
try assertEqualSQL(db, request, """
SELECT "a".*, "b".* \
FROM "a" \
JOIN "b" ON ("b"."id" = "a"."bid") AND ("b"."id" IN ("a"."id", "b"."id", 42))
""")
}
do {
let request = A.including(required: A.b.filter(key: ["id": 1]))
try assertEqualSQL(db, request, """
@@ -206,8 +218,7 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
let request = aTransform(aBase)
.including(required: abTransform(abBase)
.including(required: abaTransform(abaBase)))
let sqlRequest = try SQLRequest(db, request: request)
sqls.append(sqlRequest.sql)
try sqls.append(request.build(db).sql)
}
}
}
@@ -998,4 +998,133 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
let _ = try request.fetchCount(db)
}
}
func testCaseInsensitivity() throws {
struct Child : TableRecord, EncodableRecord {
static let databaseTableName = "CHILDREN"
func encode(to container: inout PersistenceContainer) {
container["PaReNtId"] = 1
}
}
struct Parent : TableRecord {
static let databaseTableName = "PARENTS"
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parents") { t in
t.column("id", .integer).primaryKey()
t.column("name", .text)
}
try db.create(table: "children") { t in
t.column("parentId", .integer).references("parents")
}
}
try dbQueue.inDatabase { db in
do {
let association = Child.belongsTo(Parent.self)
try assertEqualSQL(db, Child.including(required: association), """
SELECT "CHILDREN".*, "PARENTS".* \
FROM "CHILDREN" \
JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
""")
try assertEqualSQL(db, Child.including(optional: association), """
SELECT "CHILDREN".*, "PARENTS".* \
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
""")
try assertEqualSQL(db, Child.joining(required: association), """
SELECT "CHILDREN".* \
FROM "CHILDREN" \
JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
""")
try assertEqualSQL(db, Child.joining(optional: association), """
SELECT "CHILDREN".* \
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
""")
try assertEqualSQL(db, Child.joining(optional: association.filter(Column("name") == "foo")), """
SELECT "CHILDREN".* \
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON ("PARENTS"."id" = "CHILDREN"."parentId") AND ("PARENTS"."name" = 'foo')
""")
try assertEqualSQL(db, Child().request(for: association), """
SELECT * FROM "PARENTS" WHERE "id" = 1
""")
try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """
SELECT "custom".* FROM "PARENTS" "custom" WHERE "custom"."id" = 1
""")
}
do {
let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("PARENTID")]))
try assertEqualSQL(db, Child.including(required: association), """
SELECT "CHILDREN".*, "PARENTS".* \
FROM "CHILDREN" \
JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
""")
try assertEqualSQL(db, Child.including(optional: association), """
SELECT "CHILDREN".*, "PARENTS".* \
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
""")
try assertEqualSQL(db, Child.joining(required: association), """
SELECT "CHILDREN".* \
FROM "CHILDREN" \
JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
""")
try assertEqualSQL(db, Child.joining(optional: association), """
SELECT "CHILDREN".* \
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
""")
try assertEqualSQL(db, Child.joining(optional: association.filter(Column("name") == "foo")), """
SELECT "CHILDREN".* \
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON ("PARENTS"."id" = "CHILDREN"."parentId") AND ("PARENTS"."name" = 'foo')
""")
try assertEqualSQL(db, Child().request(for: association), """
SELECT * FROM "PARENTS" WHERE "id" = 1
""")
try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """
SELECT "custom".* FROM "PARENTS" "custom" WHERE "custom"."id" = 1
""")
}
do {
let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("PARENTID")], to: [Column("ID")]))
try assertEqualSQL(db, Child.including(required: association), """
SELECT "CHILDREN".*, "PARENTS".* \
FROM "CHILDREN" \
JOIN "PARENTS" ON "PARENTS"."ID" = "CHILDREN"."PARENTID"
""")
try assertEqualSQL(db, Child.including(optional: association), """
SELECT "CHILDREN".*, "PARENTS".* \
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON "PARENTS"."ID" = "CHILDREN"."PARENTID"
""")
try assertEqualSQL(db, Child.joining(required: association), """
SELECT "CHILDREN".* \
FROM "CHILDREN" \
JOIN "PARENTS" ON "PARENTS"."ID" = "CHILDREN"."PARENTID"
""")
try assertEqualSQL(db, Child.joining(optional: association), """
SELECT "CHILDREN".* \
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON "PARENTS"."ID" = "CHILDREN"."PARENTID"
""")
try assertEqualSQL(db, Child.joining(optional: association.filter(Column("name") == "foo")), """
SELECT "CHILDREN".* \
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON ("PARENTS"."ID" = "CHILDREN"."PARENTID") AND ("PARENTS"."name" = 'foo')
""")
try assertEqualSQL(db, Child().request(for: association), """
SELECT * FROM "PARENTS" WHERE "ID" = 1
""")
try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """
SELECT "custom".* FROM "PARENTS" "custom" WHERE "custom"."ID" = 1
""")
}
}
}
}
@@ -780,6 +780,7 @@ class AssociationHasManySQLTests: GRDBTestCase {
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent")
}
try db.create(table: "toy") { t in
@@ -793,17 +794,17 @@ class AssociationHasManySQLTests: GRDBTestCase {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parent".*, "child".* \
FROM "parent" JOIN "child" ON "child"."parentId" = "parent"."id" \
JOIN "toy" ON "toy"."childId" = "child"."rowid"
JOIN "toy" ON "toy"."childId" = "child"."id"
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parent".* FROM "parent" \
JOIN "child" ON "child"."parentId" = "parent"."id" \
JOIN "toy" ON "toy"."childId" = "child"."rowid"
JOIN "toy" ON "toy"."childId" = "child"."id"
""")
try assertEqualSQL(db, Parent().request(for: association), """
SELECT "child".* \
FROM "child" \
JOIN "toy" ON "toy"."childId" = "child"."rowid" \
JOIN "toy" ON "toy"."childId" = "child"."id" \
WHERE "child"."parentId" = 1
""")
}
@@ -332,6 +332,7 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent")
}
try db.create(table: "toy") { t in
@@ -352,21 +353,21 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
SELECT "parent".*, "pet".* \
FROM "parent" \
JOIN "child" ON "child"."parentId" = "parent"."id" \
JOIN "toy" ON "toy"."childId" = "child"."rowid" \
JOIN "pet" ON "pet"."childId" = "child"."rowid"
JOIN "toy" ON "toy"."childId" = "child"."id" \
JOIN "pet" ON "pet"."childId" = "child"."id"
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parent".* \
FROM "parent" \
JOIN "child" ON "child"."parentId" = "parent"."id" \
JOIN "toy" ON "toy"."childId" = "child"."rowid" \
JOIN "pet" ON "pet"."childId" = "child"."rowid"
JOIN "toy" ON "toy"."childId" = "child"."id" \
JOIN "pet" ON "pet"."childId" = "child"."id"
""")
try assertEqualSQL(db, Parent().request(for: association), """
SELECT "pet".* \
FROM "pet" \
JOIN "child" ON ("child"."rowid" = "pet"."childId") AND ("child"."parentId" = 1) \
JOIN "toy" ON "toy"."childId" = "child"."rowid"
JOIN "child" ON ("child"."id" = "pet"."childId") AND ("child"."parentId" = 1) \
JOIN "toy" ON "toy"."childId" = "child"."id"
""")
}
do {
@@ -378,24 +379,24 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
SELECT "parent".*, "pet".* \
FROM "parent" \
JOIN "child" "child1" ON ("child1"."parentId" = "parent"."id") AND (1 + 1) \
JOIN "pet" ON "pet"."childId" = "child1"."rowid" \
JOIN "child" "child2" ON ("child2"."rowid" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child2"."rowid"
JOIN "pet" ON "pet"."childId" = "child1"."id" \
JOIN "child" "child2" ON ("child2"."id" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child2"."id"
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parent".* \
FROM "parent" \
JOIN "child" "child1" ON ("child1"."parentId" = "parent"."id") AND (1 + 1) \
JOIN "pet" ON "pet"."childId" = "child1"."rowid" \
JOIN "child" "child2" ON ("child2"."rowid" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child2"."rowid"
JOIN "pet" ON "pet"."childId" = "child1"."id" \
JOIN "child" "child2" ON ("child2"."id" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child2"."id"
""")
try assertEqualSQL(db, Parent().request(for: association), """
SELECT "pet".* \
FROM "pet" \
JOIN "child" "child1" ON ("child1"."rowid" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child1"."rowid" \
JOIN "child" "child2" ON ("child2"."rowid" = "pet"."childId") AND (1 + 1) AND ("child2"."parentId" = 1)
JOIN "child" "child1" ON ("child1"."id" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child1"."id" \
JOIN "child" "child2" ON ("child2"."id" = "pet"."childId") AND (1 + 1) AND ("child2"."parentId" = 1)
""")
}
do {
@@ -408,24 +409,24 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
SELECT "parent".*, "pet".* \
FROM "parent" \
JOIN "child" "child1" ON ("child1"."parentId" = "parent"."id") AND (1 + 1) \
JOIN "pet" ON "pet"."childId" = "child1"."rowid" \
JOIN "child" "child2" ON ("child2"."rowid" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child2"."rowid"
JOIN "pet" ON "pet"."childId" = "child1"."id" \
JOIN "child" "child2" ON ("child2"."id" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child2"."id"
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parent".* \
FROM "parent" \
JOIN "child" "child1" ON ("child1"."parentId" = "parent"."id") AND (1 + 1) \
JOIN "pet" ON "pet"."childId" = "child1"."rowid" \
JOIN "child" "child2" ON ("child2"."rowid" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child2"."rowid"
JOIN "pet" ON "pet"."childId" = "child1"."id" \
JOIN "child" "child2" ON ("child2"."id" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child2"."id"
""")
try assertEqualSQL(db, Parent().request(for: association), """
SELECT "pet".* \
FROM "pet" \
JOIN "child" "child1" ON ("child1"."rowid" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child1"."rowid" \
JOIN "child" "child2" ON ("child2"."rowid" = "pet"."childId") AND (1 + 1) AND ("child2"."parentId" = 1)
JOIN "child" "child1" ON ("child1"."id" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child1"."id" \
JOIN "child" "child2" ON ("child2"."id" = "pet"."childId") AND (1 + 1) AND ("child2"."parentId" = 1)
""")
}
}
@@ -206,8 +206,7 @@ class AssociationHasOneSQLDerivationTests: GRDBTestCase {
let request = aTransform(aBase)
.including(required: abTransform(abBase)
.including(required: abaTransform(abaBase)))
let sqlRequest = try SQLRequest(db, request: request)
sqls.append(sqlRequest.sql)
try sqls.append(request.build(db).sql)
}
}
}
Loaded 100 of 148 files, more files were not shown because too many files have changed in this diff. Show more