Compare commits

...
Author SHA1 Message Date
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
93 changed files with 3138 additions and 2237 deletions

No files matched your search

+32 -32
View File
@@ -34,15 +34,15 @@ jobs:
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBOSX (Swift 5.1, macOS)
- TID=GRDBOSX (Swift 5.2, macOS)
script: make test_framework_GRDBOSX_maxSwift
- stage: Test GRDB Xcode 11.4
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=GRDBOSX (Swift 5.2, macOS)
# script: make test_framework_GRDBOSX_minSwift
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
@@ -55,42 +55,42 @@ jobs:
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 5.1, iOS <MAX>)
- TID=GRDBiOS (Swift 5.2, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget_maxSwift
- stage: Test GRDB Xcode 11.4
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.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>)
- TID=GRDBiOS (Swift 5.2, iOS <MIN>)
script: make test_framework_GRDBiOS_minTarget
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBtvOS (Swift 5.1, tvOS <MAX>)
- TID=GRDBtvOS (Swift 5.2, tvOS <MAX>)
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
- stage: Test GRDB Xcode 11.4
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.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>)
- TID=GRDBtvOS (Swift 5.2, tvOS <MIN>)
script: make test_framework_GRDBtvOS_minTarget
- stage: Test GRDB Xcode 11.4
@@ -107,28 +107,28 @@ jobs:
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBOSX (Swift 5.1, macOS)
- TID=GRDBOSX (Swift 5.2, macOS)
script: make test_framework_GRDBCustomSQLiteOSX
- stage: Test GRDBCustom Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 5.1, iOS <MAX>)
- TID=GRDBiOS (Swift 5.2, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
- stage: Test GRDBCustom Xcode 11.4
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.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>)
- TID=GRDBiOS (Swift 5.2, iOS <MIN>)
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
###########################################
+69 -6
View File
@@ -13,7 +13,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 5.x Releases
- `5.0.x` Development - [GRDB5 Branch](#grdb5-branch)
- `5.0.0` Betas - [5.0.0-beta](#500-beta)
#### 4.x Releases
@@ -76,14 +76,70 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
## Next Release
-->
## GRDB5 Branch
## 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
- 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.
- **[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 +164,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
+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)
+84 -5
View File
@@ -302,8 +302,86 @@ 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):
2. [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.
3. 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]
```
> :question: This change makes it possible to embed query interface requests as subqueries inside SQLLiteral:
>
> ```swift
> let maximumScore = Player.select(max(Column("score")))
> let query: SQLLiteral = "SELECT * FROM player WHERE score = (\(maximumScore))"
> ```
4. In order to extract raw SQL string from a request (SQLRequest or QueryInterfaceRequest), you now need a database connection:
```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).statement
print(statement.sql) // "SELECT * FROM player WHERE name = ?"
print(statement.arguments) // ["O'Brien"]
}
```
> :question: This change makes it possible to embed query interface requests as subqueries inside SQLRequest:
>
> ```swift
> let maximumScore = Player.select(max(Column("score")))
> let request: SQLRequest<Player> = "SELECT * FROM player WHERE score = (\(maximumScore))"
> ```
5. 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)
```
6. [Custom SQL functions] are now [callable values](https://github.com/apple/swift-evolution/blob/master/proposals/0253-callable.md):
```swift
// BEFORE: GRDB 4
@@ -313,7 +391,7 @@ 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:
7. If you happen to implement custom fetch requests with the `FetchRequest` protocol, you now have to define the `makePreparedRequest(_:forSingleResult:)` method:
```swift
// BEFORE: GRDB 4
@@ -335,7 +413,7 @@ The changes can quite impact your application. We'll describe them below, as wel
}
```
4. The module name for [custom SQLite builds](CustomSQLiteBuilds.md) is now the plain `GRDB`:
8. The module name for [custom SQLite builds](CustomSQLiteBuilds.md) is now the plain `GRDB`:
```swift
// BEFORE: GRDB 4
@@ -345,7 +423,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:
9. 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 +438,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 +446,5 @@ 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
@@ -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
+126
View File
@@ -0,0 +1,126 @@
# 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,** starting SQLite 3.7.16+ (iOS 9.0+ /
+ / tvOS 9.0+ / watchOS 2.0+ / [custom SQLite build] / [SQLCipher](../README.md#encryption)). 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:
```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"
```
Check if consecutive migrations have been applied:
```swift
if try dbQueue.read(migrator.hasCompletedMigrations) {
// All migrations have been applied, up to the last one.
}
if try dbQueue.read(migrator.completedMigrations).last == "v2" {
// All migrations up to "v2" have been applied, and no further.
}
if try dbQueue.read(migrator.completedMigrations).contains("v2") {
// All migrations up to "v2" have been applied, and maybe further.
}
```
Check if individual migrations have been applied:
```swift
if try dbQueue.read(migrator.appliedMigrations).contains("v2") {
// "v2" migration has been applied
}
```
## 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")
}
```
+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
+1 -1
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'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+4
View File
@@ -164,6 +164,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).
///
+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
+2 -2
View File
@@ -158,8 +158,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
+4 -1
View File
@@ -301,7 +301,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
+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`
+7 -1
View File
@@ -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
@@ -139,6 +141,10 @@ public final class DatabasePool: DatabaseWriter {
// 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.
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) {
+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)
}
}
+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)
}
+34 -33
View File
@@ -14,34 +14,39 @@ public struct SQLLiteral {
/// table aliases.
enum Element {
case sql(String, StatementArguments = StatementArguments())
case subquery((SQLGenerationContext) throws -> String)
// 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(function):
return try function(context)
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,18 @@ 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)
}
func sql(_ context: SQLGenerationContext) throws -> String {
try elements.map { try $0.sql(context) }.joined()
}
fileprivate func qualified(with alias: TableAlias) -> SQLLiteral {
@@ -250,11 +251,11 @@ private struct _SQLExpressionLiteral: SQLExpression {
/// [**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)
@@ -274,11 +275,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 +325,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 {
+34 -41
View File
@@ -1,5 +1,5 @@
/// A FetchRequest built from raw SQL.
public struct SQLRequest<T>: FetchRequest {
public struct SQLRequest<RowDecoder>: FetchRequest {
/// 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: """
@@ -146,8 +108,8 @@ public struct SQLRequest<T>: FetchRequest {
///
/// :nodoc:
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:
@@ -162,6 +124,37 @@ public struct SQLRequest<T>: FetchRequest {
}
}
// Support for `request.contains(expression)`
extension SQLRequest: SQLCollection {
/// :nodoc
public func collectionSQL(_ context: SQLGenerationContext) throws -> String {
try sqlLiteral.sql(context)
}
/// :nodoc
public func qualifiedCollection(with alias: TableAlias) -> SQLCollection {
self
}
}
// Support for `request == expression`
//
// Note: I wish we would give SQLExpression conformance to SQLRequest and
// QueryInterfaceRequest.
//
// But this does not play well with SQLInterpolation. Interpolation won't embed
// the request as a subquery, without wrapping parenthesis (in order to let the
// user perform unions). Instead, it insists on embedding it as an expression,
// wrapped in parenthesis (as support for `Column("score") = maxScoreRequest`).
//
// Maybe, when we master the Swift compiler a little more...
extension SQLRequest: SQLSpecificExpressible {
/// :nodoc
public var sqlExpression: SQLExpression {
sqlLiteral.sqlExpression
}
}
extension SQLRequest: ExpressibleByStringInterpolation {
/// :nodoc
public init(unicodeScalarLiteral: String) {
+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)
}
+47 -6
View File
@@ -134,12 +134,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 +162,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 +173,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).statement.sql instead")
public var sql: String { preconditionFailure() }
@available(*, unavailable, message: "Use makePreparedRequest(db).statement.arguments instead")
public var arguments: StatementArguments { preconditionFailure() }
}
extension SQLSpecificExpressible {
@available(*, unavailable, renamed: "forKey(_:)")
public func aliased(_ name: String) -> SQLSelectable
@@ -191,6 +228,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 {
@@ -213,7 +254,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 +267,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 +278,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 +291,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 +325,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.")
@@ -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)
}
}
@@ -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
}
@@ -39,8 +39,6 @@ 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.
///
@@ -49,14 +47,8 @@ extension QueryInterfaceRequest: FetchRequest {
/// - 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 generator = SQLQueryGenerator(query: query, forSingleResult: singleResult)
let (statement, adapter) = try generator.prepare(db)
let associations = query.relation.prefetchedAssociations
if associations.isEmpty {
return PreparedRequest(statement: statement, adapter: adapter)
@@ -84,7 +76,9 @@ extension QueryInterfaceRequest: FetchRequest {
/// - parameter db: A database connection.
/// :nodoc:
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
var region = try SQLQueryGenerator(query).makeSelectStatement(db).selectedRegion
var region = try SQLQueryGenerator(query: query)
.makeSelectStatement(db)
.selectedRegion
// Iterate all prefetched associations
var fifo = query.relation.prefetchedAssociations
@@ -98,12 +92,20 @@ extension QueryInterfaceRequest: FetchRequest {
let pivotAlias = TableAlias()
let prefetchedRelation = association
.map(\.pivot.relation, { $0.qualified(with: pivotAlias) })
.destinationRelation(fromOriginRows: { _ in [] /* no origin row */ })
// 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 region
try region.formUnion(SQLQueryGenerator(prefetchedQuery).makeSelectStatement(db).selectedRegion)
// Union prefetched region
let prefetchedRegion = try SQLQueryGenerator(query: prefetchedQuery)
.makeSelectStatement(db)
.selectedRegion
region.formUnion(prefetchedRegion)
// Append nested prefetched associations (support for
// A.including(all: A.bs.including(all: B.cs))
@@ -117,19 +119,19 @@ extension QueryInterfaceRequest: FetchRequest {
extension QueryInterfaceRequest: SelectionRequest {
// MARK: Request Derivation
/// Creates a request which selects *selection*.
/// 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,14 +215,14 @@ 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) }
}
}
@@ -292,9 +294,9 @@ extension QueryInterfaceRequest: AggregatingRequest {
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,7 +328,7 @@ extension QueryInterfaceRequest: _JoinableRequest {
}
}
extension QueryInterfaceRequest: JoinableRequest where T: TableRecord { }
extension QueryInterfaceRequest: JoinableRequest where RowDecoder: TableRecord { }
extension QueryInterfaceRequest: Refinable {
@@ -345,18 +347,6 @@ extension QueryInterfaceRequest: Refinable {
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.
///
/// :nodoc:
public func expectingSingleResult() -> QueryInterfaceRequest {
map(\.query) { $0.expectingSingleResult() }
}
/// Creates a request which fetches *limit* rows, starting at *offset*.
///
/// // SELECT * FROM player LIMIT 1
@@ -407,25 +397,72 @@ extension QueryInterfaceRequest: Refinable {
}
}
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
// Support for `request.contains(expression)`
extension QueryInterfaceRequest: SQLCollection {
/// :nodoc
public func collectionSQL(_ context: SQLGenerationContext) throws -> String {
// If the request selects several colums, SQLite 3.28.0 may complain
// with an error:
//
// -- Error: sub-select returns 2 columns - expected 1
// SELECT * FROM t WHERE a IN (SELECT a, b FROM t);
//
// But other requests accept multiple columns:
//
// -- OK
// SELECT * FROM t WHERE (a, b) IN (SELECT a, b FROM t);
//
// So we do not prevent using requests that select several columns
// as expressions.
try SQLQueryGenerator(query: query).sql(context)
}
/// :nodoc
public func qualifiedCollection(with alias: TableAlias) -> SQLCollection {
self
}
}
// Support for `request == expression`
//
// Note: I wish we would give SQLExpression conformance to
// QueryInterfaceRequest. See SQLRequest for more information.
extension QueryInterfaceRequest: SQLSpecificExpressible {
private struct Expression: SQLExpression {
let generator: SQLQueryGenerator
// 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")
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
try "(" + generator.sql(context) + ")"
}
return query.relation
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
self
}
}
/// :nodoc
public var sqlExpression: SQLExpression {
// We're generating an *expression*, so we have to deal with the fact
// that the request may return several rows, and select several columns.
//
// In practice, SQLite only considers the first returned row.
// So we don't have to set the `forSingleResult` flag of the generator
// in order to make sure a single row is returned.
//
// And if the request selects several colums, SQLite 3.28.0 may complain
// with a "row value misused" error:
//
// -- Error: row value misused
// SELECT * FROM t WHERE a = (SELECT a, b FROM t);
//
// But other requests accept multiple columns:
//
// -- OK
// SELECT * FROM t WHERE (a, b) = (SELECT a, b FROM t);
//
// So we do not prevent using requests that select several columns
// as expressions.
Expression(generator: SQLQueryGenerator(query: query))
}
}
@@ -441,7 +478,7 @@ extension QueryInterfaceRequest: TableRequest {
// request.filter(keys: ...)
// request.orderByPrimaryKey()
return tableName
case .query:
case .subquery:
// The only current use case for SQLSource.query is the
// "trivial count query" (see SQLQuery.countQuery):
//
@@ -456,9 +493,9 @@ extension QueryInterfaceRequest: TableRequest {
}
}
extension QueryInterfaceRequest: DerivableRequest where T: TableRecord { }
extension QueryInterfaceRequest: DerivableRequest where RowDecoder: TableRecord { }
extension QueryInterfaceRequest where T: MutablePersistableRecord {
extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
// MARK: Batch Delete
@@ -469,7 +506,7 @@ 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
}
@@ -497,7 +534,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
@@ -585,7 +622,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: []]
@@ -601,7 +638,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 +647,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 +673,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
}
}
}
+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,51 @@
/// [**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 support for SQL generation:
///
/// - It provides a database connection so that request elements can perform
/// database introspection in order to build their SQL representation.
///
/// - It provides unique table aliases in order to disambiguates table names
/// and columns.
///
/// - Request elements can turn database values as SQLite statement arguments,
/// in order to prevent SQL injection.
///
/// :nodoc:
public struct SQLGenerationContext {
var arguments: StatementArguments {
_arguments ?? StatementArguments()
}
private var _arguments: StatementArguments?
/// A database connection so that request elements can perform database
/// introspection in order to build their SQL representation.
let db: Database
/// The arguments sink which prevents SQL injection.
let argumentsSink: StatementArgumentsSink
/// All arguments gathered so far
var arguments: StatementArguments { argumentsSink.arguments }
private var resolvedNames: [TableAlias: String]
private var qualifierNeeded: Bool
private var qualifiesColumnsWithTable: Bool
/// Used for pure SQL generation. Arguments are always empty.
static let rawSQLContext = SQLGenerationContext(
_arguments: nil,
resolvedNames: [:],
qualifierNeeded: false)
/// Used for SQLLiteral generation
static let sqlLiteralContext = SQLGenerationContext(
_arguments: [],
resolvedNames: [:],
qualifierNeeded: false)
/// Used for TableRecord.selectionSQL
static let selectionContext = SQLGenerationContext(
_arguments: nil,
resolvedNames: [:],
qualifierNeeded: true)
/// Used for SQLQueryGenerator
static func queryContext(aliases: [TableAlias]) -> SQLGenerationContext {
SQLGenerationContext(
_arguments: [],
resolvedNames: aliases.resolvedNames,
qualifierNeeded: aliases.count > 1)
/// 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.db = db
self.argumentsSink = argumentsSink
self.resolvedNames = aliases.resolvedNames
self.qualifiesColumnsWithTable = aliases.count > 1
}
/// 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
func append(arguments: StatementArguments) -> Bool {
argumentsSink.append(arguments: arguments)
}
/// May be nil, when a qualifier is not needed:
@@ -62,7 +59,7 @@ public struct SQLGenerationContext {
if alias.hasUserName {
return alias.identityName
}
if qualifierNeeded == false {
if qualifiesColumnsWithTable == false {
return nil
}
return resolvedName(for: alias)
@@ -83,6 +80,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 whether arguments could be appended.
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 +307,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,20 @@
/// 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
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 +42,97 @@ 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
}
func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String {
func sql(
_ db: Database,
argumentsSink: StatementArgumentsSink = StatementArgumentsSink())
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(db, argumentsSink: argumentsSink, 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(
db,
selection: selection,
filters: filters,
groupExpressions: groupExpressions)
{
limit = SQLLimit(limit: 1, offset: limit?.offset)
}
if let limit = limit {
sql += " LIMIT "
sql += limit.sql
@@ -96,6 +141,11 @@ struct SQLQueryGenerator {
return sql
}
// Convenience
func sql(_ context: SQLGenerationContext) throws -> String {
try sql(context.db, argumentsSink: context.argumentsSink)
}
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
try (makeSelectStatement(db), rowAdapter(db))
}
@@ -126,6 +176,102 @@ 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
{
// value == Column("foo")
assert(qualifiedColumn.alias == sourceAlias)
return qualifiedColumn.name
}
if equalExpression.rhs is DatabaseValue,
let qualifiedColumn = equalExpression.lhs as? QualifiedColumn
{
// Column("foo") == value
assert(qualifiedColumn.alias == sourceAlias)
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.
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 +284,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 +317,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]) }).sql(db, argumentsSink: context.argumentsSink)
sql += ")"
let statement = try db.makeUpdateStatement(sql: sql)
statement.arguments = context.arguments
@@ -217,7 +365,7 @@ struct SQLQueryGenerator {
return nil
}
var context = SQLGenerationContext.queryContext(aliases: relation.allAliases)
let context = SQLGenerationContext(db, aliases: relation.allAliases)
var sql = "UPDATE "
@@ -225,22 +373,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 +409,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 +428,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,15 +439,17 @@ 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]) }).sql(db, argumentsSink: context.argumentsSink)
sql += ")"
let statement = try db.makeUpdateStatement(sql: sql)
statement.arguments = context.arguments
@@ -304,17 +458,13 @@ struct SQLQueryGenerator {
/// 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)
// Build
let argumentsSink = StatementArgumentsSink()
let sql = try self.sql(db, argumentsSink: argumentsSink)
// Compile & set arguments
let statement = try db.makeSelectStatement(sql: sql)
statement.arguments = context.arguments
statement.arguments = argumentsSink.arguments
// Optimize databaseRegion
statement.selectedRegion = try optimizedSelectedRegion(db, statement.selectedRegion)
@@ -409,14 +559,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 +576,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 +628,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 +665,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 +709,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 +726,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 +752,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 +765,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.sql(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 +834,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
@@ -17,6 +17,22 @@ extension SQLInterpolation {
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: TableRecord>(columnsOf record: T.Type, tableAlias: String? = nil) {
let alias = TableAlias(name: tableAlias ?? T.databaseTableName)
elements.append(contentsOf: T.databaseSelection
.map { CollectionOfOne(.selectable($0.qualifiedSelectable(with: alias))) }
.joined(separator: CollectionOfOne(.sql(", "))))
}
/// Appends the selectable SQL.
///
/// // SELECT * FROM player
@@ -147,14 +163,27 @@ extension SQLInterpolation {
elements.append(.orderingTerm(ordering))
}
/// Appends the request SQL, wrapped in parentheses
/// Appends the request SQL (not wrapped inside 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)
/// SELECT * FROM player WHERE score = (\(subQuery))
/// """
public mutating func appendInterpolation<T>(_ request: SQLRequest<T>) {
elements.append(.subQuery(request.sqlLiteral))
public mutating func appendInterpolation<RowDecoder>(_ request: SQLRequest<RowDecoder>) {
elements.append(.subquery(request.sqlLiteral.sql))
}
/// Appends the request SQL (not wrapped inside parentheses).
///
/// // SELECT name FROM player WHERE score = (SELECT MAX(score) FROM player)
/// let subQuery = Player.select(max(Column("score")))
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE score = (\(subQuery))
/// """
public mutating func appendInterpolation<RowDecoder>(_ request: QueryInterfaceRequest<RowDecoder>) {
elements.append(.subquery { context in
try SQLQueryGenerator(query: request.query).sql(context)
})
}
}
@@ -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.
+18 -15
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)
-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:
+9 -5
View File
@@ -52,8 +52,12 @@ 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"
ifeq ($(TRAVIS),true)
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=13.4"
else
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=13.4.1"
endif
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 +391,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 \
--module-version 5.0.0-beta \
--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/ \
--output Documentation/Reference \
--xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS
else
+112 -310
View File
@@ -11,13 +11,13 @@
---
**Latest release**: [GRDB5 branch](https://github.com/groue/GRDB.swift/tree/GRDB5) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
**Latest release**: May 2, 2020 • version 5.0.0-beta • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
**Requirements**: iOS 9.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ &bull; Swift 5.2+ / Xcode 11.4+
| Swift version | GRDB version |
| ------------- | ----------------------------------------------------------- |
| **Swift 5.2** | [GRDB5 branch](https://github.com/groue/GRDB.swift/tree/GRDB5) |
| **Swift 5.2** | **v5.0.0-beta**, [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0)|
| Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
| Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
| Swift 4.2 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
@@ -70,7 +70,7 @@ GRDB ships with:
- [Query Interface](#the-query-interface): A swift way to avoid the SQL language.
- [Associations](Documentation/AssociationsBasics.md): Relations and joins between record types.
- [WAL Mode Support](#database-pools): Extra performance for multi-threaded applications.
- [Migrations](#migrations): Transform your database as your application evolves.
- [Migrations]: Transform your database as your application evolves.
- [Database Observation](#database-changes-observation): Observe database changes and transactions.
- [Full-Text Search]
- [Encryption](#encryption)
@@ -263,7 +263,7 @@ Documentation
#### Reference
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/4.14/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
#### Getting Started
@@ -282,7 +282,7 @@ Documentation
#### Application Tools
- [Migrations](#migrations): Transform your database as your application evolves.
- [Migrations]: Transform your database as your application evolves.
- [Full-Text Search]: Perform efficient and customizable full-text searches.
- [Joined Queries Support](#joined-queries-support): Consume complex joined queries.
- [Database Changes Observation](#database-changes-observation): Observe database changes and transactions.
@@ -304,7 +304,7 @@ Documentation
#### General Guides & Good Practices
- :bulb: [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md)
- :bulb: [Migrating From GRDB 3 to GRDB 4](Documentation/GRDB3MigrationGuide.md)
- :bulb: [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
- :bulb: [Issues tagged "best practices"](https://github.com/groue/GRDB.swift/issues?q=is%3Aissue+label%3A%22best+practices%22)
- :question: [Issues tagged "question"](https://github.com/groue/GRDB.swift/issues?utf8=✓&q=is%3Aissue%20label%3Aquestion)
- :blue_book: [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md)
@@ -478,7 +478,7 @@ let dbQueue = try DatabaseQueue(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/4.14/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/Configuration.html) for more details.
## Database Pools
@@ -559,7 +559,7 @@ let dbPool = try DatabasePool(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/4.14/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/Configuration.html) for more details.
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
@@ -619,7 +619,7 @@ try dbQueue.write { db in
}
```
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.14/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
You can also embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details.
@@ -817,7 +817,7 @@ Both arrays and cursors can iterate over database results. How do you choose one
- **Cursors are granted with direct access to SQLite,** unlike arrays that have to take the time to copy database values. If you look after extra performance, you may prefer cursors over arrays.
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/4.14/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
```swift
// Prints all Github links
@@ -899,7 +899,7 @@ let rows = try Row.fetchAll(db,
arguments: ["name": "Arthur"])
```
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.14/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care:
@@ -1182,7 +1182,7 @@ GRDB ships with built-in support for the following value types:
- Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol.
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/4.14/Structs/StatementArguments.html):
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/StatementArguments.html):
```swift
let url: URL = ...
@@ -1589,7 +1589,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
}
```
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/4.14/Structs/Configuration.html) configuration flag:
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/Configuration.html) configuration flag:
```swift
// fatal error: A transaction has been left opened at the end of a database access
@@ -1703,7 +1703,7 @@ try dbQueue.write { db in
}
```
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.14/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
```swift
updateStatement.arguments = ["name": "Arthur", "score": 1000]
@@ -1962,7 +1962,7 @@ row["consumed"] // "Hello"
row["produced"] // nil
```
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/4.14/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters, described below.
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters, described below.
To see how row adapters can be used, see [Joined Queries Support](#joined-queries-support).
@@ -2417,7 +2417,7 @@ try Place.fetchAll(db, sql: "SELECT ...", arguments:...) // [Place]
try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place?
```
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.14/Structs/StatementArguments.html) for more information about the query arguments.
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/StatementArguments.html) for more information about the query arguments.
> :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`.
@@ -2796,7 +2796,7 @@ protocol EncodableRecord {
}
```
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/4.14/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.14/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.14/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
> :point_up: **Note**: there is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs, and uuid strings).
@@ -3909,7 +3909,7 @@ try db.alter(table: "player") { t in
}
```
> :point_up: **Note**: SQLite restricts the possible table alterations, and may require you to recreate dependent triggers or views. See the documentation of the [ALTER TABLE](https://www.sqlite.org/lang_altertable.html) for details. See [Advanced Database Schema Changes](#advanced-database-schema-changes) for a way to lift restrictions.
> :point_up: **Note**: SQLite restricts the possible table alterations, and may require you to recreate dependent triggers or views. See the documentation of the [ALTER TABLE](https://www.sqlite.org/lang_altertable.html) for details. See [Advanced Database Schema Changes](Documentation/Migrations.md#advanced-database-schema-changes) for a way to lift restrictions.
### Drop Tables
@@ -4010,7 +4010,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
- `annotated(with: aggregate)` extends the selection with [association aggregates](Documentation/AssociationsBasics.md#association-aggregates).
```swift
// 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
@@ -4086,7 +4086,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
// FROM team
// LEFT JOIN player ON player.teamId = team.id
// GROUP BY team.id
// HAVING COUNT(DISTINCT player.rowid) >= 5
// HAVING COUNT(DISTINCT player.id) >= 5
Team.having(Team.players.count >= 5)
```
@@ -4181,7 +4181,7 @@ Player // SELECT * FROM player
```
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/4.14/Structs/StatementArguments.html):
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/StatementArguments.html):
```swift
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
@@ -4258,6 +4258,18 @@ Feed [requests](#requests) with SQL expressions built from your Swift code:
Rectangle.filter(widthColumn < heightColumn)
```
Subqueries are supported:
```swift
// SELECT * FROM player WHERE score = (SELECT max(score) FROM player)
let maximumScore = Player.select(max(scoreColumn))
Player.filter(scoreColumn == maximumScore)
// SELECT * FROM player WHERE score = (SELECT max(score) FROM player)
let maximumScore: SQLRequest<Int> = "SELECT max(score) FROM player"
Player.filter(scoreColumn == maximumScore)
```
> :point_up: **Note**: SQLite string comparison, by default, is case-sensitive and not Unicode-aware. See [string comparison](#string-comparison) if you need more control.
- `*`, `/`, `+`, `-`
@@ -4353,6 +4365,18 @@ Feed [requests](#requests) with SQL expressions built from your Swift code:
Player.filter(("A"..<"N").contains(initialColumn))
```
To check inclusion inside a subquery, call the `contains` method as well:
```swift
// SELECT * FROM player WHERE id IN (SELECT playerId FROM playerSelection)
let selectedPlayerIds = PlayerSelection.select(playerIdColumn)
Player.filter(selectedPlayerIds.contains(idColumn))
// SELECT * FROM player WHERE id IN (SELECT playerId FROM playerSelection)
let selectedPlayerIds: SQLRequest<Int64> = "SELECT playerId FROM playerSelection"
Player.filter(selectedPlayerIds.contains(idColumn))
```
> :point_up: **Note**: SQLite string comparison, by default, is case-sensitive and not Unicode-aware. See [string comparison](#string-comparison) if you need more control.
- `LIKE`
@@ -4799,7 +4823,7 @@ let request = Player.all()
**To build custom requests**, you can use one of the built-in requests, derive requests from other requests, or create your own request type that adopts the [FetchRequest](#fetchrequest-protocol) protocol.
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/4.14/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example:
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example:
```swift
extension Player {
@@ -4842,7 +4866,7 @@ let request = Player.all()
- The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method.
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/4.14/Structs/AnyFetchRequest.html): a [type-erased](http://chris.eidhof.nl/post/type-erasers-in-swift/) request.
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/AnyFetchRequest.html): a [type-erased](http://chris.eidhof.nl/post/type-erasers-in-swift/) request.
### Fetching From Custom Requests
@@ -4874,132 +4898,6 @@ See [fetching methods](#fetching-methods) for information about the `fetchCursor
The RowDecoder type associated with the FetchRequest does not have to be Row, DatabaseValueConvertible, or FetchableRecord. See the [Beyond FetchableRecord] chapter for more information.
## 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](#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,** starting SQLite 3.7.16+ (iOS 9.0+ /
+ / tvOS 9.0+ / watchOS 2.0+ / [custom SQLite build] / [SQLCipher](#encryption)). 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:
```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"
```
Check if consecutive migrations have been applied:
```swift
if try dbQueue.read(migrator.hasCompletedMigrations) {
// All migrations have been applied, up to the last one.
}
if try dbQueue.read(migrator.completedMigrations).last == "v2" {
// All migrations up to "v2" have been applied, and no further.
}
if try dbQueue.read(migrator.completedMigrations).contains("v2") {
// All migrations up to "v2" have been applied, and maybe further.
}
```
Check if individual migrations have been applied:
```swift
if try dbQueue.read(migrator.appliedMigrations).contains("v2") {
// "v2" migration has been applied
}
```
### 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")
}
```
## Joined Queries Support
**GRDB helps consuming joined queries with complex selection.**
@@ -5048,7 +4946,6 @@ Unlike the name-mangling technique, splitting rows keeps SQL legible, accepts yo
- [Splitting Rows, an Introduction](#splitting-rows-an-introduction)
- [Splitting Rows, the Record Way](#splitting-rows-the-record-way)
- [Splitting Rows, the Request Way](#splitting-rows-the-request-way)
- [Splitting Rows, the Codable Way](#splitting-rows-the-codable-way)
@@ -5171,21 +5068,22 @@ extension PlayerInfo: FetchableRecord {
}
```
Let's now write the method that fetches PlayerInfo records:
Now we write a method that returns a [custom request](#custom-requests), and then build the fetching method on top of that request:
```swift
extension PlayerInfo {
static func fetchAll(_ db: Database) throws -> [PlayerInfo] {
/// The request for all player infos
static func all() -> AdaptedFetchRequest<SQLRequest<PlayerInfo>> {
```
To acknowledge that both Player and Team records may customize their selection of the "player" and "team" columns, we'll write our SQL in a slightly different way:
```swift
// Let Player and Team customize their selection:
let sql = """
let request: SQLRequest<PlayerInfo> = """
SELECT
\(Player.selectionSQL()), -- instead of player.*
\(Team.selectionSQL()), -- instead of team.*
\(columnsOf: Player.self), -- instead of player.*
\(columnsOf: Team.self), -- instead of team.*
MAX(round.score) AS maxScore
FROM player
LEFT JOIN team ON ...
@@ -5194,41 +5092,34 @@ To acknowledge that both Player and Team records may customize their selection o
"""
```
`Player.selectionSQL()` will output `player.*`, unless Player defines a [customized selection](#columns-selected-by-a-request).
Our SQL is no longer a regular String, but an `SQLRequest<PlayerInfo>` which profits from [SQL Interpolation]. Inside this request, `\(columnsOf: Player.self)` outputs `player.*`, unless Player defines a [customized selection](#columns-selected-by-a-request).
> :point_up: **Note**: you may also use SQL table aliases:
>
> ```swift
> let sql = """
> SELECT
> \(Player.selectionSQL(alias: "p")),
> \(Team.selectionSQL(alias: "t")),
> MAX(r.score) AS maxScore
> FROM player p
> LEFT JOIN team t ON ...
> LEFT JOIN round r ON ...
> GROUP BY ...
> """
> ```
Now we need to build adapters.
Now is the time to build adapters (taking in account the customized selection of both player and team). We use the `splittingRowAdapters` global function, which builds row adapters of desired widths:
We use the `splittingRowAdapters` global function, whose job is precisely to build row adapters of desired widths:
And since counting table columns require a database connection, we use the `adapted(_:)` request method. It allows requests to adapt themselves right before execution, when a database connection is available.
```swift
let adapters = try splittingRowAdapters(columnCounts: [
Player.numberOfSelectedColumns(db),
Team.numberOfSelectedColumns(db)])
let adapter = ScopeAdapter([
Scopes.player: adapters[0],
Scopes.team: adapters[1]])
return request.adapted { db in
let adapters = try splittingRowAdapters(columnCounts: [
Player.numberOfSelectedColumns(db),
Team.numberOfSelectedColumns(db)])
return ScopeAdapter([
Scopes.player: adapters[0],
Scopes.team: adapters[1]])
}
}
```
> :point_up: **Note**: `splittingRowAdapters` returns as many adapters as necessary to fully split a row. In the example above, it returns *three* adapters: one for player, one for team, and one for the remaining columns.
And finally, we can fetch player infos:
And finally, we can define the fetching method:
```swift
return try PlayerInfo.fetchAll(db, sql: sql, adapter: adapter)
/// Fetches all player infos
static func fetchAll(_ db: Database) throws -> [PlayerInfo] {
try all().fetchAll(db)
}
}
```
@@ -5246,95 +5137,16 @@ let playerInfos = try dbQueue.read { db in
> :bulb: In this chapter, we have learned:
>
> - how to define a `FetchableRecord` record that consumes rows fetched from a joined query.
> - how to use `selectionSQL` and `numberOfSelectedColumns` in order to deal with nested record types that define custom selection.
> - how to use [SQL Interpolation] and `numberOfSelectedColumns` in order to deal with nested record types that define custom selection.
> - how to use `splittingRowAdapters` in order to streamline the definition of row slices.
> - how to gather all relevant methods and constants in a record type, fully responsible of its relationship with the database.
### Splitting Rows, the Request Way
The `PlayerInfo.fetchAll` method [above](#splitting-rows-the-record-way) directly fetches records. It's all good, but in order to profit from [database observation](#database-changes-observation), you'll need a [custom request](#custom-requests) that defines a database query.
It is recommended that you read the previous paragraphs before you dive in this sample code. We start with the same PlayerInfo record as above:
```swift
struct PlayerInfo {
var player: Player
var team: Team?
var maxScore: Int
}
/// PlayerInfo can decode rows:
extension PlayerInfo: FetchableRecord {
private enum Scopes {
static let player = "player"
static let team = "team"
}
init(row: Row) {
player = row[Scopes.player]
team = row[Scopes.team]
maxScore = row["maxScore"]
}
}
```
Now we write a method that returns a request, and build the fetching method on top of that request:
```swift
extension PlayerInfo {
/// The request for all player infos
static func all() -> AdaptedFetchRequest<SQLRequest<PlayerInfo>> {
let sql = """
SELECT
\(Player.selectionSQL()),
\(Team.selectionSQL()),
MAX(round.score) AS maxScore
FROM player
LEFT JOIN team ON ...
LEFT JOIN round ON ...
GROUP BY ...
"""
return SQLRequest<PlayerInfo>(sql: sql).adapted { db in
let adapters = try splittingRowAdapters(columnCounts: [
Player.numberOfSelectedColumns(db),
Team.numberOfSelectedColumns(db)])
return ScopeAdapter([
Scopes.player: adapters[0],
Scopes.team: adapters[1]])
}
}
/// Fetches all player infos
static func fetchAll(_ db: Database) throws -> [PlayerInfo] {
try all().fetchAll(db)
}
}
```
It is now time to use our request:
```swift
// Fetch player infos
let playerInfos = try dbQueue.read { db in
try PlayerInfo.fetchAll(db)
}
// Track database transactions that change player infos:
let observation = DatabaseRegionObservation(tracking: PlayerInfo.all())
let observer = try observation.start(in: dbQueue) { (db: Database) in
print("PlayerInfo were changed")
}
```
> :bulb: In this chapter, we have learned how to define a custom request that can both fetch records from joined queries, and feed database observation tools.
### Splitting Rows, the Codable Way
[Codable Records] build on top of the standard Decodable protocol in order to decode database rows.
You can consume complex joined queries with Codable records as well. As a demonstration, we'll rewrite the [above](#splitting-rows-the-request-way) sample code:
You can consume complex joined queries with Codable records as well. As a demonstration, we'll rewrite the [above](#splitting-rows-the-record-way) sample code:
```swift
struct Player: Decodable, FetchableRecord, TableRecord {
@@ -5355,17 +5167,17 @@ struct PlayerInfo: Decodable, FetchableRecord {
extension PlayerInfo {
/// The request for all player infos
static func all() -> AdaptedFetchRequest<SQLRequest<PlayerInfo>> {
let sql = """
let request: SQLRequest<PlayerInfo> = """
SELECT
\(Player.selectionSQL()),
\(Team.selectionSQL()),
\(columnsOf: Player.self),
\(columnsOf: Team.self),
MAX(round.score) AS maxScore
FROM player
LEFT JOIN team ON ...
LEFT JOIN round ON ...
GROUP BY ...
"""
return SQLRequest<PlayerInfo>(sql: sql).adapted { db in
return request.adapted { db in
let adapters = try splittingRowAdapters(columnCounts: [
Player.numberOfSelectedColumns(db),
Team.numberOfSelectedColumns(db)])
@@ -5385,13 +5197,6 @@ extension PlayerInfo {
let playerInfos = try dbQueue.read { db in
try PlayerInfo.fetchAll(db)
}
// Track player infos with RxRGDB:
PlayerInfo.all()
.rx.fetchAll(in: dbQueue)
.subscribe(onNext: { (playerInfos: [PlayerInfo]) in
print("Player infos have changed")
})
```
> :bulb: In this chapter, we have learned how to use the `Decodable` protocol and its associated `CodingKeys` enum in order to dry up our code.
@@ -5595,7 +5400,7 @@ import RxSwift
let observation = ValueObservation.tracking(Player.fetchAll)
let disposable = observation.rx.changes(in: dbQueue).subscribe(
let disposable = observation.rx.observe(in: dbQueue).subscribe(
onNext: { (players: [Player]) in
print("fresh players", players)
},
@@ -5830,7 +5635,7 @@ When needed, you can help GRDB optimize observations and reduce database content
let observation = ValueObservation.tracking(Player.fetchAll)
let observable = observation.rx
.changes(in: dbQueue)
.observe(in: dbQueue)
.share(replay: 1, scope: .whileConnected)
```
@@ -6197,7 +6002,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan
### DatabaseRegion
**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/4.14/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**.
**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**.
A request knows which database modifications can impact its results. It can communicate this information to [transaction observers](#transactionobserver-protocol) by the way of a DatabaseRegion.
@@ -6207,7 +6012,7 @@ DatabaseRegion fuels, for example, [ValueObservation and DatabaseRegionObservati
For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table.
For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/4.14/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
#### The DatabaseRegionConvertible Protocol
@@ -7302,11 +7107,11 @@ try snapshot2.read { db in
### DatabaseWriter and DatabaseReader Protocols
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/4.14/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/4.14/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only.
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only.
These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example:
- [Migrations](#migrations)
- [Migrations]
- [DatabaseRegionObservation]
- [ValueObservation]
- [GRDBCombine]
@@ -7841,23 +7646,18 @@ Database accesses that run in background threads postpone the closing of connect
When you want to debug a request that does not deliver the expected results, you may want to print the SQL that is actually executed.
You can turn your request into a `SQLRequest` instance:
You can compile the request into a prepared statement:
```swift
try dbQueue.read { db in
let request = Wine
.filter(originColumn == "Burgundy")
.order(priceColumn)
let sqlRequest = try SQLRequest(db, request: request)
print(sqlRequest.sql)
// Prints SELECT * FROM wine WHERE origin = ? ORDER BY price
print(sqlRequest.arguments)
// Prints ["Burgundy"]
let request = Player.filter(Column("name") == "O'Brien")
let statement = try request.makePreparedRequest(db).statement
print(statement.sql) // "SELECT * FROM player WHERE name = ?"
print(statement.arguments) // ["O'Brien"]
}
```
Another option is to setup a tracing function that will print out all SQL requests executed by your application. You provide the trace function when you connect to the database:
Another option is to setup a tracing function that prints out all SQL requests executed by your application. You provide the trace function when you connect to the database:
```swift
var config = Configuration()
@@ -7865,11 +7665,8 @@ config.trace = { print($0) } // Prints all SQL statements
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
try dbQueue.read { db in
let wines = Wine
.filter(originColumn == "Burgundy")
.order(priceColumn)
.fetchAll(db)
// Prints SELECT * FROM wine WHERE origin = 'Burgundy' ORDER BY price
let players = try Player.filter(Column("name") == "O'Brien").fetchAll(db)
// Prints SELECT * FROM player WHERE name = 'O''Brien'
}
```
@@ -7992,10 +7789,30 @@ Sample Code
This chapter has been renamed [Record Comparison].
#### Customized Decoding of Database Rows
This chapter has been renamed [Beyond FetchableRecord].
#### Dealing with External Connections
This chapter has been superseded by [App Group Containers].
#### Enabling FTS5 Support
This chapter has [moved](Documentation/FullTextSearch.md#enabling-fts5-support).
#### FetchedRecordsController
This chapter has [moved](Documentation/FetchedRecordsController.md).
#### Full-Text Search
This chapter has [moved](Documentation/FullTextSearch.md).
#### Migrations
This chapter has [moved](Documentation/Migrations.md).
#### Persistable Protocol
This protocol has been renamed [PersistableRecord] in GRDB 3.0.
@@ -8008,22 +7825,6 @@ This protocol has been renamed [FetchableRecord] in GRDB 3.0.
This protocol has been renamed [TableRecord] in GRDB 3.0.
#### Customized Decoding of Database Rows
This chapter has been renamed [Beyond FetchableRecord].
#### Full-Text Search
This chapter has [moved](Documentation/FullTextSearch.md).
#### Enabling FTS5 Support
This chapter has [moved](Documentation/FullTextSearch.md#enabling-fts5-support).
#### Dealing with External Connections
This chapter has been superseded by [App Group Containers].
#### ValueObservation and DatabaseRegionObservation
This chapter has been superseded by [ValueObservation] and [DatabaseRegionObservation].
@@ -8038,6 +7839,7 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv
[Date and UUID Coding Strategies]: #date-and-uuid-coding-strategies
[Fetching from Requests]: #fetching-from-requests
[Full-Text Search]: Documentation/FullTextSearch.md
[Migrations]: Documentation/Migrations.md
[The Implicit RowID Primary Key]: #the-implicit-rowid-primary-key
[The userInfo Dictionary]: #the-userinfo-dictionary
[JSON Columns]: #json-columns
+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</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+3 -8
View File
@@ -6,27 +6,22 @@
- [ ] 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
- [ ] 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.* ...)`
+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)
}
}
}
@@ -1,7 +1,7 @@
import XCTest
import Dispatch
import Foundation
import GRDB
@testable import GRDB
class DatabasePoolConcurrencyTests: GRDBTestCase {
@@ -267,6 +267,8 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
}
func testReadError() throws {
// Necessary for this test to run as quickly as possible
dbConfiguration.readonlyBusyMode = .immediateError
let dbPool = try makeDatabasePool()
// Block 1 Block 2
@@ -1073,6 +1075,8 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
}
func testConcurrentReadError() throws {
// Necessary for this test to run as quickly as possible
dbConfiguration.readonlyBusyMode = .immediateError
let dbPool = try makeDatabasePool()
try dbPool.writeWithoutTransaction { db in
try db.execute(sql: "PRAGMA locking_mode=EXCLUSIVE")
@@ -1156,6 +1160,8 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
}
func testAsyncConcurrentReadError() throws {
// Necessary for this test to run as quickly as possible
dbConfiguration.readonlyBusyMode = .immediateError
let dbPool = try makeDatabasePool()
var readError: DatabaseError? = nil
let expectation = self.expectation(description: "read")
@@ -453,11 +453,6 @@ class DatabaseRegionTests : GRDBTestCase {
let derivedRequest: AdaptedFetchRequest = request.adapted { db in SuffixRowAdapter(fromIndex: 1) }
try XCTAssertEqual(derivedRequest.databaseRegion(db).description, "foo(a,id)[1,2,3]")
}
do {
// SQL request loses region info
let derivedRequest = try SQLRequest(db, request: request)
try XCTAssertEqual(derivedRequest.databaseRegion(db).description, "foo(a,id)")
}
}
}
@@ -3,29 +3,49 @@ import XCTest
@testable import GRDB
class DatabaseValueConvertibleEscapingTests: GRDBTestCase {
func testText() {
XCTAssertEqual("".databaseValue.quotedSQL(), "''")
XCTAssertEqual("foo".databaseValue.quotedSQL(), "'foo'")
XCTAssertEqual("\"foo\"".databaseValue.quotedSQL(), "'\"foo\"'")
XCTAssertEqual("'foo'".databaseValue.quotedSQL(), "'''foo'''")
func testNull() throws {
try makeDatabaseQueue().inDatabase { db in
try XCTAssertEqual(DatabaseValue.null.quotedSQL(db), "NULL")
}
}
func testInteger() {
XCTAssertEqual(0.databaseValue.quotedSQL(), "0")
XCTAssertEqual(Int64.min.databaseValue.quotedSQL(), "-9223372036854775808")
XCTAssertEqual(Int64.max.databaseValue.quotedSQL(), "9223372036854775807")
func testText() throws {
try makeDatabaseQueue().inDatabase { db in
try XCTAssertEqual("".databaseValue.quotedSQL(db), "''")
try XCTAssertEqual("foo".databaseValue.quotedSQL(db), "'foo'")
try XCTAssertEqual("\"foo\"".databaseValue.quotedSQL(db), #"'"foo"'"#)
try XCTAssertEqual("'foo'".databaseValue.quotedSQL(db), "'''foo'''")
}
}
func testDouble() {
XCTAssertEqual(0.0.databaseValue.quotedSQL(), "0.0")
XCTAssertEqual(1.0.databaseValue.quotedSQL(), "1.0")
XCTAssertEqual((-1.0).databaseValue.quotedSQL(), "-1.0")
XCTAssertEqual(1.5.databaseValue.quotedSQL(), "1.5")
func testInteger() throws {
try makeDatabaseQueue().inDatabase { db in
try XCTAssertEqual(0.databaseValue.quotedSQL(db), "0")
try XCTAssertEqual(Int64.min.databaseValue.quotedSQL(db), "-9223372036854775808")
try XCTAssertEqual(Int64.max.databaseValue.quotedSQL(db), "9223372036854775807")
}
}
func testBlob() {
XCTAssertEqual(Data().databaseValue.quotedSQL(), "X''")
XCTAssertEqual("foo".data(using: .utf8)!.databaseValue.quotedSQL(), "X'666F6F'")
func testDouble() throws {
try makeDatabaseQueue().inDatabase { db in
try XCTAssertEqual(0.0.databaseValue.quotedSQL(db), "0.0")
try XCTAssertEqual(1.0.databaseValue.quotedSQL(db), "1.0")
try XCTAssertEqual((-1.0).databaseValue.quotedSQL(db), "-1.0")
try XCTAssertEqual(1.5.databaseValue.quotedSQL(db), "1.5")
}
}
func testBlob() throws {
try makeDatabaseQueue().inDatabase { db in
try XCTAssertEqual(Data().databaseValue.quotedSQL(db), "X''")
try XCTAssertEqual("foo".data(using: .utf8)!.databaseValue.quotedSQL(db), "X'666F6F'")
}
}
func testComplexExpression() throws {
try makeDatabaseQueue().inDatabase { db in
try XCTAssertEqual((Column("a") == 12).quotedSQL(db), #""a" = 12"#)
}
}
}
@@ -1053,42 +1053,39 @@ extension FetchableRecordDecodableTests {
}
}
// MARK: - Ill-defined records
// This is a regression test for https://github.com/groue/GRDB.swift/issues/664
func testIllDecoding() throws {
struct Left: Decodable { }
struct Right: Decodable { }
func testMissingKeys1() throws {
struct A: Decodable { }
struct B: Decodable { }
struct C: Decodable { }
struct Composed: Decodable, FetchableRecord {
var left: Left
var right: Right
}
let decoder = RowDecoder()
do {
_ = try decoder.decode(Composed.self, from: [:])
XCTFail("Expected error")
} catch let DecodingError.keyNotFound(key, context) {
XCTAssertEqual(key.stringValue, "left")
XCTAssertEqual(context.debugDescription, "No such key: left")
var a: A
var b: B?
var c: C?
}
// No error expected:
// - a is succesfully decoded because it consumes the one and unique
// allowed missing key
// - b and c are succesfully decoded, because they are optionals, and
// all optionals decode missing keys are nil. This is because GRDB
// records accept rows with missing columns, and b and c may want to
// decode columns.
_ = try RowDecoder().decode(Composed.self, from: [:])
}
// This is a regression test for https://github.com/groue/GRDB.swift/issues/664
// TODO: make this test pass
// func testIllDecoding2() throws {
// struct Left: Decodable { }
// struct Right: Decodable { }
// struct Composed: Decodable, FetchableRecord {
// var left: Left
// var right: Right?
// }
// let decoder = RowDecoder()
// do {
// _ = try decoder.decode(Composed.self, from: [:])
// XCTFail("Expected error")
// } catch let DecodingError.keyNotFound(key, context) {
// XCTAssertEqual(key.stringValue, "left")
// XCTAssertEqual(context.debugDescription, "No such key: left")
// }
// }
func testMissingKeys2() throws {
struct A: Decodable { }
struct B: Decodable { }
struct Composed: Decodable, FetchableRecord {
var a: A
var b: B
}
do {
_ = try RowDecoder().decode(Composed.self, from: [:])
XCTFail("Expected error")
} catch DecodingError.keyNotFound {
// a or b can not be decoded because only one key is allowed to be missing
}
}
}
+15 -4
View File
@@ -145,8 +145,7 @@ class GRDBTestCase: XCTestCase {
// Compare SQL strings (ignoring leading and trailing white space and semicolons.
func assertEqualSQL<Request: FetchRequest>(_ db: Database, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws {
let request = try request.makePreparedRequest(db, forSingleResult: false)
try request.statement.makeCursor().next()
try request.makeStatement(db).makeCursor().next()
assertEqualSQL(lastSQLQuery, sql, file: file, line: line)
}
@@ -159,13 +158,25 @@ class GRDBTestCase: XCTestCase {
func sql<Request: FetchRequest>(_ databaseReader: DatabaseReader, _ request: Request) -> String {
try! databaseReader.unsafeRead { db in
let request = try request.makePreparedRequest(db, forSingleResult: false)
try request.statement.makeCursor().next()
try request.makeStatement(db).makeCursor().next()
return lastSQLQuery
}
}
}
extension FetchRequest {
/// Turn request into a statement
func makeStatement(_ db: Database) throws -> SelectStatement {
try makePreparedRequest(db, forSingleResult: false).statement
}
/// Turn request into SQL and arguments
func build(_ db: Database) throws -> (sql: String, arguments: StatementArguments) {
let statement = try makePreparedRequest(db, forSingleResult: false).statement
return (sql: statement.sql, arguments: statement.arguments)
}
}
/// A type-erased ValueReducer.
public struct AnyValueReducer<Fetched, Value>: _ValueReducer {
private var _fetch: (Database) throws -> Fetched
+1 -1
View File
@@ -57,7 +57,7 @@ class IndexInfoTests: GRDBTestCase {
try XCTAssertTrue(db.table("persons", hasUniqueKey: ["email"]))
try XCTAssertFalse(db.table("persons", hasUniqueKey: []))
try XCTAssertFalse(db.table("persons", hasUniqueKey: ["name"]))
try XCTAssertFalse(db.table("persons", hasUniqueKey: ["id", "email"])) // TODO: is it expected?
try XCTAssertTrue(db.table("persons", hasUniqueKey: ["id", "email"]))
try db.execute(sql: "CREATE TABLE citizenships (year INTEGER, personId INTEGER NOT NULL, countryIsoCode TEXT NOT NULL, PRIMARY KEY (personId, countryIsoCode))")
try db.execute(sql: "CREATE INDEX citizenshipsOnYear ON citizenships(year)")
+17 -13
View File
@@ -18,12 +18,12 @@ let expectedSQL = """
ORDER BY t1.id
"""
let testedSQL = """
let testedLiteral: SQLLiteral = """
SELECT
\(T1.selectionSQL()),
\(T2.selectionSQL(alias: "t2Left")),
\(T2.selectionSQL(alias: "t2Right")),
\(T3.selectionSQL()),
\(columnsOf: T1.self),
\(columnsOf: T2.self, tableAlias: "t2Left"),
\(columnsOf: T2.self, tableAlias: "t2Right"),
\(columnsOf: T3.self),
COUNT(DISTINCT t5.id) AS t5count
FROM t1
LEFT JOIN t2 t2Left ON t2Left.t1id = t1.id AND t2Left.name = 'left'
@@ -93,7 +93,7 @@ private struct FlatModel: FetchableRecord {
}
static func all() -> AdaptedFetchRequest<SQLRequest<FlatModel>> {
SQLRequest<FlatModel>(sql: testedSQL).adapted { db in
SQLRequest<FlatModel>(literal: testedLiteral).adapted { db in
let adapters = try splittingRowAdapters(columnCounts: [
T1.numberOfSelectedColumns(db),
T2.numberOfSelectedColumns(db),
@@ -109,7 +109,7 @@ private struct FlatModel: FetchableRecord {
}
static func hierarchicalAll() -> AdaptedFetchRequest<SQLRequest<CodableFlatModel>> {
SQLRequest<CodableFlatModel>(sql: testedSQL).adapted { db in
SQLRequest<CodableFlatModel>(literal: testedLiteral).adapted { db in
let adapters = try splittingRowAdapters(columnCounts: [
T1.numberOfSelectedColumns(db),
T2.numberOfSelectedColumns(db),
@@ -134,7 +134,7 @@ private struct CodableFlatModel: FetchableRecord, Codable {
var t5count: Int
static func all() -> AdaptedFetchRequest<SQLRequest<CodableFlatModel>> {
SQLRequest<CodableFlatModel>(sql: testedSQL).adapted { db in
SQLRequest<CodableFlatModel>(literal: testedLiteral).adapted { db in
let adapters = try splittingRowAdapters(columnCounts: [
T1.numberOfSelectedColumns(db),
T2.numberOfSelectedColumns(db),
@@ -149,7 +149,7 @@ private struct CodableFlatModel: FetchableRecord, Codable {
}
static func hierarchicalAll() -> AdaptedFetchRequest<SQLRequest<CodableFlatModel>> {
SQLRequest<CodableFlatModel>(sql: testedSQL).adapted { db in
SQLRequest<CodableFlatModel>(literal: testedLiteral).adapted { db in
let adapters = try splittingRowAdapters(columnCounts: [
T1.numberOfSelectedColumns(db),
T2.numberOfSelectedColumns(db),
@@ -177,7 +177,7 @@ private struct CodableNestedModel: FetchableRecord, Codable {
var t5count: Int
static func all() -> AdaptedFetchRequest<SQLRequest<CodableNestedModel>> {
SQLRequest<CodableNestedModel>(sql: testedSQL).adapted { db in
SQLRequest<CodableNestedModel>(literal: testedLiteral).adapted { db in
let adapters = try splittingRowAdapters(columnCounts: [
T1.numberOfSelectedColumns(db),
T2.numberOfSelectedColumns(db),
@@ -253,7 +253,7 @@ class JoinSupportTests: GRDBTestCase {
func testSampleData() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let rows = try Row.fetchAll(db, sql: expectedSQL)
let rows = try SQLRequest<Row>(literal: testedLiteral).fetchAll(db)
XCTAssertEqual(rows.count, 3)
XCTAssertEqual(rows[0], [
// t1.*
@@ -292,13 +292,17 @@ class JoinSupportTests: GRDBTestCase {
}
func testTestedSQL() throws {
XCTAssertEqual(testedSQL, expectedSQL)
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let (testedSQL, _) = try testedLiteral.build(db)
XCTAssertEqual(testedSQL, expectedSQL)
}
}
func testSplittingRowAdapters() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = SQLRequest<Row>(sql: testedSQL).adapted { db in
let request = SQLRequest<Row>(literal: testedLiteral).adapted { db in
let adapters = try splittingRowAdapters(columnCounts: [
T1.numberOfSelectedColumns(db),
T2.numberOfSelectedColumns(db),
@@ -205,8 +205,8 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase {
do {
try Player.including(required: Player.team).deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "player" WHERE rowid IN (\
SELECT "player"."rowid" \
DELETE FROM "player" WHERE "id" IN (\
SELECT "player"."id" \
FROM "player" \
JOIN "team" ON "team"."id" = "player"."teamId")
""")
@@ -215,8 +215,8 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase {
let alias = TableAlias(name: "p")
try Player.aliased(alias).including(required: Player.team).deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "player" WHERE rowid IN (\
SELECT "p"."rowid" \
DELETE FROM "player" WHERE "id" IN (\
SELECT "p"."id" \
FROM "player" "p" \
JOIN "team" ON "team"."id" = "p"."teamId")
""")
@@ -224,12 +224,12 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase {
do {
try Team.having(Team.players.isEmpty).deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "team" WHERE rowid IN (\
SELECT "team"."rowid" \
DELETE FROM "team" WHERE "id" IN (\
SELECT "team"."id" \
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)
""")
}
do {
@@ -261,8 +261,8 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase {
do {
try Player.all().groupByPrimaryKey().deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "player" WHERE rowid IN (\
SELECT "rowid" \
DELETE FROM "player" WHERE "id" IN (\
SELECT "id" \
FROM "player" \
GROUP BY "id")
""")
@@ -270,8 +270,8 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase {
do {
try Player.all().group(Column.rowID).deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "player" WHERE rowid IN (\
SELECT "rowid" \
DELETE FROM "player" WHERE "id" IN (\
SELECT "id" \
FROM "player" \
GROUP BY "rowid")
""")
@@ -279,7 +279,7 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase {
do {
try Passport.all().groupByPrimaryKey().deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "passport" WHERE rowid IN (\
DELETE FROM "passport" WHERE "rowid" IN (\
SELECT "rowid" \
FROM "passport" \
GROUP BY "countryCode", "citizenId")
@@ -288,7 +288,7 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase {
do {
try Passport.all().group(Column.rowID).deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "passport" WHERE rowid IN (\
DELETE FROM "passport" WHERE "rowid" IN (\
SELECT "rowid" \
FROM "passport" \
GROUP BY "rowid")
@@ -422,8 +422,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
do {
try Player.including(required: Player.team).updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE rowid IN (\
SELECT "player"."rowid" \
UPDATE "player" SET "score" = 0 WHERE "id" IN (\
SELECT "player"."id" \
FROM "player" \
JOIN "team" ON "team"."id" = "player"."teamId")
""")
@@ -432,8 +432,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
// Regression test for https://github.com/groue/GRDB.swift/issues/758
try Player.including(required: Player.team.filter(Column("active") == 1)).updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE rowid IN (\
SELECT "player"."rowid" \
UPDATE "player" SET "score" = 0 WHERE "id" IN (\
SELECT "player"."id" \
FROM "player" \
JOIN "team" ON ("team"."id" = "player"."teamId") AND ("team"."active" = 1))
""")
@@ -442,8 +442,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
let alias = TableAlias(name: "p")
try Player.aliased(alias).including(required: Player.team).updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE rowid IN (\
SELECT "p"."rowid" \
UPDATE "player" SET "score" = 0 WHERE "id" IN (\
SELECT "p"."id" \
FROM "player" "p" \
JOIN "team" ON "team"."id" = "p"."teamId")
""")
@@ -451,12 +451,12 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
do {
try Team.having(Team.players.isEmpty).updateAll(db, Column("active").set(to: false))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "team" SET "active" = 0 WHERE rowid IN (\
SELECT "team"."rowid" \
UPDATE "team" SET "active" = 0 WHERE "id" IN (\
SELECT "team"."id" \
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)
""")
}
do {
@@ -489,8 +489,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
do {
try Player.all().groupByPrimaryKey().updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE rowid IN (\
SELECT "rowid" \
UPDATE "player" SET "score" = 0 WHERE "id" IN (\
SELECT "id" \
FROM "player" \
GROUP BY "id")
""")
@@ -498,8 +498,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
do {
try Player.all().group(Column.rowID).updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE rowid IN (\
SELECT "rowid" \
UPDATE "player" SET "score" = 0 WHERE "id" IN (\
SELECT "id" \
FROM "player" \
GROUP BY "rowid")
""")
@@ -507,7 +507,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
do {
try Passport.all().groupByPrimaryKey().updateAll(db, Column("active").set(to: true))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "passport" SET "active" = 1 WHERE rowid IN (\
UPDATE "passport" SET "active" = 1 WHERE "rowid" IN (\
SELECT "rowid" \
FROM "passport" \
GROUP BY "countryCode", "citizenId")
@@ -516,7 +516,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
do {
try Passport.all().group(Column.rowID).updateAll(db, Column("active").set(to: true))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "passport" SET "active" = 1 WHERE rowid IN (\
UPDATE "passport" SET "active" = 1 WHERE "rowid" IN (\
SELECT "rowid" \
FROM "passport" \
GROUP BY "rowid")
@@ -195,6 +195,41 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
"SELECT * FROM \"readers\" WHERE (\"name\" >= 'A' COLLATE NOCASE) AND (\"name\" < 'z' COLLATE NOCASE)")
}
func testSubqueryContains() throws {
let dbQueue = try makeDatabaseQueue()
do {
let subquery = tableRequest.select(Col.age).filter(Col.name != nil).distinct()
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(subquery.contains(Col.age))),
"""
SELECT * FROM "readers" WHERE "age" IN \
(SELECT DISTINCT "age" FROM "readers" WHERE "name" IS NOT NULL)
""")
}
do {
let subquery = SQLRequest<Int>(sql: "SELECT ? UNION SELECT ?", arguments: [1, 2])
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(subquery.contains(Col.age + 1))),
"""
SELECT * FROM "readers" WHERE ("age" + 1) IN (SELECT 1 UNION SELECT 2)
""")
}
do {
let subquery1 = tableRequest.select(max(Col.age))
let subquery2 = tableRequest.filter(Col.age == subquery1)
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(subquery2.select(Col.id).contains(Col.id))),
"""
SELECT * FROM "readers" WHERE "id" IN (\
SELECT "id" FROM "readers" WHERE "age" = (\
SELECT MAX("age") FROM "readers"))
""")
}
}
func testGreaterThan() throws {
let dbQueue = try makeDatabaseQueue()
@@ -469,6 +504,28 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
"SELECT * FROM \"readers\" WHERE \"name\" = 'fOo' COLLATE localized_case_insensitive")
}
func testSubqueryEqual() throws {
let dbQueue = try makeDatabaseQueue()
do {
let subquery = tableRequest.select(max(Col.age))
XCTAssertEqual(
sql(dbQueue, tableRequest.filter(Col.age == subquery)),
"""
SELECT * FROM "readers" WHERE "age" = (SELECT MAX("age") FROM "readers")
""")
}
do {
let subquery = SQLRequest<Int>(sql: "SELECT MAX(age + ?) FROM readers", arguments: [1])
XCTAssertEqual(
sql(dbQueue, tableRequest.filter((Col.age + 2) == subquery)),
"""
SELECT * FROM "readers" WHERE ("age" + 2) = (SELECT MAX(age + 1) FROM readers)
""")
}
}
func testNotEqual() throws {
let dbQueue = try makeDatabaseQueue()
@@ -386,8 +386,7 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = MinimalRowID.orderByPrimaryKey()
let sqlRequest = try SQLRequest(db, request: request)
XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"minimalRowIDs\" ORDER BY \"id\"")
try assertEqualSQL(db, request, "SELECT * FROM \"minimalRowIDs\" ORDER BY \"id\"")
}
}
@@ -402,8 +402,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = MinimalSingle.orderByPrimaryKey()
let sqlRequest = try SQLRequest(db, request: request)
XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"minimalSingles\" ORDER BY \"UUID\"")
try assertEqualSQL(db, request, "SELECT * FROM \"minimalSingles\" ORDER BY \"UUID\"")
}
}
@@ -472,8 +472,7 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = Person.orderByPrimaryKey()
let sqlRequest = try SQLRequest(db, request: request)
XCTAssertEqual(sqlRequest.sql, "SELECT *, \"rowid\" FROM \"persons\" ORDER BY \"rowid\"")
try assertEqualSQL(db, request, "SELECT *, \"rowid\" FROM \"persons\" ORDER BY \"rowid\"")
}
}
@@ -425,8 +425,7 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = Citizenship.orderByPrimaryKey()
let sqlRequest = try SQLRequest(db, request: request)
XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"citizenships\" ORDER BY \"personName\", \"countryName\"")
try assertEqualSQL(db, request, "SELECT * FROM \"citizenships\" ORDER BY \"personName\", \"countryName\"")
}
}
@@ -120,8 +120,7 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = Item.orderByPrimaryKey()
let sqlRequest = try SQLRequest(db, request: request)
XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"items\" ORDER BY \"rowid\"")
try assertEqualSQL(db, request, "SELECT * FROM \"items\" ORDER BY \"rowid\"")
}
}
@@ -468,8 +468,7 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = Person.orderByPrimaryKey()
let sqlRequest = try SQLRequest(db, request: request)
XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"persons\" ORDER BY \"id\"")
try assertEqualSQL(db, request, "SELECT * FROM \"persons\" ORDER BY \"id\"")
}
}
@@ -416,8 +416,7 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = Pet.orderByPrimaryKey()
let sqlRequest = try SQLRequest(db, request: request)
XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"pets\" ORDER BY \"UUID\"")
try assertEqualSQL(db, request, "SELECT * FROM \"pets\" ORDER BY \"UUID\"")
}
}
@@ -409,8 +409,7 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = Email.orderByPrimaryKey()
let sqlRequest = try SQLRequest(db, request: request)
XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"emails\" ORDER BY \"email\"")
try assertEqualSQL(db, request, "SELECT * FROM \"emails\" ORDER BY \"email\"")
}
}
+20 -16
View File
@@ -3,23 +3,27 @@ import XCTest
@testable import GRDB
class SQLExpressionLiteralTests: GRDBTestCase {
func testWithArguments() {
let expression = Column("foo").collating(.nocase) == "'fooéı👨👨🏿🇫🇷🇨🇮'" && Column("baz") >= 1
var context = SQLGenerationContext.sqlLiteralContext
let sql = expression.expressionSQL(&context, wrappedInParenthesis: true)
XCTAssertEqual(sql, "((\"foo\" = ? COLLATE NOCASE) AND (\"baz\" >= ?))")
let values = context.arguments.values
XCTAssertEqual(values.count, 2)
XCTAssertEqual(values[0], "'fooéı👨👨🏿🇫🇷🇨🇮'".databaseValue)
XCTAssertEqual(values[1], 1.databaseValue)
func testWithArguments() throws {
try DatabaseQueue().inDatabase { db in
let expression = Column("foo").collating(.nocase) == "'fooéı👨👨🏿🇫🇷🇨🇮'" && Column("baz") >= 1
let context = SQLGenerationContext(db)
let sql = try expression.expressionSQL(context, wrappedInParenthesis: true)
XCTAssertEqual(sql, "((\"foo\" = ? COLLATE NOCASE) AND (\"baz\" >= ?))")
let values = context.arguments.values
XCTAssertEqual(values.count, 2)
XCTAssertEqual(values[0], "'fooéı👨👨🏿🇫🇷🇨🇮'".databaseValue)
XCTAssertEqual(values[1], 1.databaseValue)
}
}
func testWithoutArguments() {
let expression = Column("foo").collating(.nocase) == "'fooéı👨👨🏿🇫🇷🇨🇮'" && Column("baz") >= 1
var context = SQLGenerationContext.rawSQLContext
let sql = expression.expressionSQL(&context, wrappedInParenthesis: true)
XCTAssert(context.arguments.isEmpty)
XCTAssertEqual(sql, "((\"foo\" = '''fooéı👨👨🏿🇫🇷🇨🇮''' COLLATE NOCASE) AND (\"baz\" >= 1))")
func testWithoutArguments() throws {
try DatabaseQueue().inDatabase { db in
let expression = Column("foo").collating(.nocase) == "'fooéı👨👨🏿🇫🇷🇨🇮'" && Column("baz") >= 1
let context = SQLGenerationContext(db, argumentsSink: .forRawSQL)
let sql = try expression.expressionSQL(context, wrappedInParenthesis: true)
XCTAssert(context.arguments.isEmpty)
XCTAssertEqual(sql, "((\"foo\" = '''fooéı👨👨🏿🇫🇷🇨🇮''' COLLATE NOCASE) AND (\"baz\" >= 1))")
}
}
}
+548 -333
View File
@@ -2,106 +2,134 @@ import XCTest
@testable import GRDB
class SQLLiteralTests: GRDBTestCase {
func testSQLInitializer() {
let query = SQLLiteral(sql: """
SELECT * FROM player
WHERE id = \("?")
""", arguments: [1])
XCTAssertEqual(query.sql, """
SELECT * FROM player
WHERE id = ?
""")
XCTAssertEqual(query.arguments, [1])
func testSQLInitializer() throws {
try makeDatabaseQueue().inDatabase { db in
let query = SQLLiteral(sql: """
SELECT * FROM player
WHERE id = \("?")
""", arguments: [1])
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT * FROM player
WHERE id = ?
""")
XCTAssertEqual(arguments, [1])
}
}
func testPlusOperator() {
var query = SQLLiteral(sql: "SELECT * ")
query = query + SQLLiteral(sql: "FROM player ")
query = query + SQLLiteral(sql: "WHERE id = ? ", arguments: [1])
query = query + SQLLiteral(sql: "AND name = ?", arguments: ["Arthur"])
XCTAssertEqual(query.sql, """
SELECT * FROM player WHERE id = ? AND name = ?
""")
XCTAssertEqual(query.arguments, [1, "Arthur"])
func testPlusOperator() throws {
try makeDatabaseQueue().inDatabase { db in
var query = SQLLiteral(sql: "SELECT * ")
query = query + SQLLiteral(sql: "FROM player ")
query = query + SQLLiteral(sql: "WHERE id = ? ", arguments: [1])
query = query + SQLLiteral(sql: "AND name = ?", arguments: ["Arthur"])
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT * FROM player WHERE id = ? AND name = ?
""")
XCTAssertEqual(arguments, [1, "Arthur"])
}
}
func testPlusEqualOperator() {
var query = SQLLiteral(sql: "SELECT * ")
query += SQLLiteral(sql: "FROM player ")
query += SQLLiteral(sql: "WHERE id = ? ", arguments: [1])
query += SQLLiteral(sql: "AND name = ?", arguments: ["Arthur"])
XCTAssertEqual(query.sql, """
SELECT * FROM player WHERE id = ? AND name = ?
""")
XCTAssertEqual(query.arguments, [1, "Arthur"])
func testPlusEqualOperator() throws {
try makeDatabaseQueue().inDatabase { db in
var query = SQLLiteral(sql: "SELECT * ")
query += SQLLiteral(sql: "FROM player ")
query += SQLLiteral(sql: "WHERE id = ? ", arguments: [1])
query += SQLLiteral(sql: "AND name = ?", arguments: ["Arthur"])
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT * FROM player WHERE id = ? AND name = ?
""")
XCTAssertEqual(arguments, [1, "Arthur"])
}
}
func testAppendLiteral() {
var query = SQLLiteral(sql: "SELECT * ")
query.append(literal: SQLLiteral(sql: "FROM player "))
query.append(literal: SQLLiteral(sql: "WHERE id = ? ", arguments: [1]))
query.append(literal: SQLLiteral(sql: "AND name = ?", arguments: ["Arthur"]))
XCTAssertEqual(query.sql, """
SELECT * FROM player WHERE id = ? AND name = ?
""")
XCTAssertEqual(query.arguments, [1, "Arthur"])
func testAppendLiteral() throws {
try makeDatabaseQueue().inDatabase { db in
var query = SQLLiteral(sql: "SELECT * ")
query.append(literal: SQLLiteral(sql: "FROM player "))
query.append(literal: SQLLiteral(sql: "WHERE id = ? ", arguments: [1]))
query.append(literal: SQLLiteral(sql: "AND name = ?", arguments: ["Arthur"]))
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT * FROM player WHERE id = ? AND name = ?
""")
XCTAssertEqual(arguments, [1, "Arthur"])
}
}
func testAppendRawSQL() {
var query = SQLLiteral(sql: "SELECT * ")
query.append(sql: "FROM player ")
query.append(sql: "WHERE score > \(1000) ")
query.append(sql: "AND \("name") = :name", arguments: ["name": "Arthur"])
XCTAssertEqual(query.sql, """
SELECT * FROM player WHERE score > 1000 AND name = :name
""")
XCTAssertEqual(query.arguments, ["name": "Arthur"])
func testAppendRawSQL() throws {
try makeDatabaseQueue().inDatabase { db in
var query = SQLLiteral(sql: "SELECT * ")
query.append(sql: "FROM player ")
query.append(sql: "WHERE score > \(1000) ")
query.append(sql: "AND \("name") = :name", arguments: ["name": "Arthur"])
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT * FROM player WHERE score > 1000 AND name = :name
""")
XCTAssertEqual(arguments, ["name": "Arthur"])
}
}
func testSequenceJoined() {
// A sequence that can't be consumed twice
var i = 0
let sequence = AnySequence<SQLLiteral> {
return AnyIterator {
guard i < 3 else { return nil }
i += 1
return SQLLiteral(sql: "(\(i) = ?)", arguments: [i])
func testSequenceJoined() throws {
try makeDatabaseQueue().inDatabase { db in
// A sequence that can't be consumed twice
var i = 0
let sequence = AnySequence<SQLLiteral> {
return AnyIterator {
guard i < 3 else { return nil }
i += 1
return SQLLiteral(sql: "(\(i) = ?)", arguments: [i])
}
}
do {
i = 0
let joined = sequence.joined()
let (sql, arguments) = try joined.build(db)
XCTAssertEqual(sql, "(1 = ?)(2 = ?)(3 = ?)")
XCTAssertEqual(arguments, [1, 2, 3])
}
do {
i = 0
let joined = sequence.joined(separator: " AND ")
let (sql, arguments) = try joined.build(db)
XCTAssertEqual(sql, "(1 = ?) AND (2 = ?) AND (3 = ?)")
XCTAssertEqual(arguments, [1, 2, 3])
}
}
do {
i = 0
let joined = sequence.joined()
XCTAssertEqual(joined.sql, "(1 = ?)(2 = ?)(3 = ?)")
XCTAssertEqual(joined.arguments, [1, 2, 3])
}
do {
i = 0
let joined = sequence.joined(separator: " AND ")
XCTAssertEqual(joined.sql, "(1 = ?) AND (2 = ?) AND (3 = ?)")
XCTAssertEqual(joined.arguments, [1, 2, 3])
}
}
func testCollectionJoined() {
let collection = AnyCollection([
SQLLiteral(sql: "SELECT * "),
SQLLiteral(sql: "FROM player "),
SQLLiteral(sql: "WHERE score > ? ", arguments: [1000]),
SQLLiteral(sql: "AND name = :name", arguments: ["name": "Arthur"]),
func testCollectionJoined() throws {
try makeDatabaseQueue().inDatabase { db in
let collection = AnyCollection([
SQLLiteral(sql: "SELECT * "),
SQLLiteral(sql: "FROM player "),
SQLLiteral(sql: "WHERE score > ? ", arguments: [1000]),
SQLLiteral(sql: "AND name = :name", arguments: ["name": "Arthur"]),
])
do {
let joined = collection.joined()
XCTAssertEqual(joined.sql, """
SELECT * FROM player WHERE score > ? AND name = :name
""")
XCTAssertEqual(joined.arguments, [1000] + ["name": "Arthur"])
}
do {
let joined = collection.joined(separator: " ")
XCTAssertEqual(joined.sql, """
SELECT * FROM player WHERE score > ? AND name = :name
""")
XCTAssertEqual(joined.arguments, [1000] + ["name": "Arthur"])
do {
let joined = collection.joined()
let (sql, arguments) = try joined.build(db)
XCTAssertEqual(sql, """
SELECT * FROM player WHERE score > ? AND name = :name
""")
XCTAssertEqual(arguments, [1000] + ["name": "Arthur"])
}
do {
let joined = collection.joined(separator: " ")
let (sql, arguments) = try joined.build(db)
XCTAssertEqual(sql, """
SELECT * FROM player WHERE score > ? AND name = :name
""")
XCTAssertEqual(arguments, [1000] + ["name": "Arthur"])
}
}
}
@@ -137,289 +165,476 @@ class SQLLiteralTests: GRDBTestCase {
}
extension SQLLiteralTests {
func testLiteralInitializer() {
let query = SQLLiteral("""
SELECT * FROM player
WHERE id = \(1)
""")
XCTAssertEqual(query.sql, """
SELECT * FROM player
WHERE id = ?
""")
XCTAssertEqual(query.arguments, [1])
}
func testRawSQLInterpolation() {
let query: SQLLiteral = """
SELECT *
\(sql: "FROM player")
\(sql: "WHERE score > \(1000)")
\(sql: "AND \("name") = :name", arguments: ["name": "Arthur"])
"""
XCTAssertEqual(query.sql, """
SELECT *
FROM player
WHERE score > 1000
AND name = :name
""")
XCTAssertEqual(query.arguments, ["name": "Arthur"])
}
func testSelectableInterpolation() {
do {
// Non-existential
let query: SQLLiteral = """
SELECT \(AllColumns())
FROM player
"""
XCTAssertEqual(query.sql, """
SELECT *
FROM player
func testLiteralInitializer() throws {
try makeDatabaseQueue().inDatabase { db in
let query = SQLLiteral("""
SELECT * FROM player
WHERE id = \(1)
""")
XCTAssert(query.arguments.isEmpty)
}
do {
// Existential
let query: SQLLiteral = """
SELECT \(AllColumns() as SQLSelectable)
FROM player
"""
XCTAssertEqual(query.sql, """
SELECT *
FROM player
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT * FROM player
WHERE id = ?
""")
XCTAssert(query.arguments.isEmpty)
XCTAssertEqual(arguments, [1])
}
}
func testTableInterpolation() {
struct Player: TableRecord { }
do {
func testRawSQLInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
let query: SQLLiteral = """
SELECT *
FROM \(Player.self)
\(sql: "FROM player")
\(sql: "WHERE score > \(1000)")
\(sql: "AND \("name") = :name", arguments: ["name": "Arthur"])
"""
XCTAssertEqual(query.sql, """
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT *
FROM "player"
FROM player
WHERE score > 1000
AND name = :name
""")
XCTAssert(query.arguments.isEmpty)
XCTAssertEqual(arguments, ["name": "Arthur"])
}
do {
}
func testSelectableInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
do {
// Non-existential
let query: SQLLiteral = """
SELECT \(AllColumns())
FROM player
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT *
FROM player
""")
XCTAssert(arguments.isEmpty)
}
do {
// Existential
let query: SQLLiteral = """
SELECT \(AllColumns() as SQLSelectable)
FROM player
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT *
FROM player
""")
XCTAssert(arguments.isEmpty)
}
}
}
func testTableInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
struct Player: TableRecord { }
do {
let query: SQLLiteral = """
SELECT *
FROM \(Player.self)
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT *
FROM "player"
""")
XCTAssert(arguments.isEmpty)
}
do {
let query: SQLLiteral = """
INSERT INTO \(tableOf: Player()) DEFAULT VALUES
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
INSERT INTO "player" DEFAULT VALUES
""")
XCTAssert(arguments.isEmpty)
}
}
}
func testTableSelectionInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
struct Player: TableRecord { }
struct AltPlayer: TableRecord {
static let databaseSelection: [SQLSelectable] = [Column("id"), Column("name")]
}
do {
let query: SQLLiteral = """
SELECT \(columnsOf: Player.self)
FROM player
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT "player".*
FROM player
""")
XCTAssert(arguments.isEmpty)
}
do {
let query: SQLLiteral = """
SELECT \(columnsOf: Player.self, tableAlias: "p")
FROM player p
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT "p".*
FROM player p
""")
XCTAssert(arguments.isEmpty)
}
do {
let query: SQLLiteral = """
SELECT \(columnsOf: AltPlayer.self)
FROM player
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT "altPlayer"."id", "altPlayer"."name"
FROM player
""")
XCTAssert(arguments.isEmpty)
}
do {
let query: SQLLiteral = """
SELECT \(columnsOf: AltPlayer.self, tableAlias: "p")
FROM player p
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT "p"."id", "p"."name"
FROM player p
""")
XCTAssert(arguments.isEmpty)
}
}
}
func testExpressibleInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
let a = Column("a")
let b = Column("b")
let integer: Int = 1
let optionalInteger: Int? = 2
let nilInteger: Int? = nil
let query: SQLLiteral = """
INSERT INTO \(tableOf: Player()) DEFAULT VALUES
SELECT
\(a),
\(a + 1),
\(2 * (a + 1)),
\(a < b),
\(integer),
\(optionalInteger),
\(nilInteger),
\(a == nilInteger)
"""
XCTAssertEqual(query.sql, """
INSERT INTO "player" DEFAULT VALUES
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT
"a",
"a" + ?,
? * ("a" + ?),
"a" < "b",
?,
?,
NULL,
"a" IS NULL
""")
XCTAssert(query.arguments.isEmpty)
XCTAssertEqual(arguments, [1, 2, 1, 1, 2])
}
}
func testExpressibleInterpolation() {
let a = Column("a")
let b = Column("b")
let integer: Int = 1
let optionalInteger: Int? = 2
let nilInteger: Int? = nil
let query: SQLLiteral = """
SELECT
\(a),
\(a + 1),
\(2 * (a + 1)),
\(a < b),
\(integer),
\(optionalInteger),
\(nilInteger),
\(a == nilInteger)
"""
XCTAssertEqual(query.sql, """
SELECT
"a",
"a" + ?,
? * ("a" + ?),
"a" < "b",
?,
?,
NULL,
"a" IS NULL
""")
XCTAssertEqual(query.arguments, [1, 2, 1, 1, 2])
}
func testDatabaseValueConvertibleInterpolation() {
func test<V: DatabaseValueConvertible>(value: V, isInterpolatedAs dbValue: DatabaseValue) {
let query: SQLLiteral = "SELECT \(value)"
XCTAssertEqual(query.sql, "SELECT ?")
XCTAssertEqual(query.arguments, [dbValue])
}
struct V: DatabaseValueConvertible {
var databaseValue: DatabaseValue {
"V".databaseValue
func testDatabaseValueConvertibleInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
func test<V: DatabaseValueConvertible>(value: V, isInterpolatedAs dbValue: DatabaseValue) throws {
let query: SQLLiteral = "SELECT \(value)"
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, "SELECT ?")
XCTAssertEqual(arguments, [dbValue])
}
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> V? {
nil
struct V: DatabaseValueConvertible {
var databaseValue: DatabaseValue {
"V".databaseValue
}
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> V? {
nil
}
}
try test(value: 42, isInterpolatedAs: 42.databaseValue)
try test(value: 1.23, isInterpolatedAs: 1.23.databaseValue)
try test(value: "foo", isInterpolatedAs: "foo".databaseValue)
try test(value: "foo".data(using: .utf8)!, isInterpolatedAs: "foo".data(using: .utf8)!.databaseValue)
try test(value: V(), isInterpolatedAs: "V".databaseValue)
}
test(value: 42, isInterpolatedAs: 42.databaseValue)
test(value: 1.23, isInterpolatedAs: 1.23.databaseValue)
test(value: "foo", isInterpolatedAs: "foo".databaseValue)
test(value: "foo".data(using: .utf8)!, isInterpolatedAs: "foo".data(using: .utf8)!.databaseValue)
test(value: V(), isInterpolatedAs: "V".databaseValue)
}
func testDataInterpolation() {
// This test makes sure the Sequence conformance of Data does not
// kick in.
let data = "SQLite".data(using: .utf8)!
let query: SQLLiteral = "SELECT \(data)"
XCTAssertEqual(query.sql, "SELECT ?")
XCTAssertEqual(query.arguments, [data])
}
func testAliasedExpressionInterpolation() {
let query: SQLLiteral = """
SELECT \(Column("name").forKey("foo")), \(1.databaseValue.forKey("bar"))
FROM player
"""
XCTAssertEqual(query.sql, """
SELECT "name" AS "foo", ? AS "bar"
FROM player
""")
XCTAssertEqual(query.arguments, [1])
}
func testCodingKeyInterpolation() {
enum CodingKeys: String, CodingKey {
case name
func testDataInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
// This test makes sure the Sequence conformance of Data does not
// kick in.
let data = "SQLite".data(using: .utf8)!
let query: SQLLiteral = "SELECT \(data)"
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, "SELECT ?")
XCTAssertEqual(arguments, [data])
}
let query: SQLLiteral = """
SELECT \(CodingKeys.name)
FROM player
"""
XCTAssertEqual(query.sql, """
SELECT "name"
FROM player
""")
XCTAssert(query.arguments.isEmpty)
}
func testCodingKeyColumnInterpolation() {
enum CodingKeys: String, CodingKey, ColumnExpression {
case name
func testAliasedExpressionInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
let query: SQLLiteral = """
SELECT \(Column("name").forKey("foo")), \(1.databaseValue.forKey("bar"))
FROM player
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT "name" AS "foo", ? AS "bar"
FROM player
""")
XCTAssertEqual(arguments, [1])
}
let query: SQLLiteral = """
SELECT \(CodingKeys.name)
FROM player
"""
XCTAssertEqual(query.sql, """
SELECT "name"
FROM player
""")
XCTAssert(query.arguments.isEmpty)
}
func testExpressibleSequenceInterpolation() {
let set: Set = [1]
let array = ["foo", "bar", "baz"]
let expressions = [Column("a"), Column("b") + 2]
let query: SQLLiteral = """
SELECT * FROM player
WHERE teamId IN \(set)
AND name IN \(array)
AND c IN \(expressions)
AND d IN \([])
"""
XCTAssertEqual(query.sql, """
SELECT * FROM player
WHERE teamId IN (?)
AND name IN (?,?,?)
AND c IN ("a","b" + ?)
AND d IN (SELECT NULL WHERE NULL)
""")
XCTAssertEqual(query.arguments, [1, "foo", "bar", "baz", 2])
}
func testOrderingTermInterpolation() {
let query: SQLLiteral = """
SELECT * FROM player
ORDER BY \(Column("name").desc)
"""
XCTAssertEqual(query.sql, """
SELECT * FROM player
ORDER BY "name" DESC
""")
XCTAssert(query.arguments.isEmpty)
func testCodingKeyInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
enum CodingKeys: String, CodingKey {
case name
}
let query: SQLLiteral = """
SELECT \(CodingKeys.name)
FROM player
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT "name"
FROM player
""")
XCTAssert(arguments.isEmpty)
}
}
func testSQLLiteralInterpolation() {
let condition: SQLLiteral = "name = \("Arthur")"
let query: SQLLiteral = """
SELECT *, \(true) FROM player
WHERE \(literal: condition) AND score > \(1000)
"""
XCTAssertEqual(query.sql, """
SELECT *, ? FROM player
WHERE name = ? AND score > ?
""")
XCTAssertEqual(query.arguments, [true, "Arthur", 1000])
func testCodingKeyColumnInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
enum CodingKeys: String, CodingKey, ColumnExpression {
case name
}
let query: SQLLiteral = """
SELECT \(CodingKeys.name)
FROM player
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT "name"
FROM player
""")
XCTAssert(arguments.isEmpty)
}
}
func testSQLRequestInterpolation() {
let subQuery: SQLRequest<Int> = "SELECT MAX(score) - \(10) FROM player"
let query: SQLLiteral = """
SELECT * FROM player
WHERE score = \(subQuery)
"""
XCTAssertEqual(query.sql, """
SELECT * FROM player
WHERE score = (SELECT MAX(score) - ? FROM player)
""")
XCTAssertEqual(query.arguments, [10])
func testExpressibleSequenceInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
let set: Set = [1]
let array = ["foo", "bar", "baz"]
let expressions = [Column("a"), Column("b") + 2]
let query: SQLLiteral = """
SELECT * FROM player
WHERE teamId IN \(set)
AND name IN \(array)
AND c IN \(expressions)
AND d IN \([])
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT * FROM player
WHERE teamId IN (?)
AND name IN (?,?,?)
AND c IN ("a","b" + ?)
AND d IN (SELECT NULL WHERE NULL)
""")
XCTAssertEqual(arguments, [1, "foo", "bar", "baz", 2])
}
}
func testPlusOperatorWithInterpolation() {
var query: SQLLiteral = "SELECT \(AllColumns()) "
query = query + "FROM player "
query = query + "WHERE id = \(1)"
XCTAssertEqual(query.sql, """
SELECT * FROM player WHERE id = ?
""")
XCTAssertEqual(query.arguments, [1])
func testOrderingTermInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
let query: SQLLiteral = """
SELECT * FROM player
ORDER BY \(Column("name").desc)
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT * FROM player
ORDER BY "name" DESC
""")
XCTAssert(arguments.isEmpty)
}
}
func testPlusEqualOperatorWithInterpolation() {
var query: SQLLiteral = "SELECT \(AllColumns()) "
query += "FROM player "
query += "WHERE id = \(1)"
XCTAssertEqual(query.sql, """
SELECT * FROM player WHERE id = ?
""")
XCTAssertEqual(query.arguments, [1])
func testSQLLiteralInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
let condition: SQLLiteral = "name = \("Arthur")"
let query: SQLLiteral = """
SELECT *, \(true) FROM player
WHERE \(literal: condition) AND score > \(1000)
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT *, ? FROM player
WHERE name = ? AND score > ?
""")
XCTAssertEqual(arguments, [true, "Arthur", 1000])
}
}
func testAppendLiteralWithInterpolation() {
var query: SQLLiteral = "SELECT \(AllColumns()) "
query.append(literal: "FROM player ")
query.append(literal: "WHERE id = \(1)")
XCTAssertEqual(query.sql, """
SELECT * FROM player WHERE id = ?
""")
XCTAssertEqual(query.arguments, [1])
func testSQLRequestInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
let subquery: SQLRequest<Int> = "SELECT MAX(score) - \(10) FROM player"
let query: SQLLiteral = """
SELECT * FROM player
WHERE score = (\(subquery))
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT * FROM player
WHERE score = (SELECT MAX(score) - ? FROM player)
""")
XCTAssertEqual(arguments, [10])
}
}
func testAppendRawSQLWithInterpolation() {
var query: SQLLiteral = "SELECT \(AllColumns()) "
query.append(sql: "FROM player ")
query.append(sql: "WHERE score > \(1000) ")
query.append(sql: "AND \("name") = :name", arguments: ["name": "Arthur"])
XCTAssertEqual(query.sql, """
SELECT * FROM player WHERE score > 1000 AND name = :name
""")
XCTAssertEqual(query.arguments, ["name": "Arthur"])
func testQueryInterfaceRequestInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("score", .integer)
}
struct Player: TableRecord { }
let subquery = Player.select(max(Column("score")) - 10)
let query: SQLLiteral = """
SELECT * FROM player
WHERE score = (\(subquery))
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT * FROM player
WHERE score = (SELECT MAX("score") - ? FROM "player")
""")
XCTAssertEqual(arguments, [10])
}
}
func testJoinedQueryInterfaceRequestInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
try db.create(table: "team") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("teamId", .integer).references("team")
t.column("score", .integer)
}
struct Player: TableRecord { }
struct Team: TableRecord { }
let subquery = Player
.select(max(Column("score")) - 10)
.joining(required: Player.belongsTo(Team.self))
let query: SQLLiteral = """
SELECT * FROM player
WHERE score = (\(subquery))
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT * FROM player
WHERE score = (SELECT MAX("player"."score") - ? FROM "player" JOIN "team" ON "team"."id" = "player"."teamId")
""")
XCTAssertEqual(arguments, [10])
}
}
func testPlusOperatorWithInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
var query: SQLLiteral = "SELECT \(AllColumns()) "
query = query + "FROM player "
query = query + "WHERE id = \(1)"
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT * FROM player WHERE id = ?
""")
XCTAssertEqual(arguments, [1])
}
}
func testPlusEqualOperatorWithInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
var query: SQLLiteral = "SELECT \(AllColumns()) "
query += "FROM player "
query += "WHERE id = \(1)"
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT * FROM player WHERE id = ?
""")
XCTAssertEqual(arguments, [1])
}
}
func testAppendLiteralWithInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
var query: SQLLiteral = "SELECT \(AllColumns()) "
query.append(literal: "FROM player ")
query.append(literal: "WHERE id = \(1)")
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT * FROM player WHERE id = ?
""")
XCTAssertEqual(arguments, [1])
}
}
func testAppendRawSQLWithInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
var query: SQLLiteral = "SELECT \(AllColumns()) "
query.append(sql: "FROM player ")
query.append(sql: "WHERE score > \(1000) ")
query.append(sql: "AND \("name") = :name", arguments: ["name": "Arthur"])
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT * FROM player WHERE score > 1000 AND name = :name
""")
XCTAssertEqual(arguments, ["name": "Arthur"])
}
}
func testQualifiedSQLInterpolation() throws {
@@ -450,8 +665,8 @@ extension SQLLiteralTests {
}
do {
let subQuery: SQLRequest<String> = "SELECT MAX(\(nameColumn)) FROM \(Player.self)"
let conditionLiteral = SQLLiteral("\(nameColumn) = \(subQuery)")
let subquery: SQLRequest<String> = "SELECT MAX(\(nameColumn)) FROM \(Player.self)"
let conditionLiteral = SQLLiteral("\(nameColumn) = (\(subquery))")
let request = baseRequest.filter(literal: conditionLiteral)
try assertEqualSQL(db, request, """
SELECT "p".* FROM "player" "p" WHERE "p"."name" = (SELECT MAX("name") FROM "player")
+40 -67
View File
@@ -47,49 +47,19 @@ class SQLRequestTests: GRDBTestCase {
}
}
func testRequestInitializer() throws {
struct CustomRequest: FetchRequest {
typealias RowDecoder = Row
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
let statement = try db.makeSelectStatement(sql: "SELECT ? AS a, ? AS b")
statement.arguments = [1, "foo"]
return PreparedRequest(statement: statement)
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = CustomRequest()
let sqlRequest = try SQLRequest<Row>(db, request: request)
XCTAssertEqual(sqlRequest.sql, "SELECT ? AS a, ? AS b")
XCTAssertEqual(sqlRequest.arguments, [1, "foo"])
XCTAssertEqual(try sqlRequest.fetchOne(db)!, ["a": 1, "b": "foo"])
}
}
func testRequestInitializerAndSingleResultHint() throws {
struct CustomRequest: FetchRequest {
typealias RowDecoder = Row
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
if singleResult { fatalError("not implemented") }
return try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT 'multiple'"))
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
let request = try SQLRequest(db, request: CustomRequest())
XCTAssertEqual(request.sql, "SELECT 'multiple'")
}
}
func testSQLLiteralInitializer() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = SQLRequest<String>(literal: SQLLiteral(sql: """
SELECT ?
""", arguments: ["O'Brien"]))
XCTAssertEqual(request.sql, """
let (sql, arguments) = try request.build(db)
XCTAssertEqual(sql, """
SELECT ?
""")
XCTAssertEqual(arguments, ["O'Brien"])
let string = try request.fetchOne(db)!
XCTAssertEqual(string, "O'Brien")
}
@@ -101,9 +71,13 @@ class SQLRequestTests: GRDBTestCase {
let request = SQLRequest<String>("""
SELECT \("O'Brien")
""")
XCTAssertEqual(request.sql, """
let (sql, arguments) = try request.build(db)
XCTAssertEqual(sql, """
SELECT ?
""")
XCTAssertEqual(arguments, ["O'Brien"])
let string = try request.fetchOne(db)!
XCTAssertEqual(string, "O'Brien")
}
@@ -115,9 +89,13 @@ class SQLRequestTests: GRDBTestCase {
let request = SQLRequest<String>(literal: """
SELECT \("O'Brien")
""")
XCTAssertEqual(request.sql, """
let (sql, arguments) = try request.build(db)
XCTAssertEqual(sql, """
SELECT ?
""")
XCTAssertEqual(arguments, ["O'Brien"])
let string = try request.fetchOne(db)!
XCTAssertEqual(string, "O'Brien")
}
@@ -174,84 +152,79 @@ class SQLRequestTests: GRDBTestCase {
do {
let request = Player.filter(id: 42)
XCTAssertEqual(request.sql, """
let (sql, arguments) = try request.build(db)
XCTAssertEqual(sql, """
SELECT *
FROM "player"
WHERE "id" = ?
""")
XCTAssertEqual(arguments, [42])
let player = try request.fetchOne(db)!
XCTAssertEqual(player.name, "Barbara")
XCTAssertEqual(lastSQLQuery, """
SELECT *
FROM "player"
WHERE "id" = 42
""")
}
do {
let request = Player.filter(ids: [1, 2, 3])
XCTAssertEqual(request.sql, """
let (sql, arguments) = try request.build(db)
XCTAssertEqual(sql, """
SELECT *
FROM "player"
WHERE "id" IN (?,?,?)
""")
XCTAssertEqual(arguments, [1, 2, 3])
let players = try request.fetchAll(db)
XCTAssertEqual(players.count, 1)
XCTAssertEqual(players[0].name, "Arthur")
XCTAssertEqual(lastSQLQuery, """
SELECT *
FROM "player"
WHERE "id" IN (1,2,3)
""")
}
do {
let request = Player.filter(ids: [])
XCTAssertEqual(request.sql, """
let (sql, arguments) = try request.build(db)
XCTAssertEqual(sql, """
SELECT *
FROM "player"
WHERE "id" IN (SELECT NULL WHERE NULL)
""")
XCTAssert(arguments.isEmpty)
let players = try request.fetchAll(db)
XCTAssert(players.isEmpty)
XCTAssertEqual(lastSQLQuery, """
SELECT *
FROM "player"
WHERE "id" IN (SELECT NULL WHERE NULL)
""")
}
do {
let request = Player.filter(excludedIds: [42, 666])
XCTAssertEqual(request.sql, """
let (sql, arguments) = try request.build(db)
XCTAssertEqual(sql, """
SELECT *
FROM "player"
WHERE "id" NOT IN (?,?)
""")
XCTAssertEqual(arguments, [42, 666])
let players = try request.fetchAll(db)
XCTAssertEqual(players.count, 1)
XCTAssertEqual(players[0].name, "Arthur")
XCTAssertEqual(lastSQLQuery, """
SELECT *
FROM "player"
WHERE "id" NOT IN (42,666)
""")
}
do {
let request = Player.filter(excludedIds: [])
XCTAssertEqual(request.sql, """
let (sql, arguments) = try request.build(db)
XCTAssertEqual(sql, """
SELECT *
FROM "player"
WHERE "id" NOT IN (SELECT NULL WHERE NULL)
""")
XCTAssert(arguments.isEmpty)
let players = try request.fetchAll(db)
XCTAssertEqual(players.count, 2)
XCTAssertEqual(lastSQLQuery, """
SELECT *
FROM "player"
WHERE "id" NOT IN (SELECT NULL WHERE NULL)
""")
}
}
}
@@ -7,7 +7,7 @@ class ValueObservationCountTests: GRDBTestCase {
try assertValueObservation(
ValueObservation.tracking(T.fetchCount),
records: [0, 1, 1, 2, 3, 2],
records: [0, 1, 1, 2, 3, 4],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
},
@@ -21,7 +21,7 @@ class ValueObservationCountTests: GRDBTestCase {
try db.execute(sql: "DELETE FROM t WHERE id = 1")
return .commit
}
try db.execute(sql: "DELETE FROM t WHERE id = 2")
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
})
}
@@ -30,7 +30,7 @@ class ValueObservationCountTests: GRDBTestCase {
try assertValueObservation(
ValueObservation.tracking(T.fetchCount).removeDuplicates(),
records: [0, 1, 2, 3, 2],
records: [0, 1, 2, 3, 4],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
},
@@ -44,7 +44,7 @@ class ValueObservationCountTests: GRDBTestCase {
try db.execute(sql: "DELETE FROM t WHERE id = 1")
return .commit
}
try db.execute(sql: "DELETE FROM t WHERE id = 2")
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
})
}
}
@@ -77,7 +77,8 @@ class ValueObservationRecordTests: GRDBTestCase {
Player(id: 1, name: "foo"),
Player(id: 1, name: "foo"),
Player(id: 2, name: "bar"),
nil],
nil,
Player(id: 3, name: "toto")],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
},
@@ -91,6 +92,7 @@ class ValueObservationRecordTests: GRDBTestCase {
return .commit
}
try db.execute(sql: "DELETE FROM t")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'toto')")
})
// The fundamental technique for removing duplicates of non-Equatable types
@@ -103,7 +105,8 @@ class ValueObservationRecordTests: GRDBTestCase {
nil,
Player(id: 1, name: "foo"),
Player(id: 2, name: "bar"),
nil],
nil,
Player(id: 3, name: "toto")],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
},
@@ -117,6 +120,7 @@ class ValueObservationRecordTests: GRDBTestCase {
return .commit
}
try db.execute(sql: "DELETE FROM t")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'toto')")
})
}
}
+37 -16
View File
@@ -378,6 +378,13 @@ extension GRDBTestCase {
throws
where Reducer.Value: Equatable
{
#if SQLITE_HAS_CODEC || GRDBCUSTOMSQLITE
// debug SQLite builds can be *very* slow
let timeout: TimeInterval = 2
#else
let timeout: TimeInterval = 0.3
#endif
func test(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
@@ -404,7 +411,7 @@ extension GRDBTestCase {
try writer.writeWithoutTransaction(recordedUpdates)
let expectation = recorder.next(expectedValues.count)
let values = try wait(for: expectation, timeout: 0.3)
let values = try wait(for: expectation, timeout: timeout)
XCTAssertEqual(
values, expectedValues,
"\(#function), \(writer), \(scheduler)", file: file, line: line)
@@ -434,7 +441,7 @@ extension GRDBTestCase {
}
let expectation = recorder.next(expectedValues.count)
let values = try wait(for: expectation, timeout: 0.3)
let values = try wait(for: expectation, timeout: timeout)
XCTAssertEqual(
values, expectedValues,
"\(#function), \(writer), \(scheduler)", file: file, line: line)
@@ -459,17 +466,28 @@ extension GRDBTestCase {
try writer.writeWithoutTransaction(recordedUpdates)
let expectation = recorder
.prefix(expectedValues.count + 2 /* pool may perform double initial fetch */)
.inverted
let values = try wait(for: expectation, timeout: 0.3)
let recordedValues: [Reducer.Value]
let lastExpectedValue = expectedValues.last!
let waitForLast = expectedValues.firstIndex(of: lastExpectedValue) == expectedValues.count - 1
if waitForLast {
// Optimization!
let expectation = recorder.prefix(until: { $0 == lastExpectedValue } )
recordedValues = try wait(for: expectation, timeout: timeout)
} else {
// Slow!
assertionFailure("Please rewrite your test, because it is too slow: make sure the last expected value is unique.")
let expectation = recorder
.prefix(expectedValues.count + 2 /* pool may perform double initial fetch */)
.inverted
recordedValues = try wait(for: expectation, timeout: timeout)
}
if scheduler.immediateInitialValue() {
XCTAssertEqual(values.first, expectedValues.first)
XCTAssertEqual(recordedValues.first, expectedValues.first)
}
assertValueObservationRecordingMatch(
recorded: values,
recorded: recordedValues,
expected: expectedValues,
"\(#function), \(writer), \(scheduler)", file: file, line: line)
}
@@ -503,18 +521,14 @@ extension GRDBTestCase {
if waitForLast {
// Optimization!
let expectation = recorder.prefix(until: { $0 == lastExpectedValue } )
recordedValues = try wait(for: expectation, timeout: 1)
recordedValues = try wait(for: expectation, timeout: timeout)
} else {
// Slow!
assertionFailure("Please rewrite your test, because it is too slow: make sure the last expected value is unique.")
let expectation = recorder
.prefix(expectedValues.count + 2 /* pool may perform double initial fetch */)
.inverted
#if SQLITE_HAS_CODEC || GRDBCUSTOMSQLITE
// debug SQLite builds can be *very* slow
recordedValues = try wait(for: expectation, timeout: 1)
#else
recordedValues = try wait(for: expectation, timeout: 0.3)
#endif
recordedValues = try wait(for: expectation, timeout: timeout)
}
XCTAssertEqual(recordedValues.first, expectedValues.first)
@@ -581,6 +595,13 @@ extension GRDBTestCase {
line: UInt = #line)
throws
{
#if SQLITE_HAS_CODEC || GRDBCUSTOMSQLITE
// debug SQLite builds can be *very* slow
let timeout: TimeInterval = 2
#else
let timeout: TimeInterval = 0.3
#endif
func test(
observation: ValueObservation<Reducer>,
scheduling scheduler: ValueObservationScheduler,
@@ -594,7 +615,7 @@ extension GRDBTestCase {
scheduling: scheduler,
onError: { _ in testErrorDispatching() })
let (_, error) = try wait(for: recorder.failure(), timeout: 0.3)
let (_, error) = try wait(for: recorder.failure(), timeout: timeout)
if let error = error as? Failure {
try testFailure(error, writer)
} else {
@@ -61,7 +61,8 @@ class ValueObservationRowTests: GRDBTestCase {
["id":1, "name":"foo"],
["id":1, "name":"foo"],
["id":2, "name":"bar"],
nil],
nil,
["id":3, "name":"toto"]],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
},
@@ -75,6 +76,7 @@ class ValueObservationRowTests: GRDBTestCase {
return .commit
}
try db.execute(sql: "DELETE FROM t")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'toto')")
})
try assertValueObservation(
@@ -83,7 +85,8 @@ class ValueObservationRowTests: GRDBTestCase {
nil,
["id":1, "name":"foo"],
["id":2, "name":"bar"],
nil],
nil,
["id":3, "name":"toto"]],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
},
@@ -97,6 +100,7 @@ class ValueObservationRowTests: GRDBTestCase {
return .commit
}
try db.execute(sql: "DELETE FROM t")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'toto')")
})
}
+4 -4
View File
@@ -31,7 +31,7 @@ class ValueObservationTests: GRDBTestCase {
// Track reducer process
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 3
notificationExpectation.expectedFulfillmentCount = 4
notificationExpectation.isInverted = true
struct TestError: Error { }
@@ -62,7 +62,7 @@ class ValueObservationTests: GRDBTestCase {
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 0.3, handler: nil)
waitForExpectations(timeout: 1, handler: nil)
XCTAssertTrue(errorCaught)
}
}
@@ -227,7 +227,7 @@ class ValueObservationTests: GRDBTestCase {
try dbWriter.write { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
waitForExpectations(timeout: 0.2, handler: nil)
waitForExpectations(timeout: 1, handler: nil)
}
try test(makeDatabaseQueue())
@@ -270,7 +270,7 @@ class ValueObservationTests: GRDBTestCase {
try dbWriter.write { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
waitForExpectations(timeout: 0.2, handler: nil)
waitForExpectations(timeout: 1, handler: nil)
}
try test(makeDatabaseQueue())