Compare commits

..
Author SHA1 Message Date
Gwendal Roué a88067a815 Merge branch 'GRDB5' into dev/hasMany-first 2020-04-25 13:31:58 +02:00
Gwendal Roué df4d5b8603 Back to basics, round 2: keep all children of firstOnly relations 2020-04-19 17:44:50 +02:00
Gwendal Roué a7b8a73dba Cleanup
After failed experiment:

SELECT ...
FROM parent
JOIN (SELECT * FROM child LIMIT 1) child ON child.parentId = child.id

The problem is that the join condition can't go inside the subquery, because SQLite complains about unknown table "parent". And when the join condition is outside the subquery, the LIMIT clause has been applied too early.

So we're still stuck with:

SELECT ...
FROM parent
JOIN child ON child.id = (SELECT id FROM child WHERE child.parentId = child.id LIMIT 1)

For some reason SQLite accepts the reference to the parent table in this case.
2020-04-19 14:14:13 +02:00
Gwendal Roué 278c18adfc Cleanup 2020-04-18 20:21:14 +02:00
Gwendal Roué cbd494e3b9 Documentation 2020-04-18 20:19:47 +02:00
Gwendal Roué c73fb0dd9b Back to basics 2020-04-18 20:14:27 +02:00
Gwendal Roué c966eb3ecf Cleanup 2020-04-18 19:09:02 +02:00
Gwendal Roué 217b0a3f3e More failing HasManyThrough.first tests 2020-04-18 17:52:50 +02:00
Gwendal Roué e604a10860 TODO 2020-04-18 17:06:29 +02:00
Gwendal Roué ac4f4c6611 Improve HasMany.first tests 2020-04-18 17:06:29 +02:00
Gwendal Roué 162da80e4f Attempt at expressing some todos 2020-04-18 17:06:29 +02:00
Gwendal Roué 315496928b More failing HasManyThrough.first 2020-04-18 17:06:29 +02:00
Gwendal Roué d82cbb6853 Improve HasManyThrough.first tests 2020-04-18 17:06:29 +02:00
Gwendal Roué 5fed231856 Simplify SQLAssociationCondition.filteringExpression 2020-04-18 17:06:29 +02:00
Gwendal Roué 45dfe7d7f1 More HasManyThrough.first tests 2020-04-18 17:06:29 +02:00
Gwendal Roué c7d1cca023 Ease testing SQL by ignoring white space 2020-04-18 17:06:29 +02:00
Gwendal Roué 615f4159d6 Rename firstInMany to firstOnly 2020-04-18 17:06:29 +02:00
Gwendal Roué 8057572357 Move firstInMany flag in SQLRelation 2020-04-18 17:06:29 +02:00
Gwendal Roué da63037948 Fix documentation 2020-04-18 17:06:29 +02:00
Gwendal Roué 2d3dafad7d Document first and last properties, set their association key 2020-04-18 17:06:29 +02:00
Gwendal Roué 7ed967b502 Cleanup SQLAssociationCardinality and SQLAssociationStep 2020-04-18 17:06:29 +02:00
Gwendal Roué f545789205 Avoid using the rowid column when we can use the regular primary key 2020-04-18 17:06:23 +02:00
Gwendal Roué 79373d5b74 Cleanup some old tests 2020-04-18 16:40:22 +02:00
Gwendal Roué f97088d63a Failing tests for HasManyThrough.first 2020-04-18 16:40:22 +02:00
Gwendal Roué 860faf19f7 HasManyThrough.first and last 2020-04-18 16:40:22 +02:00
Gwendal Roué 0f54779386 Isolate tests for hasMany.first 2020-04-18 16:40:22 +02:00
Gwendal Roué 6f125bd3d7 SQLAssociation.associationForFirst() 2020-04-18 16:40:22 +02:00
Gwendal Roué 4483f037a4 Cleanup 2020-04-18 16:40:22 +02:00
Gwendal Roué 20296652dd More test for hasMany.first including nested associations 2020-04-18 16:40:22 +02:00
Gwendal Roué d80922954a Let hasMany.first include nested associations 2020-04-18 16:40:22 +02:00
Gwendal Roué d67814ef61 Make sure hasMany.first doesn't lose information 2020-04-18 16:40:22 +02:00
Gwendal Roué fb550d30a0 HasManyAssociation.first and last 2020-04-18 16:40:22 +02:00
96 changed files with 3442 additions and 2993 deletions

No files matched your search

+35 -35
View File
@@ -34,15 +34,15 @@ jobs:
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBOSX (Swift 5.2, macOS)
- TID=GRDBOSX (Swift 5.1, 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 5.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 4.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.2, iOS <MAX>)
- TID=GRDBiOS (Swift 5.1, 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 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.2, iOS <MIN>)
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget_minSwift
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 5.1, iOS <MIN>)
script: make test_framework_GRDBiOS_minTarget
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBtvOS (Swift 5.2, tvOS <MAX>)
- TID=GRDBtvOS (Swift 5.1, 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 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.2, tvOS <MIN>)
- TID=GRDBtvOS (Swift 4.2, tvOS <MAX>)
script: make test_framework_GRDBtvOS_maxTarget_minSwift
- stage: Test GRDB Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBtvOS (Swift 5.1, tvOS <MIN>)
script: make test_framework_GRDBtvOS_minTarget
- stage: Test GRDB Xcode 11.4
@@ -107,28 +107,28 @@ jobs:
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBOSX (Swift 5.2, macOS)
- TID=GRDBOSX (Swift 5.1, 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.2, iOS <MAX>)
- TID=GRDBiOS (Swift 5.1, 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 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.2, iOS <MIN>)
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_minSwift
- stage: Test GRDBCustom Xcode 11.4
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
env:
- TID=GRDBiOS (Swift 5.1, iOS <MIN>)
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
###########################################
+6 -69
View File
@@ -13,7 +13,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 5.x Releases
- `5.0.0` Betas - [5.0.0-beta](#500-beta)
- `5.0.x` Development - [GRDB5 Branch](#grdb5-branch)
#### 4.x Releases
@@ -76,70 +76,14 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
## Next Release
-->
## 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>
## GRDB5 Branch
### Documentation Diff
- **[Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)**: how to upgrade your apps, and deal with breaking changes.
- [ValueObservation](README.md#valueobservation): this chapter describes the new ValueObservation behaviors.
- [DatabaseError](README.md#databaseerror): learn how to catch and match DatabaseError on their codes, in a fashion similar to `CocoaError`.
- [Batch Updates](README.md#update-requests): this chapter is updated for the new `set(to:)` method.
- [SQL Operators](README.md#sql-operators): introduces support for SQL and query interface subqueries.
- [How do I print a request as SQL?](README.md#how-do-i-print-a-request-as-sql) This FAQ was updated for GRDB 5.
- [SQL Interpolation](Documentation/SQLInterpolation.md): this guide now describes how to embed subqueries and record columns in your SQL literals.
- [Joined Queries Support](README.md#joined-queries-support): describes the GRDB 5 way of dealing with complex and hand-crafted SQL queries.
- [Raw SQLite Pointers](README.md#raw-sqlite-pointers) and [Custom SQLite builds](Documentation/CustomSQLiteBuilds.md): `import GRDB` now provides access to the full [C SQLite API](https://www.sqlite.org/capi3ref.html), and custom SQLite builds.
- 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.
### New
@@ -164,13 +108,6 @@ let sqliteVersion = String(cString: sqlite3_libversion())
- [#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.id) AS bookCount,
// COUNT(DISTINCT book.rowid) 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.id) = 0
HAVING COUNT(DISTINCT book.rowid) = 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.id) > 0
HAVING COUNT(DISTINCT book.rowid) > 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.id) >= 2
HAVING COUNT(DISTINCT book.rowid) >= 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.id) > 0
HAVING COUNT(DISTINCT book.rowid) > 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.id) > COUNT(DISTINCT painting.id)
HAVING COUNT(DISTINCT book.rowid) > COUNT(DISTINCT painting.rowid)
```
</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.id) = 0) AND (COUNT(DISTINCT painting.id) > 0))
HAVING ((COUNT(DISTINCT book.rowid) = 0) AND (COUNT(DISTINCT painting.rowid) > 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.id) = 0) AND (COUNT(DISTINCT painting.id) = 0))
HAVING ((COUNT(DISTINCT book.rowid) = 0) AND (COUNT(DISTINCT painting.rowid) = 0))
```
</details>
@@ -2101,8 +2101,8 @@ Aggregates can be modified and combined with Swift operators:
```sql
SELECT author.*,
(COUNT(DISTINCT book.id) +
COUNT(DISTINCT painting.id)) AS workCount
(COUNT(DISTINCT book.rowid) +
COUNT(DISTINCT painting.rowid)) 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.id) + COUNT(DISTINCT painting.id)) AS workCount
(COUNT(DISTINCT book.rowid) + COUNT(DISTINCT painting.rowid)) 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.id) AS novelCount,
COUNT(DISTINCT book2.id) AS theatrePlayCount
COUNT(DISTINCT book1.rowid) AS novelCount,
COUNT(DISTINCT book2.rowid) 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.id) AS novelCount,
COUNT(DISTINCT book.id) AS theatrePlayCount
COUNT(DISTINCT book.rowid) AS novelCount,
COUNT(DISTINCT book.rowid) 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]: Migrations.md
[migration]: ../README.md#migrations
[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/Documentation/Migrations.md
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#migrations
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](../../Migrations.md) in order to setup the database schema.
`AppDatabase` defines the database for the whole application. It uses [DatabaseMigrator](../../README.md#migrations) 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)
+5 -84
View File
@@ -302,86 +302,8 @@ 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. [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):
2. [Custom SQL functions] are now [callable values](https://github.com/apple/swift-evolution/blob/master/proposals/0253-callable.md):
```swift
// BEFORE: GRDB 4
@@ -391,7 +313,7 @@ The changes can quite impact your application. We'll describe them below, as wel
Player.select(myFunction(Column("name")))
```
7. If you happen to implement custom fetch requests with the `FetchRequest` protocol, you now have to define the `makePreparedRequest(_:forSingleResult:)` method:
3. 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
@@ -413,7 +335,7 @@ The changes can quite impact your application. We'll describe them below, as wel
}
```
8. The module name for [custom SQLite builds](CustomSQLiteBuilds.md) is now the plain `GRDB`:
4. The module name for [custom SQLite builds](CustomSQLiteBuilds.md) is now the plain `GRDB`:
```swift
// BEFORE: GRDB 4
@@ -423,7 +345,7 @@ The changes can quite impact your application. We'll describe them below, as wel
import GRDB
```
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:
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:
```swift
// BEFORE: GRDB 4
@@ -438,6 +360,7 @@ 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
@@ -446,5 +369,3 @@ 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]: Migrations.md
[migration]: Migrations.md
[migrations]: ../README.md#migrations
[migration]: ../README.md#migrations
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
[Concurrency Guide]: ../README.md#concurrency
[GRDB concurrency rules]: ../README.md#concurrency
-126
View File
@@ -1,126 +0,0 @@
# 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")
}
```
+93 -113
View File
@@ -6,17 +6,16 @@ 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 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])
}
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.
@@ -35,9 +34,7 @@ SQL Interpolation is an answer to these troubles. It is available in Swift 5.
```swift
let name: String = ...
let id: Int64 = ...
try dbQueue.write { db in
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
}
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
```
SQL interpolation looks and feel just like regular [String interpolation]:
@@ -50,12 +47,16 @@ 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 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)")
}
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])
```
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:
@@ -78,21 +79,17 @@ 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
try dbQueue.write { db in
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
try db.execute(literal: query)
}
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
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)
}
// 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)
```
SQLLiteral can build your queries step by step, with regular operators and methods:
@@ -116,9 +113,8 @@ Extract the plain SQL string from a literal:
```swift
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
let (sql, arguments) = try dbQueue.read(query.build)
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(arguments) // prints ["O'Brien", 42]
print(query.sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(query.arguments) // prints ["O'Brien", 42]
```
Build a literal from a plain SQL string:
@@ -171,7 +167,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. Let's start from this record:
SQL Interpolation puts this knowledge to good use, so that you can build robust queries that consistently use correct table and column names:
```swift
struct Player {
@@ -180,15 +176,51 @@ struct Player {
var score: Int?
}
extension Player: Decodable, TableRecord, FetchableRecord { }
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)
}
}
```
Let's extend Player with database methods.
Let's breakdown each one of those methods.
- `Player.deleteAllWithoutScore(_:)`
- `deleteAllWithoutScore(_:)`
```swift
extension Player {
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")
@@ -209,22 +241,13 @@ Let's extend Player with database 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.
- `Player.filter(id:)`
- `filter(id:)`
```swift
extension Player {
/// "Simple" version
extension Player: Decodable, FetchableRecord, TableRecord {
/// The player with a given id
static func filter(id: Int64) -> SQLRequest<Player> {
"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)
"""
"SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)"
}
}
```
@@ -238,28 +261,17 @@ Let's extend Player with database methods.
}
```
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"".
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 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].
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]).
- `filter(ids:)`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// "Simple" version
/// All players with the given ids
static func filter(ids: [Int64]) -> SQLRequest<Player> {
"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)
"""
"SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)"
}
}
```
@@ -268,7 +280,7 @@ Let's extend Player with database methods.
```swift
let players = try dbQueue.read { db in
// SELECT * FROM player WHERE id IN (1, 2, 3)
// SELECT * player WHERE id IN (1, 2, 3)
try Player.filter(ids: [1, 2, 3]).fetchAll(db) // [Player]
}
```
@@ -297,21 +309,15 @@ Let's extend Player with database 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]).
- `bestPlayers()`
- `leaders()`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// "Simple" version
static func bestPlayers() -> SQLRequest<Player> {
"SELECT * FROM player WHERE score = (\(maximumScore()))"
}
/// "Future-proof" version
static func bestPlayers() -> SQLRequest<Player> {
/// All players whose score is the maximum score
static func leaders() -> SQLRequest<Player> {
"""
SELECT \(columnsOf: self)
FROM \(self)
WHERE \(CodingKeys.score) = (\(maximumScore()))
SELECT * FROM \(self)
WHERE \(CodingKeys.score) = \(maximumScore())
"""
}
}
@@ -320,9 +326,10 @@ Let's extend Player with database methods.
Usage:
```swift
let bestPlayers = try dbQueue.read { db in
// SELECT * FROM player WHERE score = (SELECT MAX(score) FROM player)
try Player.bestPlayers().fetchAll(db) // [Player]
let leaders = try dbQueue.read { db in
// SELECT * FROM player
// WHERE score = (SELECT MAX(score) FROM player)
try Player.leaders().fetchAll(db) // [Player]
}
```
@@ -334,8 +341,7 @@ Let's extend Player with database methods.
extension Player: Decodable, FetchableRecord, TableRecord {
/// A complex request
static func complexRequest() -> SQLRequest<Player> {
let query: SQLLiteral = "SELECT \(columnsOf: self) "
query += "FROM \(self) "
let query: SQLLiteral = "SELECT * FROM \(self) "
query += "JOIN \(Team.self) ON ..."
query += "GROUP BY ..."
return SQLRequest(literal: query)
@@ -343,7 +349,7 @@ Let's extend Player with database methods.
}
```
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.
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".
@@ -354,9 +360,8 @@ 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 ...
@@ -364,26 +369,6 @@ 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
@@ -420,16 +405,12 @@ This chapter lists all kinds of supported interpolations.
"SELECT * FROM player WHERE id IN \(Column("name").desc)"
```
- Subqueries:
- SQLRequest:
```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))"
// SELECT * FROM player WHERE score = (SELECT MAX(score) FROM player)
let subquery = Player.select(max(Column("score")))
"SELECT * FROM player WHERE score = (\(subquery))"
let subQuery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
"SELECT * FROM player WHERE score = \(subQuery)"
```
- SQLLiteral:
@@ -471,4 +452,3 @@ 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 = '5.0.0-beta'
s.version = '4.14.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+20
View File
@@ -189,6 +189,14 @@
5644DE6E20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; };
5644DE6F20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; };
564A50C81BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */; };
564C2450244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C244F244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift */; };
564C2451244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C244F244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift */; };
564C2452244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C244F244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift */; };
564C2453244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C244F244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift */; };
564C2459244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C2458244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */; };
564C245A244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C2458244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */; };
564C245B244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C2458244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */; };
564C245C244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C2458244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */; };
564CE43121AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
564CE43221AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
564CE43321AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
@@ -1244,6 +1252,8 @@
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversion.swift; sourceTree = "<group>"; };
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
564C244F244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyFirstSQLTests.swift; sourceTree = "<group>"; };
564C2458244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughFirstSQLTests.swift; sourceTree = "<group>"; };
564CE43021AA901800652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = "<group>"; };
564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = "<group>"; };
564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RemoveDuplicates.swift; sourceTree = "<group>"; };
@@ -1831,9 +1841,11 @@
5653EAC920944B4D00F46237 /* AssociationBelongsToSQLTests.swift */,
5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */,
5653EACF20944B4E00F46237 /* AssociationChainSQLTests.swift */,
564C244F244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift */,
561CFA9B2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift */,
56057C4E2291B16900A7CB10 /* AssociationHasManyRowScopeTests.swift */,
56959632222D056D002CB7C9 /* AssociationHasManySQLTests.swift */,
564C2458244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */,
561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */,
56057C612291C7C600A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */,
56959615222C456C002CB7C9 /* AssociationHasManyThroughSQLTests.swift */,
@@ -2845,10 +2857,12 @@
569531091C9067DC00CF1A2B /* DatabaseQueueCrashTests.swift in Sources */,
5695310D1C9067DC00CF1A2B /* RecordCrashTests.swift in Sources */,
56BF2283241781C5003D86EB /* UtilsTests.swift in Sources */,
564C2451244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */,
5695310E1C9067DC00CF1A2B /* StatementColumnConvertibleCrashTests.swift in Sources */,
5695310A1C9067DC00CF1A2B /* DatabaseValueConvertibleCrashTests.swift in Sources */,
5695310F1C9067DC00CF1A2B /* StatementCrashTests.swift in Sources */,
5695310B1C9067DC00CF1A2B /* GRDBCrashTestCase.swift in Sources */,
564C245A244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */,
560A37AF1C90A8D800949E71 /* DatabasePoolCrashTests.swift in Sources */,
56553C101C3E906C00522B5C /* GRDBTestCase.swift in Sources */,
);
@@ -3059,6 +3073,7 @@
56EA869F1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */,
56677C16241D14450050755D /* FailableTestCase.swift in Sources */,
5615B288222B17C000061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
564C245B244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */,
567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
5682D722239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */,
5657AB621D108BA9006283EF /* FoundationNSURLTests.swift in Sources */,
@@ -3116,6 +3131,7 @@
5653EAE520944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */,
56A4CDB41D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */,
56CC9247201E058100CB597E /* DropFirstCursorTests.swift in Sources */,
564C2452244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */,
56915783231BF28B00E1D237 /* PoolTests.swift in Sources */,
56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */,
5665FA342129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
@@ -3265,6 +3281,7 @@
56176C591EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */,
56677C15241D14450050755D /* FailableTestCase.swift in Sources */,
5615B289222B17C000061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
564C2459244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */,
56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */,
56D496601D81304E008276D7 /* FoundationNSUUIDTests.swift in Sources */,
@@ -3322,6 +3339,7 @@
562393601DEE06D300A6B01F /* CursorTests.swift in Sources */,
5653EAE420944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */,
56D4968F1D81316E008276D7 /* RowFromDictionaryTests.swift in Sources */,
564C2450244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */,
56915782231BF28B00E1D237 /* PoolTests.swift in Sources */,
56D4968E1D81316E008276D7 /* RowCopiedFromStatementTests.swift in Sources */,
5665FA332129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
@@ -3600,6 +3618,7 @@
AAA4DD4D230F262000C74B15 /* DatabasePoolReadOnlyTests.swift in Sources */,
56677C17241D14450050755D /* FailableTestCase.swift in Sources */,
AAA4DD4E230F262000C74B15 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
564C245C244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */,
AAA4DD4F230F262000C74B15 /* TruncateOptimizationTests.swift in Sources */,
5682D723239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */,
AAA4DD50230F262000C74B15 /* FoundationNSURLTests.swift in Sources */,
@@ -3657,6 +3676,7 @@
AAA4DD85230F262000C74B15 /* AssociationParallelRowScopesTests.swift in Sources */,
AAA4DD86230F262000C74B15 /* SQLExpressionLiteralTests.swift in Sources */,
AAA4DD87230F262000C74B15 /* DropFirstCursorTests.swift in Sources */,
564C2453244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */,
56915784231BF28B00E1D237 /* PoolTests.swift in Sources */,
AAA4DD88230F262000C74B15 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
AAA4DD89230F262000C74B15 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
-4
View File
@@ -164,10 +164,6 @@ 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() }).isSubset(of: lowercasedColumns) {
if Set(primaryKey.columns.map { $0.lowercased() }) == 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() }).isSubset(of: lowercasedColumns)
index.isUnique && Set(index.columns.map { $0.lowercased() }) == 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.
let context = SQLGenerationContext(self)
let sql = try sqlLiteral.sql(context)
var context = SQLGenerationContext.sqlLiteralContext
let sql = sqlLiteral.sql(&context)
var arguments = context.arguments
let initialValuesCount = arguments.values.count
+1 -4
View File
@@ -301,10 +301,7 @@ public final class Database {
}
private func setupBusyMode() {
let busyMode = configuration.readonly
? configuration.readonlyBusyMode ?? configuration.busyMode
: configuration.busyMode
switch busyMode {
switch configuration.busyMode {
case .immediateError:
break
+6 -3
View File
@@ -223,9 +223,6 @@ 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,
@@ -246,6 +243,12 @@ 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`
+1 -7
View File
@@ -80,9 +80,7 @@ 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.
if readerConfiguration.readonlyBusyMode == nil {
readerConfiguration.readonlyBusyMode = .timeout(10)
}
readerConfiguration.busyMode = .timeout(10)
var readerCount = 0
readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in
@@ -141,10 +139,6 @@ 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) {
+8 -6
View File
@@ -224,16 +224,18 @@ extension DatabaseValue {
extension DatabaseValue {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
// fast path for NULL
if isNull {
// fast path for NULL
return "NULL"
} else if context.append(arguments: [self]) {
// Use statement arguments
}
if context.append(arguments: [self]) {
return "?"
} else {
// Quoting needed: just use SQLite, which knows better.
return try String.fetchOne(context.db, sql: "SELECT QUOTE(?)", arguments: [self])!
// 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])! }
}
}
+1 -1
View File
@@ -26,7 +26,7 @@ struct ValueConversionContext: Refinable {
case .columnIndex(let index):
return index
case .columnName(let name):
return row?.index(forColumn: name)
return row?.index(ofColumn: name)
}
}
+15 -15
View File
@@ -140,12 +140,12 @@ extension Row {
///
/// This method is case-insensitive.
public func hasColumn(_ columnName: String) -> Bool {
index(forColumn: columnName) != nil
index(ofColumn: columnName) != nil
}
@usableFromInline
func index(forColumn name: String) -> Int? {
impl.index(forColumn: name)
func index(ofColumn name: String) -> Int? {
impl.index(ofColumn: name)
}
}
@@ -282,7 +282,7 @@ extension Row {
// if row["foo"] != nil { ... }
//
// Without this method, the code above would not compile.
guard let index = index(forColumn: columnName) else {
guard let index = index(ofColumn: 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(forColumn: columnName) else {
guard let index = index(ofColumn: 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(forColumn: columnName) else {
guard let index = index(ofColumn: 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(forColumn: columnName) else {
guard let index = index(ofColumn: 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(forColumn: columnName) else {
guard let index = index(ofColumn: 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(forColumn: columnName) else {
guard let index = index(ofColumn: 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(forColumn name: String) -> Int?
func index(ofColumn 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(forColumn name: String) -> Int? {
func index(ofColumn 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(forColumn name: String) -> Int? {
func index(ofColumn 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(forColumn name: String) -> Int? {
func index(ofColumn 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(forColumn name: String) -> Int? {
func index(ofColumn 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(forColumn name: String) -> Int? { nil }
func index(ofColumn 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(forColumn name: String) -> Int? {
func index(ofColumn name: String) -> Int? {
mapping.layoutIndex(ofColumn: name)
}
+33 -34
View File
@@ -14,39 +14,34 @@ 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: SQLGenerationContext) throws -> String {
fileprivate func sql(_ context: inout SQLGenerationContext) -> String {
switch self {
case let .sql(sql, arguments):
if context.append(arguments: arguments) == false {
// We don't know how to look for `?` in sql and
// GRDB limitation: we don't know how to look for `?` in sql and
// replace them with literals.
fatalError("Not implemented: turning an SQL parameter into an SQL literal value")
fatalError("Not implemented")
}
return sql
case let .subquery(function):
return try function(context)
case let .expression(expression):
return try expression.expressionSQL(context, wrappedInParenthesis: false)
return expression.expressionSQL(&context, wrappedInParenthesis: false)
case let .selectable(selectable):
return try selectable.resultColumnSQL(context)
return selectable.resultColumnSQL(&context)
case let .orderingTerm(orderingTerm):
return try orderingTerm.orderingTermSQL(context)
return orderingTerm.orderingTermSQL(&context)
case let .subQuery(sqlLiteral):
return "(" + sqlLiteral.sql(&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))
@@ -54,10 +49,24 @@ 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]) {
@@ -88,18 +97,8 @@ public struct SQLLiteral {
self.init(elements: [.expression(expression)])
}
/// 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()
func sql(_ context: inout SQLGenerationContext) -> String {
elements.map { $0.sql(&context) }.joined()
}
fileprivate func qualified(with alias: TableAlias) -> SQLLiteral {
@@ -251,11 +250,11 @@ private struct _SQLExpressionLiteral: SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
if wrappedInParenthesis {
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
}
return try sqlLiteral.sql(context)
return sqlLiteral.sql(&context)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
@@ -275,11 +274,11 @@ private struct _SQLSelectionLiteral: SQLSelectable {
self.sqlLiteral = sqlLiteral
}
func resultColumnSQL(_ context: SQLGenerationContext) throws -> String {
try sqlLiteral.sql(context)
func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
sqlLiteral.sql(&context)
}
func countedSQL(_ context: SQLGenerationContext) throws -> String {
func countedSQL(_ context: inout SQLGenerationContext) -> String {
fatalError("""
Selection literals can't be counted. \
To resolve this error, select one or several literal expressions instead. \
@@ -325,8 +324,8 @@ private struct _SQLOrderingLiteral: SQLOrderingTerm {
""")
}
func orderingTermSQL(_ context: SQLGenerationContext) throws -> String {
try sqlLiteral.sql(context)
func orderingTermSQL(_ context: inout SQLGenerationContext) -> String {
sqlLiteral.sql(&context)
}
func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm {
+41 -34
View File
@@ -1,5 +1,5 @@
/// A FetchRequest built from raw SQL.
public struct SQLRequest<RowDecoder>: FetchRequest {
public struct SQLRequest<T>: 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,6 +12,22 @@ public struct SQLRequest<RowDecoder>: 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?
@@ -73,6 +89,28 @@ public struct SQLRequest<RowDecoder>: 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: """
@@ -108,8 +146,8 @@ public struct SQLRequest<RowDecoder>: FetchRequest {
///
/// :nodoc:
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
let context = SQLGenerationContext(db)
let sql = try sqlLiteral.sql(context)
var context = SQLGenerationContext.sqlLiteralContext
let sql = sqlLiteral.sql(&context)
let statement: SelectStatement
switch cache {
case .none:
@@ -124,37 +162,6 @@ public struct SQLRequest<RowDecoder>: 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) {
+2 -4
View File
@@ -19,10 +19,8 @@ public struct FTS3Pattern {
// that pattern.
do {
try DatabaseQueue().inDatabase { db in
try db.execute(literal: """
CREATE VIRTUAL TABLE documents USING fts3();
SELECT * FROM documents WHERE content MATCH \(rawPattern);
""")
try db.execute(sql: "CREATE VIRTUAL TABLE documents USING fts3()")
try db.execute(sql: "SELECT * FROM documents WHERE content MATCH ?", arguments: [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 = try tokenizer
let tokenizerSQL = tokenizer
.components
.joined(separator: " ")
.sqlExpression
.quotedSQL(db)
.quotedSQL()
arguments.append("tokenize=\(tokenizerSQL)")
}
switch definition.contentMode {
case let .raw(content, contentRowID):
if let content = content {
let quotedContent = try content.sqlExpression.quotedSQL(db)
let quotedContent = content.sqlExpression.quotedSQL()
arguments.append("content=\(quotedContent)")
}
if let contentRowID = contentRowID {
let quotedContentRowID = try contentRowID.sqlExpression.quotedSQL(db)
let quotedContentRowID = contentRowID.sqlExpression.quotedSQL()
arguments.append("content_rowid=\(quotedContentRowID)")
}
case let .synchronized(contentTable):
try arguments.append("content=\(contentTable.sqlExpression.quotedSQL(db))")
arguments.append("content=\(contentTable.sqlExpression.quotedSQL())")
if let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn {
let quotedRowID = try rowIDColumn.sqlExpression.quotedSQL(db)
let quotedRowID = rowIDColumn.sqlExpression.quotedSQL()
arguments.append("content_rowid=\(quotedRowID)")
}
}
if let prefixes = definition.prefixes {
let prefix = try prefixes
let prefix = prefixes
.sorted()
.map { "\($0)" }
.joined(separator: " ")
.sqlExpression
.quotedSQL(db)
.quotedSQL()
arguments.append("prefix=\(prefix)")
}
+26 -37
View File
@@ -59,17 +59,14 @@ public struct FTS5TokenizerDescriptor {
if separators.isEmpty {
components = ["ascii"]
} else {
components = DatabaseQueue().inDatabase { db in
// Assume quoting a string never fails
try! [
"ascii",
"separators",
separators
.map { String($0) }
.joined()
.sqlExpression
.quotedSQL(db)]
}
components = [
"ascii",
"separators",
separators
.map { String($0) }
.joined()
.sqlExpression
.quotedSQL()]
}
return FTS5TokenizerDescriptor(components: components)
}
@@ -129,37 +126,29 @@ public struct FTS5TokenizerDescriptor {
// TODO: test "=" and "\"", "(" and ")" as separators, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
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)
components.append(contentsOf: [
"separators",
separators
.sorted()
.map { String($0) }
.joined()
.sqlExpression
.quotedSQL()
])
}
if !tokenCharacters.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
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)
components.append(contentsOf: [
"tokenchars",
tokenCharacters
.sorted()
.map { String($0) }
.joined()
.sqlExpression
.quotedSQL()
])
}
return FTS5TokenizerDescriptor(components: components)
}
+6 -47
View File
@@ -134,23 +134,12 @@ 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() }
@@ -162,7 +151,7 @@ public struct SQLExpressionLiteral: SQLExpression {
public init(literal sqlLiteral: SQLLiteral)
{ preconditionFailure() }
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String
{ preconditionFailure() }
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression
@@ -173,37 +162,11 @@ 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
@@ -228,10 +191,6 @@ 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 {
@@ -254,7 +213,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() }
@@ -267,7 +226,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,
@@ -278,7 +237,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,
@@ -291,7 +250,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,
@@ -325,7 +284,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 { db in [Column("color")]
/// let association = Player.team.select([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 { db in [Column("id")] }
/// .select { db in [Column("color") }
/// .select([Column("id")])
/// .select([Column("color")])
/// var request = Player.including(required: association)
public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
public func select(_ selection: [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: { db in [Column("name")] })
/// .annotated(with: [Column("name")])
/// var request = Player.including(required: association)
public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
public func annotated(with selection: [SQLSelectable]) -> Self {
mapDestinationRelation { $0.annotated(with: selection) }
}
@@ -321,3 +321,166 @@ 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> {
// TODO: try to replace rowid with actual primary key
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> {
// TODO: try to replace rowid with actual primary key
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,181 +1,8 @@
import Foundation
typealias AssociationAggregatePreparation<RowDecoder> =
(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
}
}
}
(QueryInterfaceRequest<RowDecoder>)
-> (request: QueryInterfaceRequest<RowDecoder>, expression: SQLExpression)
/// An AssociationAggregate is able to compute aggregated values from a
/// population of associated records.
@@ -200,9 +27,10 @@ extension AssociationToMany {
/// // Won't compile because Fruit is not Author.
/// let request = Fruit.annotated(with: bookCount)
public struct AssociationAggregate<RowDecoder> {
/// Extend the request with the associated records used to compute the
/// aggregate, and return an expression promise which resolves to the
/// aggregated value.
// TODO: replace rowid with actual primary key in the doc when implemented
/// 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.
///
/// For example:
///
@@ -211,22 +39,22 @@ public struct AssociationAggregate<RowDecoder> {
/// }
///
/// // SELECT * FROM author
/// var request = Author.all()
/// let request = Author.all()
///
/// let aggregate = Author.books.count
/// let expressionPromise = aggregate.prepare(&request)
/// let tuple = aggregate.prepare(request)
///
/// // The request has been extended with associated records:
/// // The request extended with associated records:
/// //
/// // SELECT author.* FROM author
/// // LEFT JOIN book ON book.authorId = author.id
/// // GROUP BY author.id
/// request
/// tuple.request
///
/// // The aggregated value:
/// //
/// // COUNT(DISTINCT book.id)
/// try expressionPromise.resolve(db)
/// // COUNT(DISTINCT book.rowid)
/// tuple.expression
///
/// The aggregated value is not right away embedded in the extended request:
///
@@ -271,31 +99,6 @@ 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)
@@ -306,7 +109,10 @@ private func combine<RowDecoder>(
///
/// Author.having(!Author.books.isEmpty)
public prefix func ! <RowDecoder>(aggregate: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
aggregate.map { !$0 }
AssociationAggregate { request in
let (request, expression) = aggregate.prepare(request)
return (request: request, expression: !expression)
}
}
/// Groups two aggregates with the `AND` SQL operator.
@@ -319,7 +125,11 @@ public func && <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
combine(lhs, rhs, with: &&)
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression && rExpression)
}
}
// TODO: test
@@ -329,7 +139,10 @@ public func && <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
lhs.map { $0 && rhs }
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression && rhs)
}
}
// TODO: test
@@ -339,7 +152,10 @@ public func && <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
rhs.map { lhs && $0 }
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs && expression)
}
}
@@ -353,7 +169,11 @@ public func || <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
combine(lhs, rhs, with: ||)
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression || rExpression)
}
}
// TODO: test
@@ -363,7 +183,10 @@ public func || <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
lhs.map { $0 || rhs }
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression || rhs)
}
}
// TODO: test
@@ -373,7 +196,10 @@ public func || <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
rhs.map { lhs || $0 }
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs || expression)
}
}
// MARK: - Egality and Identity Operators (=, <>, IS, IS NOT)
@@ -388,7 +214,11 @@ public func == <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
combine(lhs, rhs, with: ==)
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression == rExpression)
}
}
/// Returns an aggregate that compares an aggregate with the `=` SQL operator.
@@ -401,7 +231,10 @@ public func == <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
lhs.map { $0 == rhs }
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression == rhs)
}
}
/// Returns an aggregate that compares an aggregate with the `=` SQL operator.
@@ -414,7 +247,10 @@ public func == <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
rhs.map { lhs == $0 }
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs == expression)
}
}
/// Returns an aggregate that checks the boolean value of an aggregate.
@@ -423,7 +259,10 @@ public func == <RowDecoder>(
///
/// Author.having(Author.books.isEmpty == false)
public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) -> AssociationAggregate<RowDecoder> {
lhs.map { $0 == rhs }
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression == rhs)
}
}
/// Returns an aggregate that checks the boolean value of an aggregate.
@@ -432,7 +271,10 @@ public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) ->
///
/// Author.having(false == Author.books.isEmpty)
public func == <RowDecoder>(lhs: Bool, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
rhs.map { lhs == $0 }
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs == expression)
}
}
/// Returns an aggregate that compares two aggregates with the `<>` SQL operator.
@@ -445,7 +287,11 @@ public func != <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
combine(lhs, rhs, with: !=)
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression != rExpression)
}
}
/// Returns an aggregate that compares an aggregate with the `<>` SQL operator.
@@ -458,7 +304,10 @@ public func != <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
lhs.map { $0 != rhs }
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression != rhs)
}
}
/// Returns an aggregate that compares an aggregate with the `<>` SQL operator.
@@ -471,7 +320,10 @@ public func != <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
rhs.map { lhs != $0 }
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs != expression)
}
}
/// Returns an aggregate that checks the boolean value of an aggregate.
@@ -480,7 +332,10 @@ public func != <RowDecoder>(
///
/// Author.having(Author.books.isEmpty != true)
public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) -> AssociationAggregate<RowDecoder> {
lhs.map { $0 != rhs }
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression != rhs)
}
}
/// Returns an aggregate that checks the boolean value of an aggregate.
@@ -489,7 +344,10 @@ public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) ->
///
/// Author.having(true != Author.books.isEmpty)
public func != <RowDecoder>(lhs: Bool, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
rhs.map { lhs != $0 }
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs != expression)
}
}
/// Returns an aggregate that compares two aggregates with the `IS` SQL operator.
@@ -502,7 +360,11 @@ public func === <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
combine(lhs, rhs, with: ===)
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression === rExpression)
}
}
/// Returns an aggregate that compares an aggregate with the `IS` SQL operator.
@@ -515,7 +377,10 @@ public func === <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
lhs.map { $0 === rhs }
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression === rhs)
}
}
/// Returns an aggregate that compares an aggregate with the `IS` SQL operator.
@@ -528,7 +393,10 @@ public func === <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
rhs.map { lhs === $0 }
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs === expression)
}
}
/// Returns an aggregate that compares two aggregates with the `IS NOT` SQL operator.
@@ -541,7 +409,11 @@ public func !== <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
combine(lhs, rhs, with: !==)
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression !== rExpression)
}
}
/// Returns an aggregate that compares an aggregate with the `IS NOT` SQL operator.
@@ -554,7 +426,10 @@ public func !== <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
lhs.map { $0 !== rhs }
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression !== rhs)
}
}
/// Returns an aggregate that compares an aggregate with the `IS NOT` SQL operator.
@@ -567,7 +442,10 @@ public func !== <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
rhs.map { lhs !== $0 }
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs !== expression)
}
}
// MARK: - Comparison Operators (<, >, <=, >=)
@@ -582,7 +460,11 @@ public func <= <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
combine(lhs, rhs, with: <=)
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression <= rExpression)
}
}
/// Returns an aggregate that compares an aggregate with the `<=` SQL operator.
@@ -595,7 +477,10 @@ public func <= <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
lhs.map { $0 <= rhs }
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression <= rhs)
}
}
/// Returns an aggregate that compares an aggregate with the `<=` SQL operator.
@@ -608,7 +493,10 @@ public func <= <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
rhs.map { lhs <= $0 }
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs <= expression)
}
}
/// Returns an aggregate that compares two aggregates with the `<` SQL operator.
@@ -621,7 +509,11 @@ public func < <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
combine(lhs, rhs, with: <)
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression < rExpression)
}
}
/// Returns an aggregate that compares an aggregate with the `<` SQL operator.
@@ -634,7 +526,10 @@ public func < <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
lhs.map { $0 < rhs }
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression < rhs)
}
}
/// Returns an aggregate that compares an aggregate with the `<` SQL operator.
@@ -647,7 +542,10 @@ public func < <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
rhs.map { lhs < $0 }
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs < expression)
}
}
/// Returns an aggregate that compares two aggregates with the `>` SQL operator.
@@ -660,7 +558,11 @@ public func > <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
combine(lhs, rhs, with: >)
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression > rExpression)
}
}
/// Returns an aggregate that compares an aggregate with the `>` SQL operator.
@@ -673,7 +575,10 @@ public func > <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
lhs.map { $0 > rhs }
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression > rhs)
}
}
/// Returns an aggregate that compares an aggregate with the `>` SQL operator.
@@ -686,7 +591,10 @@ public func > <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
rhs.map { lhs > $0 }
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs > expression)
}
}
/// Returns an aggregate that compares two aggregates with the `>=` SQL operator.
@@ -699,7 +607,11 @@ public func >= <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
combine(lhs, rhs, with: >=)
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression >= rExpression)
}
}
/// Returns an aggregate that compares an aggregate with the `>=` SQL operator.
@@ -712,7 +624,10 @@ public func >= <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
lhs.map { $0 >= rhs }
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression >= rhs)
}
}
/// Returns an aggregate that compares an aggregate with the `>=` SQL operator.
@@ -725,7 +640,10 @@ public func >= <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
rhs.map { lhs >= $0 }
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs >= expression)
}
}
// MARK: - Arithmetic Operators (+, -, *, /)
@@ -736,7 +654,10 @@ public func >= <RowDecoder>(
///
/// Author.annotated(with: -Author.books.count)
public prefix func - <RowDecoder>(aggregate: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
aggregate.map { -$0 }
AssociationAggregate { request in
let (request, expression) = aggregate.prepare(request)
return (request: request, expression:-expression)
}
}
/// Returns an aggregate that sums two aggregates with the `+` SQL operator.
@@ -749,7 +670,11 @@ public func + <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
combine(lhs, rhs, with: +)
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression + rExpression)
}
}
/// Returns an aggregate that sums an aggregate with the `+` SQL operator.
@@ -762,7 +687,10 @@ public func + <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
lhs.map { $0 + rhs }
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression + rhs)
}
}
/// Returns an aggregate that sums an aggregate with the `+` SQL operator.
@@ -775,7 +703,10 @@ public func + <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
rhs.map { lhs + $0 }
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs + expression)
}
}
/// Returns an aggregate that substracts two aggregates with the `-` SQL operator.
@@ -788,7 +719,11 @@ public func - <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
combine(lhs, rhs, with: -)
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression - rExpression)
}
}
/// Returns an aggregate that substracts an aggregate with the `-` SQL operator.
@@ -801,7 +736,10 @@ public func - <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
lhs.map { $0 - rhs }
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression - rhs)
}
}
/// Returns an aggregate that substracts an aggregate with the `-` SQL operator.
@@ -814,7 +752,10 @@ public func - <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
rhs.map { lhs - $0 }
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs - expression)
}
}
/// Returns an aggregate that multiplies two aggregates with the `*` SQL operator.
@@ -827,7 +768,11 @@ public func * <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
combine(lhs, rhs, with: *)
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression * rExpression)
}
}
/// Returns an aggregate that substracts an aggregate with the `*` SQL operator.
@@ -840,7 +785,10 @@ public func * <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
lhs.map { $0 * rhs }
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression * rhs)
}
}
/// Returns an aggregate that substracts an aggregate with the `*` SQL operator.
@@ -853,7 +801,10 @@ public func * <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
rhs.map { lhs * $0 }
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs * expression)
}
}
/// Returns an aggregate that multiplies two aggregates with the `/` SQL operator.
@@ -866,7 +817,11 @@ public func / <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
combine(lhs, rhs, with: /)
AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
return (request: request, expression: lExpression / rExpression)
}
}
/// Returns an aggregate that substracts an aggregate with the `/` SQL operator.
@@ -879,7 +834,10 @@ public func / <RowDecoder>(
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
lhs.map { $0 / rhs }
AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression / rhs)
}
}
/// Returns an aggregate that substracts an aggregate with the `/` SQL operator.
@@ -892,7 +850,10 @@ public func / <RowDecoder>(
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
rhs.map { lhs / $0 }
AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs / expression)
}
}
// MARK: - IFNULL(...)
@@ -905,8 +866,14 @@ 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
lhs.map { $0 ?? rhs }.with(\.key, lhs.key)
aggregate.key = lhs.key
return aggregate
}
// 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.relationForAll,
relation: Destination.all().relation,
cardinality: .toOne)
}
}
@@ -96,7 +96,72 @@ public struct HasManyAssociation<Origin: TableRecord, Destination: TableRecord>:
sqlAssociation = SQLAssociation(
key: associationKey,
condition: condition,
relation: Destination.relationForAll,
relation: Destination.all().relation,
cardinality: .toMany)
}
/// Creates a "Has one" association between the source and
/// destination types.
///
/// struct Book: TableRecord { ... }
/// struct Author: TableRecord {
/// static let firstBook = hasMany(Book.self).order(Column("year")).first
/// }
///
/// The association lets you define requests that load both the source
/// and the destination type:
///
/// // A request for all (author, firstBook) pairs:
/// let request = Author.including(required: Author.firstBook)
///
/// To consume those requests, define a type that adopts both the
/// FetchableRecord and Decodable protocols:
///
/// struct Authorship: FetchableRecord, Decodable {
/// var author: Author
/// var firstBook: Book
/// }
///
/// let authorships = try dbQueue.read { db in
/// return try Authorship.fetchAll(db, request)
/// }
/// for authorship in authorships {
/// print("\(authorship.author.name) wrote \(authorship.firstBook.title) first")
/// }
public var first: HasOneAssociation<Origin, Destination> {
HasOneAssociation(sqlAssociation: sqlAssociation.associationForFirst())
.forKey("first\(key.singularizedName.uppercasingFirstCharacter)")
}
/// Creates a "Has one" association between the source and
/// destination types.
///
/// struct Book: TableRecord { ... }
/// struct Author: TableRecord {
/// static let lastBook = hasMany(Book.self).order(Column("year")).last
/// }
///
/// The association lets you define requests that load both the source
/// and the destination type:
///
/// // A request for all (author, firstBook) pairs:
/// let request = Author.including(required: Author.lastBook)
///
/// To consume those requests, define a type that adopts both the
/// FetchableRecord and Decodable protocols:
///
/// struct Authorship: FetchableRecord, Decodable {
/// var author: Author
/// var lastBook: Book
/// }
///
/// let authorships = try dbQueue.read { db in
/// return try Authorship.fetchAll(db, request)
/// }
/// for authorship in authorships {
/// print("\(authorship.author.name) wrote \(authorship.lastBook.title) last")
/// }
public var last: HasOneAssociation<Origin, Destination> {
reversed().first.forKey("last\(key.singularizedName.uppercasingFirstCharacter)")
}
}
@@ -55,4 +55,15 @@ public struct HasManyThroughAssociation<Origin: TableRecord, Destination: TableR
public init(sqlAssociation: SQLAssociation) {
self.sqlAssociation = sqlAssociation
}
// TODO
public var first: HasOneThroughAssociation<Origin, Destination> {
HasOneThroughAssociation(sqlAssociation: sqlAssociation.associationForFirst())
.forKey("first\(key.singularizedName.uppercasingFirstCharacter)")
}
// TODO
public var last: HasOneThroughAssociation<Origin, Destination> {
reversed().first.forKey("last\(key.singularizedName.uppercasingFirstCharacter)")
}
}
@@ -98,7 +98,7 @@ public struct HasOneAssociation<Origin: TableRecord, Destination: TableRecord>:
sqlAssociation = SQLAssociation(
key: associationKey,
condition: condition,
relation: Destination.relationForAll,
relation: Destination.all().relation,
cardinality: .toOne)
}
}
@@ -3,18 +3,18 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
// MARK: - Association Aggregates
private func annotated(with aggregate: AssociationAggregate<RowDecoder>) -> QueryInterfaceRequest {
var request = self
let expressionPromise = aggregate.prepare(&request)
let (request, expression) = aggregate.prepare(self)
if let key = aggregate.key {
return request.annotated(with: { db in try [expressionPromise.resolve(db).forKey(key)] })
return request.annotated(with: [expression.forKey(key)])
} else {
return request.annotated(with: { db in try [expressionPromise.resolve(db)] })
return request.annotated(with: [expression])
}
}
// TODO: replace rowid with actual primary key in the doc when implemented
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.all()
/// request = request.annotated(with: Player.books.count)
@@ -22,9 +22,10 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
annotated(with: aggregates)
}
// TODO: replace rowid with actual primary key in the doc when implemented
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.all()
/// request = request.annotated(with: [Player.books.count])
@@ -34,17 +35,17 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
}
}
// TODO: replace rowid with actual primary key in the doc when implemented
/// Creates a request which appends the provided aggregate *predicate* to
/// the eventual set of already applied predicates.
///
/// // SELECT player.*
/// // FROM player LEFT JOIN book ...
/// // HAVING COUNT(DISTINCT book.id) = 0
/// // HAVING COUNT(DISTINCT book.rowid) = 0
/// var request = Player.all()
/// request = request.having(Player.books.isEmpty)
public func having(_ predicate: AssociationAggregate<RowDecoder>) -> QueryInterfaceRequest {
var request = self
let expressionPromise = predicate.prepare(&request)
return request.having(expressionPromise.resolve)
let (request, expression) = predicate.prepare(self)
return request.having(expression)
}
}
@@ -28,7 +28,7 @@
/// }
///
/// See https://github.com/groue/GRDB.swift#the-query-interface
public struct QueryInterfaceRequest<RowDecoder> {
public struct QueryInterfaceRequest<T> {
var query: SQLQuery
}
@@ -39,6 +39,8 @@ 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.
///
@@ -47,8 +49,14 @@ extension QueryInterfaceRequest: FetchRequest {
/// - returns: A prepared statement and an eventual row adapter.
/// :nodoc:
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
let generator = SQLQueryGenerator(query: query, forSingleResult: singleResult)
let (statement, adapter) = try generator.prepare(db)
var query = self.query
// Optimize query by setting a limit of 1 when appropriate
if singleResult && !query.expectsSingleResult {
query.limit = SQLLimit(limit: 1, offset: query.limit?.offset)
}
let (statement, adapter) = try SQLQueryGenerator(query).prepare(db)
let associations = query.relation.prefetchedAssociations
if associations.isEmpty {
return PreparedRequest(statement: statement, adapter: adapter)
@@ -76,9 +84,7 @@ extension QueryInterfaceRequest: FetchRequest {
/// - parameter db: A database connection.
/// :nodoc:
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
var region = try SQLQueryGenerator(query: query)
.makeSelectStatement(db)
.selectedRegion
var region = try SQLQueryGenerator(query).makeSelectStatement(db).selectedRegion
// Iterate all prefetched associations
var fifo = query.relation.prefetchedAssociations
@@ -92,20 +98,12 @@ extension QueryInterfaceRequest: FetchRequest {
let pivotAlias = TableAlias()
let prefetchedRelation = association
.map(\.pivot.relation, { $0.qualified(with: pivotAlias) })
// Use a `NullRow` in order to make sure all join condition
// columns are made visible to SQLite, and present in the
// selected region:
// ... JOIN right ON right.leftId IS NULL
// ^ content of the NullRow
.destinationRelation(fromOriginRows: { _ in [NullRow()] })
.destinationRelation(fromOriginRows: { _ in [] /* no origin row */ })
.annotated(with: pivotColumns.map { pivotAlias[Column($0)].forKey("grdb_\($0)") })
let prefetchedQuery = SQLQuery(relation: prefetchedRelation)
// Union prefetched region
let prefetchedRegion = try SQLQueryGenerator(query: prefetchedQuery)
.makeSelectStatement(db)
.selectedRegion
region.formUnion(prefetchedRegion)
// Union region
try region.formUnion(SQLQueryGenerator(prefetchedQuery).makeSelectStatement(db).selectedRegion)
// Append nested prefetched associations (support for
// A.including(all: A.bs.including(all: B.cs))
@@ -119,19 +117,19 @@ extension QueryInterfaceRequest: FetchRequest {
extension QueryInterfaceRequest: SelectionRequest {
// MARK: Request Derivation
/// Creates a request which selects *selection promise*.
/// Creates a request which selects *selection*.
///
/// // SELECT id, email FROM player
/// var request = Player.all()
/// request = request.select { db in [Column("id"), Column("email")] }
/// request = request.select([Column("id"), Column("email")])
///
/// Any previous selection is replaced:
///
/// // SELECT email FROM player
/// request
/// .select { db in [Column("id")] }
/// .select { db in [Column("email")] }
public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest {
/// .select([Column("id")])
/// .select([Column("email")])
public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest {
map(\.query) { $0.select(selection) }
}
@@ -215,14 +213,14 @@ extension QueryInterfaceRequest: SelectionRequest {
select(sqlLiteral.sqlSelectable, as: type)
}
/// Creates a request which appends *selection promise*.
/// 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: { db in [Column("name")] })
public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest {
/// .annotated(with: [Column("name")])
public func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest {
map(\.query) { $0.annotated(with: selection) }
}
}
@@ -294,9 +292,9 @@ extension QueryInterfaceRequest: AggregatingRequest {
map(\.query) { $0.group(expressions) }
}
/// Creates a request with the provided *predicate promise* added to the
/// Creates a request with the provided *predicate* added to the
/// eventual set of already applied predicates.
public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest {
public func having(_ predicate: SQLExpressible) -> QueryInterfaceRequest {
map(\.query) { $0.having(predicate) }
}
}
@@ -328,7 +326,7 @@ extension QueryInterfaceRequest: _JoinableRequest {
}
}
extension QueryInterfaceRequest: JoinableRequest where RowDecoder: TableRecord { }
extension QueryInterfaceRequest: JoinableRequest where T: TableRecord { }
extension QueryInterfaceRequest: Refinable {
@@ -347,6 +345,18 @@ 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
@@ -397,72 +407,25 @@ extension QueryInterfaceRequest: Refinable {
}
}
// 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
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
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
try "(" + generator.sql(context) + ")"
}
// 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 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))
return query.relation
}
}
@@ -478,7 +441,7 @@ extension QueryInterfaceRequest: TableRequest {
// request.filter(keys: ...)
// request.orderByPrimaryKey()
return tableName
case .subquery:
case .query:
// The only current use case for SQLSource.query is the
// "trivial count query" (see SQLQuery.countQuery):
//
@@ -493,9 +456,9 @@ extension QueryInterfaceRequest: TableRequest {
}
}
extension QueryInterfaceRequest: DerivableRequest where RowDecoder: TableRecord { }
extension QueryInterfaceRequest: DerivableRequest where T: TableRecord { }
extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
extension QueryInterfaceRequest where T: MutablePersistableRecord {
// MARK: Batch Delete
@@ -506,7 +469,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@discardableResult
public func deleteAll(_ db: Database) throws -> Int {
try SQLQueryGenerator(query: query).makeDeleteStatement(db).execute()
try SQLQueryGenerator(query).makeDeleteStatement(db).execute()
return db.changesCount
}
@@ -534,7 +497,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
_ assignments: [ColumnAssignment]) throws -> Int
{
let conflictResolution = conflictResolution ?? RowDecoder.persistenceConflictPolicy.conflictResolutionForUpdate
guard let updateStatement = try SQLQueryGenerator(query: query).makeUpdateStatement(
guard let updateStatement = try SQLQueryGenerator(query).makeUpdateStatement(
db,
conflictResolution: conflictResolution,
assignments: assignments) else
@@ -622,7 +585,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(forColumns: pivotMappings.map(\.left))
let groupingIndexes = firstRow.indexes(ofColumns: pivotMappings.map(\.left))
for row in rows {
let groupingKey = groupingIndexes.map { row.impl.databaseValue(atUncheckedIndex: $0) }
let prefetchedRows = prefetchedRows[groupingKey, default: []]
@@ -638,7 +601,7 @@ extension Array where Element == Row {
guard let firstRow = first else {
return [:]
}
let indexes = firstRow.indexes(forColumns: columns)
let indexes = firstRow.indexes(ofColumns: columns)
return Dictionary(grouping: self, by: { row in
indexes.map { row.impl.databaseValue(atUncheckedIndex: $0) }
})
@@ -647,9 +610,9 @@ extension Array where Element == Row {
extension Row {
/// - precondition: Columns all exist in the row.
fileprivate func indexes(forColumns columns: [String]) -> [Int] {
fileprivate func indexes(ofColumns columns: [String]) -> [Int] {
columns.map { column -> Int in
guard let index = index(forColumn: column) else {
guard let index = index(ofColumn: column) else {
fatalError("Column \(column) is not selected")
}
return index
@@ -673,10 +636,10 @@ public struct ColumnAssignment {
var column: ColumnExpression
var value: SQLExpressible
func sql(_ context: SQLGenerationContext) throws -> String {
try column.expressionSQL(context, wrappedInParenthesis: false) +
func sql(_ context: inout SQLGenerationContext) -> String {
column.expressionSQL(&context, wrappedInParenthesis: false) +
" = " +
value.sqlExpression.expressionSQL(context, wrappedInParenthesis: false)
value.sqlExpression.expressionSQL(&context, wrappedInParenthesis: false)
}
}
@@ -6,32 +6,6 @@
///
/// :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
@@ -44,10 +18,20 @@ extension SelectionRequest {
/// request
/// .select([Column("id")])
/// .select([Column("email")])
public func select(_ selection: [SQLSelectable]) -> Self {
select { _ in selection }
}
func select(_ selection: [SQLSelectable]) -> Self
/// 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
@@ -107,18 +91,7 @@ extension SelectionRequest {
/// .select(literal: SQLLiteral(sql: "email"))
public func select(literal sqlLiteral: SQLLiteral) -> Self {
// NOT TESTED
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 })
return select(sqlLiteral.sqlSelectable)
}
/// Creates a request which appends *selection*.
@@ -148,10 +121,23 @@ 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.
///
@@ -188,7 +174,7 @@ extension FilteredRequest {
/// request = request.filter(literal: "name = \("O'Brien")")
public func filter(literal sqlLiteral: SQLLiteral) -> Self {
// NOT TESTED
filter(sqlLiteral.sqlExpression)
return filter(sqlLiteral.sqlExpression)
}
/// Creates a request that matches nothing.
@@ -248,13 +234,19 @@ extension TableRequest where Self: FilteredRequest {
-> Self
where Sequence.Element: DatabaseValueConvertible
{
var request = self
let keys = Array(keys)
if keys.isEmpty {
switch keys.count {
case 0:
return none()
case 1:
request = request.expectingSingleResult()
default:
break
}
let databaseTableName = self.databaseTableName
return filter { db in
return request.filter { db in
let primaryKey = try db.primaryKey(databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
@@ -279,12 +271,18 @@ 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 {
if keys.isEmpty {
var request = self
switch keys.count {
case 0:
return none()
case 1:
request = request.expectingSingleResult()
default:
break
}
let databaseTableName = self.databaseTableName
return filter { db in
return request.filter { db in
try keys
.map { key in
// Prevent filter(keys: [["foo": 1, "bar": 2]]) where
@@ -346,9 +344,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 promise* added to the
/// Creates a request with the provided *predicate* added to the
/// eventual set of already applied predicates.
func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self
func having(_ predicate: SQLExpressible) -> Self
}
/// :nodoc:
@@ -371,13 +369,7 @@ extension AggregatingRequest {
/// Creates a request with a new grouping.
public func group(literal sqlLiteral: SQLLiteral) -> Self {
// NOT TESTED
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 }
return group(sqlLiteral.sqlExpression)
}
/// Creates a request with the provided *sql* added to the
@@ -390,7 +382,7 @@ extension AggregatingRequest {
/// eventual set of already applied predicates.
public func having(literal sqlLiteral: SQLLiteral) -> Self {
// NOT TESTED
having(sqlLiteral.sqlExpression)
return having(sqlLiteral.sqlExpression)
}
}
@@ -504,7 +496,7 @@ extension OrderedRequest {
/// .order(sql: "name")
public func order(literal sqlLiteral: SQLLiteral) -> Self {
// NOT TESTED
order(sqlLiteral.sqlOrderingTerm)
return 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: SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
name.quotedDatabaseIdentifier
}
@@ -73,7 +73,7 @@ struct QualifiedColumn: ColumnExpression {
self.alias = alias
}
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
func expressionSQL(_ context: inout 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
self
return self
}
}
@@ -41,4 +41,10 @@ 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)
}
}
}
+22 -14
View File
@@ -95,6 +95,17 @@ public /* TODO: internal */ struct SQLAssociation {
SQLAssociation(steps: other.steps + steps)
}
func associationForFirst() -> Self {
SQLAssociation(steps: steps.map { step in
switch step.cardinality {
case .toOne:
return step
case .toMany:
return step.map(\.relation) { $0.with(\.firstOnly, true) }
}
})
}
/// Given an origin alias and rows, returns the destination of the
/// association as a relation.
///
@@ -135,16 +146,13 @@ 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<Row>(
fromOriginRows originRows: @escaping (Database) throws -> [Row])
-> SQLRelation
where Row: ColumnAddressable
{
// Filter the pivot: `pivot.originId = 123` or `pivot.originId IN (1, 2, 3)`
func destinationRelation(fromOriginRows originRows: @escaping (Database) throws -> [Row]) -> SQLRelation {
// Filter the pivot
let pivot = self.pivot
let filteredPivotRelation = pivot.relation.filter { db in
let filteredPivotRelation = pivot.relation.filter({ db in
// `pivot.originId = 123` or `pivot.originId IN (1, 2, 3)`
try pivot.condition.filteringExpression(db, leftRows: originRows(db))
}
})
if steps.count == 1 {
// This is a direct join from origin to destination, without
@@ -179,11 +187,11 @@ public /* TODO: internal */ struct SQLAssociation {
let relation = step.relation
.selectOnly([])
.filteringChildren({
switch $0.kind {
case .allPrefetched, .allNotPrefetched: return false
case .oneRequired, .oneOptional: return true
}
})
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)" }
@@ -213,7 +221,7 @@ struct SQLAssociationStep: Refinable {
case .toOne:
return true
case .toMany:
return false
return relation.firstOnly
}
}
@@ -87,8 +87,8 @@ extension SQLCollatedExpression: SQLOrderingTerm {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func orderingTermSQL(_ context: SQLGenerationContext) throws -> String {
try sqlExpression.orderingTermSQL(context)
public func orderingTermSQL(_ context: inout SQLGenerationContext) -> String {
sqlExpression.orderingTermSQL(&context)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
+8 -11
View File
@@ -9,16 +9,13 @@ 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: SQLGenerationContext) throws -> String
func collectionSQL(_ context: inout SQLGenerationContext) -> 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
}
@@ -43,9 +40,13 @@ extension SQLCollection {
struct SQLExpressionsArray: SQLCollection {
let expressions: [SQLExpression]
func collectionSQL(_ context: SQLGenerationContext) throws -> String {
try expressions
.map { try $0.expressionSQL(context, wrappedInParenthesis: false) }
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) }
.joined(separator: ", ")
}
@@ -61,8 +62,4 @@ 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: SQLGenerationContext) throws -> String {
try sqlExpression.expressionSQL(context, wrappedInParenthesis: false)
public func orderingTermSQL(_ context: inout SQLGenerationContext) -> String {
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: SQLGenerationContext) throws -> String {
try sqlExpression.expressionSQL(context, wrappedInParenthesis: false)
public func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
sqlExpression.expressionSQL(&context, wrappedInParenthesis: false)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func countedSQL(_ context: SQLGenerationContext) throws -> String {
try sqlExpression.expressionSQL(context, wrappedInParenthesis: false)
public func countedSQL(_ context: inout SQLGenerationContext) -> String {
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)
///
/// 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)
/// "foo'bar".databaseValue.quotedSQL() // "'foo''bar'""
func quotedSQL() -> String {
var context = SQLGenerationContext.rawSQLContext
return expressionSQL(&context, wrappedInParenthesis: false)
}
}
@@ -70,13 +70,11 @@ public struct SQLExpressionUnary: SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
if wrappedInParenthesis {
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
}
return try op.sql
+ (op.needsRightSpace ? " " : "")
+ expression.expressionSQL(context, wrappedInParenthesis: true)
return op.sql + (op.needsRightSpace ? " " : "") + expression.expressionSQL(&context, wrappedInParenthesis: true)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
@@ -168,14 +166,14 @@ public struct SQLExpressionBinary: SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
if wrappedInParenthesis {
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
}
return try """
\(lhs.expressionSQL(context, wrappedInParenthesis: true)) \
return """
\(lhs.expressionSQL(&context, wrappedInParenthesis: true)) \
\(op.sql) \
\(rhs.expressionSQL(context, wrappedInParenthesis: true))
\(rhs.expressionSQL(&context, wrappedInParenthesis: true))
"""
}
@@ -265,14 +263,14 @@ struct SQLExpressionBinaryReduce: SQLExpression {
}
}
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
guard let first = expressions.first else {
return try op.neutralValue.expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis)
return op.neutralValue.sqlExpression.expressionSQL(&context, wrappedInParenthesis: false)
}
if expressions.count == 1 {
return try first.expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis)
return first.expressionSQL(&context, wrappedInParenthesis: wrappedInParenthesis)
}
let expressionSQLs = try expressions.map { try $0.expressionSQL(context, wrappedInParenthesis: true) }
let expressionSQLs = expressions.map { $0.expressionSQL(&context, wrappedInParenthesis: true) }
let joiner = " \(op.sql) "
if wrappedInParenthesis {
return "(\(expressionSQLs.joined(separator: joiner)))"
@@ -311,22 +309,6 @@ 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 {
@@ -394,14 +376,14 @@ struct SQLExpressionEqual: SQLExpression {
}
}
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
if wrappedInParenthesis {
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
}
return try """
\(lhs.expressionSQL(context, wrappedInParenthesis: true)) \
return """
\(lhs.expressionSQL(&context, wrappedInParenthesis: true)) \
\(op.rawValue) \
\(rhs.expressionSQL(context, wrappedInParenthesis: true))
\(rhs.expressionSQL(&context, wrappedInParenthesis: true))
"""
}
@@ -465,14 +447,14 @@ struct SQLExpressionContains: SQLExpression {
self.isNegated = negated
}
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
if wrappedInParenthesis {
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
}
return try """
\(expression.expressionSQL(context, wrappedInParenthesis: true)) \
return """
\(expression.expressionSQL(&context, wrappedInParenthesis: true)) \
\(isNegated ? "NOT IN" : "IN") \
(\(collection.collectionSQL(context)))
(\(collection.collectionSQL(&context)))
"""
}
@@ -481,10 +463,7 @@ struct SQLExpressionContains: SQLExpression {
}
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
return SQLExpressionContains(
expression.qualifiedExpression(with: alias),
collection.qualifiedCollection(with: alias),
negated: isNegated)
SQLExpressionContains(expression.qualifiedExpression(with: alias), collection, negated: isNegated)
}
func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
@@ -536,16 +515,16 @@ struct SQLExpressionBetween: SQLExpression {
self.isNegated = negated
}
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
if wrappedInParenthesis {
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
}
return try """
\(expression.expressionSQL(context, wrappedInParenthesis: true)) \
return """
\(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))
"""
}
@@ -629,11 +608,11 @@ public struct SQLExpressionFunction: SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
var sql = functionName.sql
sql += "("
sql += try arguments
.map { try $0.expressionSQL(context, wrappedInParenthesis: false) }
sql += arguments
.map { $0.expressionSQL(&context, wrappedInParenthesis: false) }
.joined(separator: ", ")
sql += ")"
return sql
@@ -660,8 +639,8 @@ struct SQLExpressionCount: SQLExpression {
self.counted = counted
}
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
try "COUNT(" + counted.countedSQL(context) + ")"
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
"COUNT(" + counted.countedSQL(&context) + ")"
}
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
@@ -682,8 +661,8 @@ struct SQLExpressionCountDistinct: SQLExpression {
self.counted = counted
}
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
try "COUNT(DISTINCT " + counted.expressionSQL(context, wrappedInParenthesis: false) + ")"
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
"COUNT(DISTINCT " + counted.expressionSQL(&context, wrappedInParenthesis: false) + ")"
}
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
@@ -710,12 +689,12 @@ struct SQLExpressionIsEmpty: SQLExpression {
SQLExpressionIsEmpty(countExpression, isEmpty: !isEmpty)
}
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
if wrappedInParenthesis {
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
}
return try """
\(countExpression.expressionSQL(context, wrappedInParenthesis: true)) \
return """
\(countExpression.expressionSQL(&context, wrappedInParenthesis: true)) \
\(isEmpty ? "= 0" : "> 0")
"""
}
@@ -731,14 +710,14 @@ struct TableMatchExpression: SQLExpression {
var alias: TableAlias
var pattern: SQLExpression
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
if wrappedInParenthesis {
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
}
return try """
return """
\(context.resolvedName(for: alias).quotedDatabaseIdentifier) \
MATCH \
\(pattern.expressionSQL(context, wrappedInParenthesis: true))
\(pattern.expressionSQL(&context, wrappedInParenthesis: true))
"""
}
@@ -764,12 +743,12 @@ struct SQLExpressionCollate: SQLExpression {
self.collationName = collationName
}
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
if wrappedInParenthesis {
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
}
return try """
\(expression.expressionSQL(context, wrappedInParenthesis: false)) \
return """
\(expression.expressionSQL(&context, wrappedInParenthesis: false)) \
COLLATE \
\(collationName.rawValue)
"""
+4 -32
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: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -41,27 +41,6 @@ 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 {
@@ -104,13 +83,6 @@ 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
@@ -154,11 +126,11 @@ struct SQLExpressionNot: SQLExpression {
self.expression = expression
}
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
if wrappedInParenthesis {
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
}
return try "NOT \(expression.expressionSQL(context, wrappedInParenthesis: true))"
return "NOT \(expression.expressionSQL(&context, wrappedInParenthesis: true))"
}
var negated: SQLExpression {
+3 -21
View File
@@ -298,6 +298,7 @@ public func !== (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQ
SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs.sqlExpression)
}
// MARK: - Comparison Operators (<, >, <=, >=)
extension SQLBinaryOperator {
@@ -474,6 +475,7 @@ public func >= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL
SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
}
// MARK: - Inclusion Operators (BETWEEN, IN)
extension Range where Bound: SQLExpressible {
@@ -539,27 +541,7 @@ 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(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)
SQLExpressionsArray(self).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: SQLGenerationContext) throws -> String
func orderingTermSQL(_ context: inout SQLGenerationContext) -> 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: SQLGenerationContext) throws -> String {
func orderingTermSQL(_ context: inout SQLGenerationContext) -> String {
switch self {
case .asc(let expression):
return try expression.expressionSQL(context, wrappedInParenthesis: false) + " ASC"
return expression.expressionSQL(&context, wrappedInParenthesis: false) + " ASC"
case .desc(let expression):
return try expression.expressionSQL(context, wrappedInParenthesis: false) + " DESC"
return expression.expressionSQL(&context, wrappedInParenthesis: false) + " DESC"
#if GRDBCUSTOMSQLITE
case .ascNullsLast(let expression):
return try expression.expressionSQL(context, wrappedInParenthesis: false) + " ASC NULLS LAST"
return expression.expressionSQL(&context, wrappedInParenthesis: false) + " ASC NULLS LAST"
case .descNullsFirst(let expression):
return try expression.expressionSQL(context, wrappedInParenthesis: false) + " DESC NULLS FIRST"
return expression.expressionSQL(&context, wrappedInParenthesis: false) + " DESC NULLS FIRST"
#endif
}
}
+18 -17
View File
@@ -4,11 +4,12 @@
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 havingExpressionsPromise: DatabasePromise<[SQLExpression]> = DatabasePromise(value: [])
var havingExpressions: [SQLExpression] = []
var limit: SQLLimit?
}
@@ -17,6 +18,10 @@ 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))
}
@@ -29,11 +34,11 @@ extension SQLQuery: Refinable {
}
extension SQLQuery: SelectionRequest {
func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
func select(_ selection: [SQLSelectable]) -> Self {
map(\.relation) { $0.select(selection) }
}
func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
func annotated(with selection: [SQLSelectable]) -> Self {
map(\.relation) { $0.annotated(with: selection) }
}
}
@@ -63,12 +68,8 @@ extension SQLQuery: AggregatingRequest {
with(\.groupPromise, DatabasePromise { db in try expressions(db).map(\.sqlExpression) })
}
func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self {
map(\.havingExpressionsPromise) { havingExpressionsPromise in
DatabasePromise { db in
try havingExpressionsPromise.resolve(db) + [predicate(db).sqlExpression]
}
}
func having(_ predicate: SQLExpressible) -> Self {
mapInto(\.havingExpressions) { $0.append(predicate.sqlExpression) }
}
}
@@ -96,10 +97,11 @@ extension SQLQuery: _JoinableRequest {
extension SQLQuery {
func fetchCount(_ db: Database) throws -> Int {
try QueryInterfaceRequest<Int>(query: countQuery(db)).fetchOne(db)!
let (statement, adapter) = try SQLQueryGenerator(countQuery).prepare(db)
return try Int.fetchOne(statement, adapter: adapter)!
}
private func countQuery(_ db: Database) throws -> SQLQuery {
private var countQuery: SQLQuery {
guard groupPromise == nil && limit == nil else {
// SELECT ... GROUP BY ...
// SELECT ... LIMIT ...
@@ -116,10 +118,9 @@ extension SQLQuery {
return trivialCountQuery
}
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 {
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 {
return trivialCountQuery
}
var countQuery = self.unordered()
@@ -148,8 +149,8 @@ extension SQLQuery {
// SELECT COUNT(*) FROM (self)
private var trivialCountQuery: SQLQuery {
let relation = SQLRelation(
source: .subquery(unordered()),
selectionPromise: DatabasePromise(value: [SQLExpressionCount(AllColumns())]))
source: .query(unordered()),
selection: [SQLExpressionCount(AllColumns())])
return SQLQuery(relation: relation)
}
}
+53 -94
View File
@@ -158,12 +158,15 @@ struct SQLRelation {
}
var source: SQLSource
var selectionPromise: DatabasePromise<[SQLSelectable]> = DatabasePromise(value: [])
var selection: [SQLSelectable] = []
// 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)`.
var filtersPromise: DatabasePromise<[SQLExpression]> = DatabasePromise(value: [])
var ordering: SQLRelation.Ordering = SQLRelation.Ordering()
// If true, the relation refers to the first row only, and we'll need to
// perform explicit limit at the SQL level.
var firstOnly = false
var children: OrderedDictionary<String, Child> = [:]
var prefetchedAssociations: [SQLAssociation] {
@@ -189,8 +192,8 @@ struct SQLRelation {
/// relation as an expression.
func primaryKeyExpression(_ db: Database) throws -> SQLExpression? {
switch source {
case .subquery:
// No primary key for subquery
case .query:
// No primary key for sub query
return nil
case let .table(tableName: tableName, alias: _):
return try db.primaryKeyExpression(tableName)
@@ -199,41 +202,41 @@ struct SQLRelation {
}
extension SQLRelation: Refinable {
func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
with(\.selectionPromise, DatabasePromise(selection))
}
// Convenience
func select(_ selection: [SQLSelectable]) -> Self {
select { _ in selection }
with(\.selection, selection)
}
/// Removes all selections from chidren
func selectOnly(_ selection: [SQLSelectable]) -> Self {
select(selection).map(\.children, { $0.mapValues { $0.map(\.relation, { $0.selectOnly([]) }) } })
self.with(\.selection, 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 {
annotated(with: { _ in selection })
mapInto(\.selection) { $0.append(contentsOf: selection) }
}
func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self {
map(\.filtersPromise) { filtersPromise in
DatabasePromise { db in
try filtersPromise.resolve(db) + [predicate(db).sqlExpression]
filtersPromise.flatMap { filters in
DatabasePromise { try filters + [predicate($0).sqlExpression] }
}
}
}
// Prepending filters for aesthetic reasons
func prependingFilters(_ filters: [SQLExpression]) -> Self {
map(\.filtersPromise) { filtersPromise in
filtersPromise.flatMap { existingFilters in
DatabasePromise { _ in filters + existingFilters }
}
}
}
func unfiltered() -> Self {
with(\.filtersPromise, DatabasePromise(value: []))
}
func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self {
with(\.ordering, SQLRelation.Ordering(orderings: orderings))
}
@@ -403,7 +406,7 @@ extension SQLRelation: _JoinableRequest {
enum SQLSource {
case table(tableName: String, alias: TableAlias?)
indirect case subquery(SQLQuery)
indirect case query(SQLQuery)
func qualified(with alias: TableAlias) -> SQLSource {
switch self {
@@ -415,8 +418,8 @@ enum SQLSource {
alias.setTableName(tableName)
return .table(tableName: tableName, alias: alias)
}
case .subquery:
return self
case let .query(query):
return .query(query.qualified(with: alias))
}
}
}
@@ -584,7 +587,7 @@ struct SQLAssociationCondition: Equatable {
/// - parameter leftAlias: A TableAlias for the table on the left of the
/// JOIN operator.
/// - Returns: An array of SQL expression that should be joined with
/// the AND operator and qualified with the right table.
/// the AND operator.
func expressions(_ db: Database, leftAlias: TableAlias) throws -> [SQLExpression] {
try columnMappings(db).map {
Column($0.right) == QualifiedColumn($0.left, alias: leftAlias)
@@ -596,44 +599,33 @@ struct SQLAssociationCondition: Equatable {
///
/// Given `right.a = left.b`, returns `right.a = 1` or
/// `right.a IN (1, 2, 3)`.
func filteringExpression<Row: ColumnAddressable>(_ db: Database, leftRows: [Row]) throws -> SQLExpression {
guard let firstLeftRow = leftRows.first else {
func filteringExpression(_ db: Database, leftRows: [Row]) throws -> SQLExpression {
if leftRows.isEmpty {
// Degenerate case: there is no row to attach
return false.sqlExpression
}
// The (left, right) column mapping pairs
let columnMappings = try self.columnMappings(db)
// 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 {
guard let columnMapping = columnMappings.first else {
// Degenerate case: no joining column
return true.sqlExpression
}
if mappings.count == 1 {
if columnMappings.count == 1 {
// Join on a single right column.
let rightColumn = Column(columnMapping.right)
// Unique database values and filter out NULL:
let leftIndex = mapping.leftIndex
var dbValues = Set(leftRows.map { $0.databaseValue(at: leftIndex) })
var dbValues = Set(leftRows.map { $0[columnMapping.left] as DatabaseValue })
dbValues.remove(.null)
if dbValues.isEmpty {
return mapping.rightColumn == nil
// Can't join
return false.sqlExpression
} else {
// table.a IN (1, 2, 3, ...)
// Sort database values for nicer output.
return dbValues.sorted(by: <).contains(mapping.rightColumn)
return dbValues.sorted(by: <).contains(rightColumn)
}
} else {
// Join on a multiple columns.
@@ -641,10 +633,11 @@ struct SQLAssociationCondition: Equatable {
return leftRows
.map({ leftRow in
// (table.a = 1) AND (table.b = 2)
mappings
.map({ mapping -> SQLExpression in
let leftValue = leftRow.databaseValue(at: mapping.leftIndex)
return mapping.rightColumn == leftValue
columnMappings
.map({ columns -> SQLExpression in
let rightColumn = Column(columns.right)
let leftValue = leftRow[columns.left] as DatabaseValue
return rightColumn == leftValue
})
.joined(operator: .and)
})
@@ -653,39 +646,6 @@ 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
@@ -704,13 +664,18 @@ extension PersistenceContainer: ColumnAddressable {
extension SQLRelation {
/// Returns nil if relations can't be merged (conflict in source, joins...)
func merged(with other: SQLRelation) -> Self? {
guard firstOnly == other.firstOnly else {
// can't merge
return nil
}
guard let mergedSource = source.merged(with: other.source) else {
// can't merge
return nil
}
let mergedFiltersPromise = DatabasePromise<[SQLExpression]> { db in
try self.filtersPromise.resolve(db) + other.filtersPromise.resolve(db)
let mergedFiltersPromise: DatabasePromise<[SQLExpression]> = filtersPromise.flatMap { filters in
DatabasePromise { try filters + other.filtersPromise.resolve($0) }
}
var mergedChildren: OrderedDictionary<String, SQLRelation.Child> = [:]
@@ -730,23 +695,17 @@ extension SQLRelation {
}
// replace selection unless empty
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
}
}
let mergedSelection = other.selection.isEmpty ? selection : other.selection
// replace ordering unless empty
let mergedOrdering = other.ordering.isEmpty ? ordering : other.ordering
return SQLRelation(
source: mergedSource,
selectionPromise: mergedSelectionPromise,
selection: mergedSelection,
filtersPromise: mergedFiltersPromise,
ordering: mergedOrdering,
firstOnly: firstOnly,
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: SQLGenerationContext) -> String {
public func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
"*"
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func countedSQL(_ context: SQLGenerationContext) -> String {
public func countedSQL(_ context: inout SQLGenerationContext) -> String {
"*"
}
@@ -70,18 +70,35 @@ struct QualifiedAllColumns {
}
extension QualifiedAllColumns: SQLSelectable {
func resultColumnSQL(_ context: SQLGenerationContext) -> String {
func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
if let qualifier = context.qualifier(for: alias) {
return qualifier.quotedDatabaseIdentifier + ".*"
}
return "*"
}
func countedSQL(_ context: SQLGenerationContext) -> String {
if context.qualifier(for: alias) != nil {
// SELECT COUNT(t.*) is invalid SQL
fatalError("Not implemented, or invalid query")
}
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")
// }
return "*"
}
@@ -108,12 +125,12 @@ struct SQLAliasedExpression: SQLSelectable {
self.name = name
}
func resultColumnSQL(_ context: SQLGenerationContext) throws -> String {
try expression.resultColumnSQL(context) + " AS " + name.quotedDatabaseIdentifier
func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
expression.resultColumnSQL(&context) + " AS " + name.quotedDatabaseIdentifier
}
func countedSQL(_ context: SQLGenerationContext) throws -> String {
try expression.countedSQL(context)
func countedSQL(_ context: inout SQLGenerationContext) -> String {
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: SQLGenerationContext) throws -> String
func resultColumnSQL(_ context: inout SQLGenerationContext) -> String
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
func countedSQL(_ context: SQLGenerationContext) throws -> String
func countedSQL(_ context: inout SQLGenerationContext) -> String
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
func count(distinct: Bool) -> SQLCount?
@@ -1,51 +1,54 @@
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// 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.
/// SQLGenerationContext is responsible for preventing SQL injection and
/// disambiguating table names when GRDB generates SQL queries.
///
/// :nodoc:
public struct SQLGenerationContext {
/// 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 }
var arguments: StatementArguments {
_arguments ?? StatementArguments()
}
private var _arguments: StatementArguments?
private var resolvedNames: [TableAlias: String]
private var qualifiesColumnsWithTable: Bool
private var qualifierNeeded: Bool
/// 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
/// 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)
}
/// Returns whether arguments could be appended.
/// May be false for SQLGenerationContext.rawSQLContext
func append(arguments: StatementArguments) -> Bool {
argumentsSink.append(arguments: arguments)
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
}
/// May be nil, when a qualifier is not needed:
@@ -59,7 +62,7 @@ public struct SQLGenerationContext {
if alias.hasUserName {
return alias.identityName
}
if qualifiesColumnsWithTable == false {
if qualifierNeeded == false {
return nil
}
return resolvedName(for: alias)
@@ -80,40 +83,6 @@ 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)
@@ -307,12 +276,6 @@ 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))
@@ -3,18 +3,10 @@ struct SQLQueryGenerator: Refinable {
fileprivate private(set) var relation: SQLQualifiedRelation
private let isDistinct: Bool
private let groupPromise: DatabasePromise<[SQLExpression]>?
private let havingExpressionsPromise: DatabasePromise<[SQLExpression]>
private let havingExpressions: [SQLExpression]
private let limit: SQLLimit?
private let singleResult: Bool
/// 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)
{
init(_ query: SQLQuery) {
// To generate SQL, we need a "qualified" relation, where all tables,
// expressions, etc, are identified with table aliases.
//
@@ -42,97 +34,60 @@ struct SQLQueryGenerator: Refinable {
//
// This turns `GROUP BY id` INTO `GROUP BY book.id`, and
// `HAVING MAX(year) < 2000` INTO `HAVING MAX(book.year) < 2000`.
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
}
let alias = relation.sourceAlias
groupPromise = query.groupPromise?.map { $0.map { $0.qualifiedExpression(with: alias) } }
havingExpressions = query.havingExpressions.map { $0.qualifiedExpression(with: alias) }
limit = query.limit
// Preserve other flags
isDistinct = query.isDistinct
self.singleResult = singleResult
limit = query.limit
}
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)
func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String {
var sql = "SELECT"
if isDistinct {
sql += " DISTINCT"
}
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: ", ")
let selection = relation.selection
GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection")
sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ")
sql += " FROM "
sql += try relation.source.sql(context)
sql += try relation.source.sql(db, &context)
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)
}
for (_, join) in relation.joins {
sql += " "
sql += try join.sql(db, &context, leftAlias: relation.sourceAlias)
}
let filters = try relation.filtersPromise.resolve(context.db)
let filters = try relation.filtersPromise.resolve(db)
if filters.isEmpty == false {
sql += " WHERE "
sql += try filters.joined(operator: .and).expressionSQL(context, wrappedInParenthesis: false)
sql += filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false)
}
let groupExpressions = try groupPromise?.resolve(context.db) ?? []
if !groupExpressions.isEmpty {
if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty {
sql += " GROUP BY "
sql += try groupExpressions
.map { try $0.expressionSQL(context, wrappedInParenthesis: false) }
sql += groupExpressions
.map { $0.expressionSQL(&context, wrappedInParenthesis: false) }
.joined(separator: ", ")
}
let havingExpressions = try havingExpressionsPromise.resolve(context.db)
if havingExpressions.isEmpty == false {
sql += " HAVING "
sql += try havingExpressions.joined(operator: .and).expressionSQL(context, wrappedInParenthesis: false)
sql += havingExpressions.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false)
}
let orderings = try relation.ordering.resolve(context.db)
let orderings = try relation.ordering.resolve(db)
if !orderings.isEmpty {
sql += " ORDER BY "
sql += try orderings
.map { try $0.orderingTermSQL(context) }
sql += orderings
.map { $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
@@ -141,11 +96,6 @@ struct SQLQueryGenerator: Refinable {
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))
}
@@ -176,102 +126,6 @@ struct SQLQueryGenerator: Refinable {
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:
@@ -284,22 +138,19 @@ struct SQLQueryGenerator: Refinable {
return try makeTrivialDeleteStatement(db)
}
let context = SQLGenerationContext(db, aliases: relation.allAliases)
var context = SQLGenerationContext.queryContext(aliases: relation.allAliases)
var sql = try "DELETE FROM " + relation.source.sql(context)
var sql = try "DELETE FROM " + relation.source.sql(db, &context)
let filters = try relation.filtersPromise.resolve(db)
if filters.isEmpty == false {
sql += " WHERE "
sql += try filters
.joined(operator: .and)
.expressionSQL(context, wrappedInParenthesis: false)
sql += " WHERE " + filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false)
}
if let limit = limit {
let orderings = try relation.ordering.resolve(db)
if !orderings.isEmpty {
sql += try " ORDER BY " + orderings.map { try $0.orderingTermSQL(context) }.joined(separator: ", ")
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ")
}
sql += " LIMIT " + limit.sql
}
@@ -324,13 +175,13 @@ struct SQLQueryGenerator: Refinable {
fatalError("Can't delete without any database table")
}
let context = SQLGenerationContext(db)
var context = SQLGenerationContext.queryContext(aliases: relation.allAliases)
let primaryKey = try db.primaryKeyExpression(tableName)
var sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE "
sql += try primaryKey.expressionSQL(context, wrappedInParenthesis: false)
sql += primaryKey.expressionSQL(&context, wrappedInParenthesis: false)
sql += " IN ("
sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).sql(db, argumentsSink: context.argumentsSink)
sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).sql(db, &context)
sql += ")"
let statement = try db.makeUpdateStatement(sql: sql)
@@ -365,7 +216,7 @@ struct SQLQueryGenerator: Refinable {
return nil
}
let context = SQLGenerationContext(db, aliases: relation.allAliases)
var context = SQLGenerationContext.queryContext(aliases: relation.allAliases)
var sql = "UPDATE "
@@ -373,25 +224,22 @@ struct SQLQueryGenerator: Refinable {
sql += "OR \(conflictResolution.rawValue) "
}
sql += try relation.source.sql(context)
sql += try relation.source.sql(db, &context)
let assignmentsSQL = try assignments
.map { try $0.sql(context) }
let assignmentsSQL = assignments
.map { $0.sql(&context) }
.joined(separator: ", ")
sql += " SET " + assignmentsSQL
let filters = try relation.filtersPromise.resolve(db)
if filters.isEmpty == false {
sql += " WHERE "
sql += try filters
.joined(operator: .and)
.expressionSQL(context, wrappedInParenthesis: false)
sql += " WHERE " + filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false)
}
if let limit = limit {
let orderings = try relation.ordering.resolve(db)
if !orderings.isEmpty {
sql += try " ORDER BY " + orderings.map { try $0.orderingTermSQL(context) }.joined(separator: ", ")
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ")
}
sql += " LIMIT " + limit.sql
}
@@ -428,7 +276,7 @@ struct SQLQueryGenerator: Refinable {
return nil
}
let context = SQLGenerationContext(db)
var context = SQLGenerationContext.queryContext(aliases: relation.allAliases)
let primaryKey = try db.primaryKeyExpression(tableName)
// UPDATE table...
@@ -439,16 +287,16 @@ struct SQLQueryGenerator: Refinable {
sql += tableName.quotedDatabaseIdentifier
// SET column = value...
let assignmentsSQL = try assignments
.map { try $0.sql(context) }
let assignmentsSQL = assignments
.map { $0.sql(&context) }
.joined(separator: ", ")
sql += " SET " + assignmentsSQL
// WHERE id IN (SELECT id FROM ...)
// WHERE id IN (SELECT rowid FROM ...)
sql += " WHERE "
sql += try primaryKey.expressionSQL(context, wrappedInParenthesis: false)
sql += primaryKey.expressionSQL(&context, wrappedInParenthesis: false)
sql += " IN ("
sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).sql(db, argumentsSink: context.argumentsSink)
sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).sql(db, &context)
sql += ")"
let statement = try db.makeUpdateStatement(sql: sql)
@@ -458,13 +306,17 @@ struct SQLQueryGenerator: Refinable {
/// Returns a select statement
func makeSelectStatement(_ db: Database) throws -> SelectStatement {
// Build
let argumentsSink = StatementArgumentsSink()
let sql = try self.sql(db, argumentsSink: argumentsSink)
// Build an SQK generation context with all aliases found in the query,
// so that we can disambiguate tables that are used several times with
// SQL aliases.
var context = SQLGenerationContext.queryContext(aliases: relation.allAliases)
// Generate SQL
let sql = try self.sql(db, &context)
// Compile & set arguments
let statement = try db.makeSelectStatement(sql: sql)
statement.arguments = argumentsSink.arguments
statement.arguments = context.arguments
// Optimize databaseRegion
statement.selectedRegion = try optimizedSelectedRegion(db, statement.selectedRegion)
@@ -559,11 +411,14 @@ struct SQLQueryGenerator: Refinable {
/// | | | • filterPromise
/// | | • joins
/// | • source
/// • selectionPromise
/// • selection
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.alias].compactMap { $0 }) {
joins.reduce(into: source.allAliases) {
$0.append(contentsOf: $1.value.relation.allAliases)
}
}
@@ -576,20 +431,16 @@ private struct SQLQualifiedRelation {
let source: SQLQualifiedSource
/// The selection from source, not including selection of joined relations
private var sourceSelectionPromise: DatabasePromise<[SQLSelectable]>
private var sourceSelection: [SQLSelectable]
/// The full selection, including selection of joined relations
///
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • 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)
}
/// • selection
var selection: [SQLSelectable] {
joins.reduce(into: sourceSelection) {
$0.append(contentsOf: $1.value.relation.selection)
}
}
@@ -628,23 +479,14 @@ 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 { SQLQualifiedJoin($0) }
if let sourceAlias = source.alias {
sourceSelectionPromise = relation.selectionPromise.map {
$0.map { $0.qualifiedSelectable(with: sourceAlias) }
}
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(_:)
@@ -665,7 +507,7 @@ private struct SQLQualifiedRelation {
// The number of columns in source selection. Columns selected by joined
// relations are appended after.
let sourceSelectionWidth = try sourceSelectionPromise.resolve(db).reduce(0) {
let sourceSelectionWidth = try sourceSelection.reduce(0) {
try $0 + $1.columnCount(db)
}
@@ -709,14 +551,7 @@ private struct SQLQualifiedRelation {
/// Removes all selections from joins
func selectOnly(_ selection: [SQLSelectable]) -> Self {
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)
self.with(\.sourceSelection, selection.map { $0.qualifiedSelectable(with: sourceAlias) })
.map(\.joins, { $0.mapValues { $0.selectOnly([]) } })
}
}
@@ -726,24 +561,23 @@ 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 subquery(SQLQueryGenerator)
indirect case query(SQLQueryGenerator)
/// 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? {
var alias: TableAlias {
switch self {
case let .table(_, alias):
case .table(_, let alias):
return alias
case .subquery:
return nil
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
}
}
@@ -752,12 +586,12 @@ private enum SQLQualifiedSource {
case let .table(tableName, alias):
let alias = alias ?? TableAlias(tableName: tableName)
self = .table(tableName: tableName, alias: alias)
case let .subquery(subquery):
self = .subquery(SQLQueryGenerator(query: subquery))
case let .query(query):
self = .query(SQLQueryGenerator(query))
}
}
func sql(_ context: SQLGenerationContext) throws -> String {
func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String {
switch self {
case let .table(tableName, alias):
if let aliasName = context.aliasName(for: alias) {
@@ -765,9 +599,8 @@ private enum SQLQualifiedSource {
} else {
return "\(tableName.quotedDatabaseIdentifier)"
}
case let .subquery(generator):
let sql = try generator.sql(context)
return "(\(sql))"
case let .query(query):
return try "(\(query.sql(db, &context)))"
}
}
}
@@ -791,9 +624,15 @@ private struct SQLQualifiedJoin: Refinable {
}
}
enum Target {
case all
case first(SQLRelation)
}
var kind: Kind
var condition: SQLAssociationCondition
var relation: SQLQualifiedRelation
var target: Target
init?(_ child: SQLRelation.Child) {
guard let kind = Kind(child.kind) else {
@@ -801,25 +640,53 @@ private struct SQLQualifiedJoin: Refinable {
}
self.kind = kind
self.condition = child.condition
self.relation = SQLQualifiedRelation(child.relation)
// Remove non-joined grand children
let relation = child.relation.filteringChildren { Kind($0.kind) != nil }
if relation.firstOnly {
// Split relation into an "outer" relation exposed to the rest of
// the query, and a "subRelation", private to the join, limited
// to a single row:
//
// v--- outer relation
// JOIN child ON id = (SELECT id FROM child ... LIMIT 1)
// ^--- subRelation
//
// Outer relation has no filter or ordering: those are handled
// by the subRelation.
let outerRelation = relation
.with(\.firstOnly, false)
.unfiltered()
.unordered()
self.relation = SQLQualifiedRelation(outerRelation)
self.target = .first(relation)
} else {
self.relation = SQLQualifiedRelation(relation)
self.target = .all
}
}
func sql(_ context: SQLGenerationContext, leftAlias: TableAlias) throws -> String {
try sql(context, leftAlias: leftAlias, allowingInnerJoin: true)
func sql(_ db: Database, _ context: inout SQLGenerationContext, leftAlias: TableAlias) throws -> String {
try sql(db, &context, leftAlias: leftAlias, allowingInnerJoin: true)
}
/// Removes all selections from joins
func selectOnly(_ selection: [SQLSelectable]) -> SQLQualifiedJoin {
func selectOnly(_ selection: [SQLSelectable]) -> Self {
map(\.relation) { $0.selectOnly(selection) }
}
private func sql(
_ context: SQLGenerationContext,
_ db: Database,
_ context: inout SQLGenerationContext,
leftAlias: TableAlias,
allowingInnerJoin allowsInnerJoin: Bool)
throws -> String
{
var allowsInnerJoin = allowsInnerJoin
var sql = ""
switch self.kind {
case .innerJoin:
@@ -836,28 +703,45 @@ private struct SQLQualifiedJoin: Refinable {
}
// 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")
}
sql += try "\(kind.rawValue) \(relation.source.sql(db, &context))"
// ... 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 {
let filterSQL = try filters
.joined(operator: .and)
.qualifiedExpression(with: rightAlias)
.expressionSQL(context, wrappedInParenthesis: false)
sql += " ON \(filterSQL)"
let rightAlias = relation.sourceAlias
switch target {
case .all:
// ... ON <join conditions> AND <other filters>
var filters = try condition.expressions(db, leftAlias: leftAlias)
filters += try relation.filtersPromise.resolve(db)
if filters.isEmpty == false {
let filterSQL = filters
.joined(operator: .and)
.qualifiedExpression(with: rightAlias)
.expressionSQL(&context, wrappedInParenthesis: false)
sql += " ON \(filterSQL)"
}
case var .first(subRelation):
// Subquery: SELECT id ...
guard let primaryKey = try subRelation.primaryKeyExpression(db) else {
fatalError("Not implemented: support for WITHOUT ROWID optimization")
}
subRelation = subRelation.selectOnly([primaryKey])
// Subquery: ... WHERE <condition filters> AND <other filters>
let filters = try condition.expressions(db, leftAlias: leftAlias)
subRelation = subRelation.prependingFilters(filters)
// Subquery: ... LIMIT 1
let subQuery = SQLQuery(relation: subRelation, limit: SQLLimit(limit: 1, offset: nil))
// ... ON id = (SELECT id FROM table WHERE <condition filters> AND <other filters> LIMIT 1)
sql += " ON "
sql += rightAlias[primaryKey].expressionSQL(&context, wrappedInParenthesis: false)
sql += " = ("
sql += try SQLQueryGenerator(subQuery).sql(db, &context)
sql += ")"
}
for (_, join) in relation.joins {
// Right becomes left as we dig further
sql += try " \(join.sql(context, leftAlias: rightAlias, allowingInnerJoin: allowsInnerJoin))"
sql += try " \(join.sql(db, &context, leftAlias: rightAlias, allowingInnerJoin: allowsInnerJoin))"
}
return sql
@@ -17,22 +17,6 @@ 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
@@ -163,27 +147,14 @@ extension SQLInterpolation {
elements.append(.orderingTerm(ordering))
}
/// Appends the request SQL (not wrapped inside parentheses).
/// Appends the request SQL, wrapped in parentheses
///
/// // SELECT name FROM player WHERE score = (SELECT MAX(score) FROM player)
/// let subQuery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE score = (\(subQuery))
/// SELECT * FROM player WHERE score = \(subQuery)
/// """
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)
})
public mutating func appendInterpolation<T>(_ request: SQLRequest<T>) {
elements.append(.subQuery(request.sqlLiteral))
}
}
@@ -115,7 +115,7 @@ extension Database {
unique: unique,
ifNotExists: ifNotExists,
condition: condition?.sqlExpression)
let sql = try definition.sql(self)
let sql = definition.sql()
try execute(sql: sql)
}
@@ -457,7 +457,7 @@ public final class TableDefinition {
for checkExpression in checkConstraints {
var chunks: [String] = []
try chunks.append("CHECK (\(checkExpression.quotedSQL(db)))")
chunks.append("CHECK (\(checkExpression.quotedSQL()))")
items.append(chunks.joined(separator: " "))
}
@@ -470,9 +470,9 @@ public final class TableDefinition {
statements.append(chunks.joined(separator: " "))
}
let indexStatements = try columns
let indexStatements = columns
.compactMap { $0.indexDefinition(in: name) }
.map { try $0.sql(db) }
.map { $0.sql() }
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) {
try statements.append(indexDefinition.sql(db))
statements.append(indexDefinition.sql())
}
case let .rename(oldName, newName):
var chunks: [String] = []
@@ -884,11 +884,11 @@ public final class ColumnDefinition {
}
for checkConstraint in checkConstraints {
try chunks.append("CHECK (\(checkConstraint.quotedSQL(db)))")
chunks.append("CHECK (\(checkConstraint.quotedSQL()))")
}
if let defaultExpression = defaultExpression {
try chunks.append("DEFAULT \(defaultExpression.quotedSQL(db))")
chunks.append("DEFAULT \(defaultExpression.quotedSQL())")
}
if let collationName = collationName {
@@ -958,7 +958,7 @@ private struct IndexDefinition {
let ifNotExists: Bool
let condition: SQLExpression?
func sql(_ db: Database) throws -> String {
func sql() -> String {
var chunks: [String] = []
chunks.append("CREATE")
if unique {
@@ -976,7 +976,7 @@ private struct IndexDefinition {
)
""")
if let condition = condition {
try chunks.append("WHERE \(condition.quotedSQL(db))")
chunks.append("WHERE \(condition.quotedSQL())")
}
return chunks.joined(separator: " ")
}
@@ -487,9 +487,23 @@ extension TableRecord where Self: EncodableRecord {
where A.OriginRowDecoder == Self
{
let destinationRelation = association.sqlAssociation.destinationRelation(fromOriginRows: { db in
try [PersistenceContainer(db, self)]
try [Row(PersistenceContainer(db, self))]
})
return QueryInterfaceRequest(relation: destinationRelation)
let request = QueryInterfaceRequest<A.RowDecoder>(relation: destinationRelation)
// Deal with "firstOnly" relations
guard let firstOnlyIndex = association.sqlAssociation.steps.firstIndex(where: { $0.relation.firstOnly }) else {
return request
}
if
let toManyIndex = association.sqlAssociation.steps.lastIndex(where: { !$0.isSingular }),
toManyIndex > firstOnlyIndex
{
fatalError("Not implemented: loading multiple records associated to a `first` or `last` to-one association")
}
return request.limit(1)
}
}
@@ -547,29 +561,32 @@ extension TableRecord {
// MARK: - Association Aggregates
// TODO: replace rowid with actual primary key in the doc when implemented
/// Creates a request with *aggregates* appended to the selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
/// // SELECT player.*, COUNT(DISTINCT book.rowid) 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> {
all().annotated(with: aggregates)
}
// TODO: replace rowid with actual primary key in the doc when implemented
/// Creates a request with *aggregates* appended to the selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
/// // SELECT player.*, COUNT(DISTINCT book.rowid) 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> {
all().annotated(with: aggregates)
}
// TODO: replace rowid with actual primary key in the doc when implemented
/// Creates a request with the provided aggregate *predicate*.
///
/// // SELECT player.*
/// // FROM player LEFT JOIN book ...
/// // HAVING COUNT(DISTINCT book.id) = 0
/// // HAVING COUNT(DISTINCT book.rowid) = 0
/// var request = Player.all()
/// request = request.having(Player.books.isEmpty)
///
@@ -2,12 +2,6 @@ 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
@@ -17,7 +11,10 @@ extension TableRecord {
/// all requests by the `TableRecord.databaseSelection` property, or
/// for individual requests with the `TableRecord.select` method.
public static func all() -> QueryInterfaceRequest<Self> {
QueryInterfaceRequest(relation: relationForAll)
let relation = SQLRelation(
source: .table(tableName: databaseTableName, alias: nil),
selection: databaseSelection)
return QueryInterfaceRequest(relation: relation)
}
/// Creates a request which fetches no record.
+15 -18
View File
@@ -45,7 +45,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
throw DecodingError.keyNotFound(
codingKey,
DecodingError.Context(
codingPath: Array(codingPath.dropLast()),
codingPath: Array(codingPath.dropLast()), // TODO: remove Array initializer when Swift >= 5
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(forColumn: key.stringValue) else {
guard let index = row.index(ofColumn: key.stringValue) else {
// Don't use DecodingError.keyNotFound:
// We need to specifically recognize missing columns in order to
// provide correct feedback.
@@ -73,24 +73,20 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
self.decoder = decoder
}
lazy var allKeys: [Key] = {
var allKeys: [Key] {
let row = decoder.row
return Set(row.columnNames)
.union(row.scopesTree.names)
.union(row.prefetchedRows.keys)
.compactMap(Key.init(stringValue:))
}()
.union(Set(row.scopesTree.names))
.union(Set(row.prefetchedRows.keys))
.compactMap { Key(stringValue: $0) }
}
func contains(_ key: Key) -> Bool {
let row = decoder.row
return row.hasColumn(key.stringValue)
|| (row.scopesTree[key.stringValue] != nil)
|| (row.prefetchedRows[key.stringValue] != nil)
return row.hasColumn(key.stringValue) || (row.scopesTree[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)
}
@@ -117,7 +113,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
let keyName = key.stringValue
// Column?
if let index = row.index(forColumn: keyName) {
if let index = row.index(ofColumn: keyName) {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
if type == Date.self {
@@ -147,7 +143,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
let keyName = key.stringValue
// Column?
if let index = row.index(forColumn: keyName) {
if let index = row.index(ofColumn: keyName) {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
if type == Date.self {
@@ -200,14 +196,15 @@ 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)"))
} else {
decodedRootKey = key
return try decode(type, fromRow: row, codingPath: codingPath + [key])
debugDescription: "No such key: \(decodedRootKey.stringValue)")) // TODO: better error message
}
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,6 +114,28 @@ 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:
+12
View File
@@ -107,6 +107,10 @@
5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */; };
564B3D72239BDBD6007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */; };
564B3D73239BDBD6007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */; };
564C2456244A44F8003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C2454244A44F7003D7B05 /* AssociationHasManyFirstSQLTests.swift */; };
564C2457244A44F8003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C2454244A44F7003D7B05 /* AssociationHasManyFirstSQLTests.swift */; };
564C245E244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C245D244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */; };
564C245F244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C245D244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */; };
564CE43C21AA955B00652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueObserver.swift */; };
564CE43D21AA955B00652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueObserver.swift */; };
564CE4E321B2E05400652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */; };
@@ -787,6 +791,8 @@
5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = "<group>"; };
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
564C2454244A44F7003D7B05 /* AssociationHasManyFirstSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyFirstSQLTests.swift; sourceTree = "<group>"; };
564C245D244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughFirstSQLTests.swift; sourceTree = "<group>"; };
564CE43B21AA955B00652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = "<group>"; };
564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = "<group>"; };
564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = "<group>"; };
@@ -1339,9 +1345,11 @@
5653EB6220961FB200F46237 /* AssociationBelongsToSQLTests.swift */,
5653EB6020961FB100F46237 /* AssociationChainRowScopesTests.swift */,
5653EB6320961FB200F46237 /* AssociationChainSQLTests.swift */,
564C2454244A44F7003D7B05 /* AssociationHasManyFirstSQLTests.swift */,
561CFA9F2376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift */,
56057C572291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift */,
56959635222D058B002CB7C9 /* AssociationHasManySQLTests.swift */,
564C245D244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */,
561CFAA32376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift */,
56057C642291C7E500A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */,
5695961E222C4589002CB7C9 /* AssociationHasManyThroughSQLTests.swift */,
@@ -2341,6 +2349,7 @@
F3BA80AF1CFB2FB1003DC1BA /* DatabaseCollationTests.swift in Sources */,
56CC9235201E009100CB597E /* DropWhileCursorTests.swift in Sources */,
567E4209242AB3CB00CAAD2C /* FailableTestCase.swift in Sources */,
564C245F244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */,
56D507651F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */,
5615B286222B17BA00061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
5657AB651D108BA9006283EF /* FoundationNSURLTests.swift in Sources */,
@@ -2398,6 +2407,7 @@
F3BA80D61CFB2FFD003DC1BA /* DatabaseReaderTests.swift in Sources */,
5653EB7520961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
5691578D231BF2BE00E1D237 /* PoolTests.swift in Sources */,
564C2457244A44F8003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */,
5698AC9D1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */,
5665FA3E2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
56677C28241E6EA20050755D /* ValueObservationRecorder.swift in Sources */,
@@ -2676,6 +2686,7 @@
56B964DB1DA5216B0002DA19 /* FTS5RecordTests.swift in Sources */,
56CC9234201E009000CB597E /* DropWhileCursorTests.swift in Sources */,
567E420A242AB3CB00CAAD2C /* FailableTestCase.swift in Sources */,
564C245E244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */,
56D507611F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */,
5615B285222B17BA00061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
F3BA80B01CFB2FB2003DC1BA /* DatabaseCollationTests.swift in Sources */,
@@ -2733,6 +2744,7 @@
F3BA81321CFB3064003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */,
5653EB7420961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
5691578E231BF2BE00E1D237 /* PoolTests.swift in Sources */,
564C2456244A44F8003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */,
5623935A1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
5665FA3D2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
56677C27241E6EA20050755D /* ValueObservationRecorder.swift in Sources */,
+5 -9
View File
@@ -52,12 +52,8 @@ TEST_ACTIONS = clean build build-for-testing test-without-building
ifeq ($(XCODEVERSION),11.4)
MAX_SWIFT_VERSION = 5.2
MIN_SWIFT_VERSION = # MAX_SWIFT_VERSION is the minimum supported Swift version
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_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=13.4"
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5,OS=10.3.1"
MAX_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
@@ -391,10 +387,10 @@ ifdef JAZZY
--author 'Gwendal Roué' \
--author_url https://github.com/groue \
--github_url https://github.com/groue/GRDB.swift \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.0.0-beta \
--module-version 5.0.0-beta \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v4.14.0 \
--module-version 4.14.0 \
--module GRDB \
--root-url http://groue.github.io/GRDB.swift/docs/5.0.0-beta/ \
--root-url http://groue.github.io/GRDB.swift/docs/4.14/ \
--output Documentation/Reference \
--xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS
else
+310 -112
View File
@@ -11,13 +11,13 @@
---
**Latest release**: May 2, 2020 • version 5.0.0-beta • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
**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)
**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** | **v5.0.0-beta**, [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0)|
| **Swift 5.2** | [GRDB5 branch](https://github.com/groue/GRDB.swift/tree/GRDB5) |
| 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]: Transform your database as your application evolves.
- [Migrations](#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/5.0.0-beta/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/4.14/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
#### Getting Started
@@ -282,7 +282,7 @@ Documentation
#### Application Tools
- [Migrations]: Transform your database as your application evolves.
- [Migrations](#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 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
- :bulb: [Migrating From GRDB 3 to GRDB 4](Documentation/GRDB3MigrationGuide.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/5.0.0-beta/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/4.14/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/5.0.0-beta/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/4.14/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/5.0.0-beta/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/4.14/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/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`:
- **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`:
```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/5.0.0-beta/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/4.14/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/5.0.0-beta/Structs/StatementArguments.html):
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/4.14/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/5.0.0-beta/Structs/Configuration.html) configuration flag:
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:
```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/5.0.0-beta/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/4.14/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/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.
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.
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/5.0.0-beta/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/4.14/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/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.
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.
> :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](Documentation/Migrations.md#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](#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.id) AS playerCount
// SELECT team.*, COUNT(DISTINCT player.rowid) 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.id) >= 5
// HAVING COUNT(DISTINCT player.rowid) >= 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/5.0.0-beta/Structs/StatementArguments.html):
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/4.14/Structs/StatementArguments.html):
```swift
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
@@ -4258,18 +4258,6 @@ 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.
- `*`, `/`, `+`, `-`
@@ -4365,18 +4353,6 @@ 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`
@@ -4823,7 +4799,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/5.0.0-beta/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example:
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/4.14/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example:
```swift
extension Player {
@@ -4866,7 +4842,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/5.0.0-beta/Structs/AnyFetchRequest.html): a [type-erased](http://chris.eidhof.nl/post/type-erasers-in-swift/) request.
- [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.
### Fetching From Custom Requests
@@ -4898,6 +4874,132 @@ 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.**
@@ -4946,6 +5048,7 @@ 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)
@@ -5068,22 +5171,21 @@ extension PlayerInfo: FetchableRecord {
}
```
Now we write a method that returns a [custom request](#custom-requests), and then build the fetching method on top of that request:
Let's now write the method that fetches PlayerInfo records:
```swift
extension PlayerInfo {
/// The request for all player infos
static func all() -> AdaptedFetchRequest<SQLRequest<PlayerInfo>> {
static func fetchAll(_ db: Database) throws -> [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 request: SQLRequest<PlayerInfo> = """
let sql = """
SELECT
\(columnsOf: Player.self), -- instead of player.*
\(columnsOf: Team.self), -- instead of team.*
\(Player.selectionSQL()), -- instead of player.*
\(Team.selectionSQL()), -- instead of team.*
MAX(round.score) AS maxScore
FROM player
LEFT JOIN team ON ...
@@ -5092,34 +5194,41 @@ To acknowledge that both Player and Team records may customize their selection o
"""
```
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).
`Player.selectionSQL()` will output `player.*`, unless Player defines a [customized selection](#columns-selected-by-a-request).
Now we need to build adapters.
> :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 ...
> """
> ```
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.
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:
```swift
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]])
}
}
let adapters = try splittingRowAdapters(columnCounts: [
Player.numberOfSelectedColumns(db),
Team.numberOfSelectedColumns(db)])
let adapter = 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 define the fetching method:
And finally, we can fetch player infos:
```swift
/// Fetches all player infos
static func fetchAll(_ db: Database) throws -> [PlayerInfo] {
try all().fetchAll(db)
return try PlayerInfo.fetchAll(db, sql: sql, adapter: adapter)
}
}
```
@@ -5137,16 +5246,95 @@ 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 [SQL Interpolation] and `numberOfSelectedColumns` in order to deal with nested record types that define custom selection.
> - how to use `selectionSQL` 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-record-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-request-way) sample code:
```swift
struct Player: Decodable, FetchableRecord, TableRecord {
@@ -5167,17 +5355,17 @@ struct PlayerInfo: Decodable, FetchableRecord {
extension PlayerInfo {
/// The request for all player infos
static func all() -> AdaptedFetchRequest<SQLRequest<PlayerInfo>> {
let request: SQLRequest<PlayerInfo> = """
let sql = """
SELECT
\(columnsOf: Player.self),
\(columnsOf: Team.self),
\(Player.selectionSQL()),
\(Team.selectionSQL()),
MAX(round.score) AS maxScore
FROM player
LEFT JOIN team ON ...
LEFT JOIN round ON ...
GROUP BY ...
"""
return request.adapted { db in
return SQLRequest<PlayerInfo>(sql: sql).adapted { db in
let adapters = try splittingRowAdapters(columnCounts: [
Player.numberOfSelectedColumns(db),
Team.numberOfSelectedColumns(db)])
@@ -5197,6 +5385,13 @@ 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.
@@ -5400,7 +5595,7 @@ import RxSwift
let observation = ValueObservation.tracking(Player.fetchAll)
let disposable = observation.rx.observe(in: dbQueue).subscribe(
let disposable = observation.rx.changes(in: dbQueue).subscribe(
onNext: { (players: [Player]) in
print("fresh players", players)
},
@@ -5635,7 +5830,7 @@ When needed, you can help GRDB optimize observations and reduce database content
let observation = ValueObservation.tracking(Player.fetchAll)
let observable = observation.rx
.observe(in: dbQueue)
.changes(in: dbQueue)
.share(replay: 1, scope: .whileConnected)
```
@@ -6002,7 +6197,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan
### DatabaseRegion
**[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)**.
**[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)**.
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.
@@ -6012,7 +6207,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/5.0.0-beta/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/4.14/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
#### The DatabaseRegionConvertible Protocol
@@ -7107,11 +7302,11 @@ try snapshot2.read { db in
### DatabaseWriter and DatabaseReader Protocols
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.
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.
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]
@@ -7646,18 +7841,23 @@ 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 compile the request into a prepared statement:
You can turn your request into a `SQLRequest` instance:
```swift
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"]
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"]
}
```
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:
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:
```swift
var config = Configuration()
@@ -7665,8 +7865,11 @@ config.trace = { print($0) } // Prints all SQL statements
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
try dbQueue.read { db in
let players = try Player.filter(Column("name") == "O'Brien").fetchAll(db)
// Prints SELECT * FROM player WHERE name = 'O''Brien'
let wines = Wine
.filter(originColumn == "Burgundy")
.order(priceColumn)
.fetchAll(db)
// Prints SELECT * FROM wine WHERE origin = 'Burgundy' ORDER BY price
}
```
@@ -7789,30 +7992,10 @@ 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.
@@ -7825,6 +8008,22 @@ 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].
@@ -7839,7 +8038,6 @@ 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>5.0.0-beta</string>
<string>4.14.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+8 -2
View File
@@ -6,22 +6,28 @@
- [ ] 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 (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()
- [ ] 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
- [ ] 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 customPrimaryKey: Int64
var id: 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("customPrimaryKey", .integer).primaryKey()
t.column("id", .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(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 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 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(customPrimaryKey: 4, teamId: 2, name: "European cup 2036").insert(db)
try Award(id: 4, teamId: 2, name: "European cup 2036").insert(db)
try Team(id: 3, name: "Greens").insert(db)
try Award(customPrimaryKey: 5, teamId: 3, name: "World cup 2037").insert(db)
try Award(id: 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"."id") AS "playerCount" \
SELECT "team".*, COUNT(DISTINCT "custom"."rowid") 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"."id") AS "playerCount" \
SELECT "team"."name", COUNT(DISTINCT "player"."rowid") 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"."id") AS "playerCount" \
SELECT "team".*, COUNT(DISTINCT "player"."rowid") 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"."customPrimaryKey") AS "awardCount" \
SELECT "player".*, COUNT(DISTINCT "award"."rowid") 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"."id") AS "playerCount", \
COUNT(DISTINCT "player"."rowid") 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"."id") AS "customPlayerCount" \
SELECT "team".*, COUNT(DISTINCT "player"."rowid") 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"."id") AS "customPlayerCount", \
COUNT(DISTINCT "player"."rowid") 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"."id") AS "a2", \
COUNT(DISTINCT "player"."rowid") 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"."id") AS "lowPlayerCount", \
COUNT(DISTINCT "player2"."id") AS "highPlayerCount" \
COUNT(DISTINCT "player1"."rowid") AS "lowPlayerCount", \
COUNT(DISTINCT "player2"."rowid") 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"."id") = 0 AS "hasNoPlayer" \
SELECT "team".*, COUNT(DISTINCT "player"."rowid") = 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"."id") > 0 \
SELECT "team".*, COUNT(DISTINCT "player"."rowid") > 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"."id") = 0
HAVING COUNT(DISTINCT "player"."rowid") = 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"."id") > 0
HAVING COUNT(DISTINCT "player"."rowid") > 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"."id") > 0
HAVING COUNT(DISTINCT "player"."rowid") > 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"."id") = 0
HAVING COUNT(DISTINCT "player"."rowid") = 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"."customPrimaryKey") = 0
HAVING COUNT(DISTINCT "award"."rowid") = 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"."customPrimaryKey") > 0
HAVING COUNT(DISTINCT "award"."rowid") > 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"."customPrimaryKey") > 0
HAVING COUNT(DISTINCT "award"."rowid") > 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"."customPrimaryKey") = 0
HAVING COUNT(DISTINCT "award"."rowid") = 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"."id") = 2
HAVING COUNT(DISTINCT "player"."rowid") = 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"."id")
HAVING 2 = COUNT(DISTINCT "player"."rowid")
""")
}
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"."id") = COUNT(DISTINCT "award"."customPrimaryKey")
HAVING COUNT(DISTINCT "player"."rowid") = COUNT(DISTINCT "award"."rowid")
""")
}
}
@@ -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"."id") <> 2
HAVING COUNT(DISTINCT "player"."rowid") <> 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"."id")
HAVING 2 <> COUNT(DISTINCT "player"."rowid")
""")
}
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"."id") <> COUNT(DISTINCT "award"."customPrimaryKey")
HAVING COUNT(DISTINCT "player"."rowid") <> COUNT(DISTINCT "award"."rowid")
""")
}
}
@@ -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"."id") >= 2
HAVING COUNT(DISTINCT "player"."rowid") >= 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"."id")
HAVING 2 >= COUNT(DISTINCT "player"."rowid")
""")
}
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"."id") >= COUNT(DISTINCT "award"."customPrimaryKey")
HAVING COUNT(DISTINCT "player"."rowid") >= COUNT(DISTINCT "award"."rowid")
""")
}
}
@@ -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"."id") > 2
HAVING COUNT(DISTINCT "player"."rowid") > 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"."id")
HAVING 2 > COUNT(DISTINCT "player"."rowid")
""")
}
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"."id") > COUNT(DISTINCT "award"."customPrimaryKey")
HAVING COUNT(DISTINCT "player"."rowid") > COUNT(DISTINCT "award"."rowid")
""")
}
}
@@ -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"."id") <= 2
HAVING COUNT(DISTINCT "player"."rowid") <= 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"."id")
HAVING 2 <= COUNT(DISTINCT "player"."rowid")
""")
}
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"."id") <= COUNT(DISTINCT "award"."customPrimaryKey")
HAVING COUNT(DISTINCT "player"."rowid") <= COUNT(DISTINCT "award"."rowid")
""")
}
}
@@ -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"."id") < 2
HAVING COUNT(DISTINCT "player"."rowid") < 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"."id")
HAVING 2 < COUNT(DISTINCT "player"."rowid")
""")
}
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"."id") < COUNT(DISTINCT "award"."customPrimaryKey")
HAVING COUNT(DISTINCT "player"."rowid") < COUNT(DISTINCT "award"."rowid")
""")
}
}
@@ -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"."id") = 0) AND (COUNT(DISTINCT "award"."customPrimaryKey") = 0)
HAVING (COUNT(DISTINCT "player"."rowid") = 0) AND (COUNT(DISTINCT "award"."rowid") = 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"."id") = 0) OR (COUNT(DISTINCT "award"."customPrimaryKey") = 0)
HAVING (COUNT(DISTINCT "player"."rowid") = 0) OR (COUNT(DISTINCT "award"."rowid") = 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"."id") = 0) OR (COUNT(DISTINCT "award"."customPrimaryKey") = 0))
HAVING NOT ((COUNT(DISTINCT "player"."rowid") = 0) OR (COUNT(DISTINCT "award"."rowid") = 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"."id") > 3)) OR (COUNT(DISTINCT "award"."customPrimaryKey") = 0)
HAVING (NOT (COUNT(DISTINCT "player"."rowid") > 3)) OR (COUNT(DISTINCT "award"."rowid") = 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"."id") \
SELECT "team".*, -COUNT(DISTINCT "player"."rowid") \
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"."id") + 2 \
SELECT "team".*, COUNT(DISTINCT "player"."rowid") + 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"."id") \
SELECT "team".*, 2 + COUNT(DISTINCT "player"."rowid") \
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"."id") + COUNT(DISTINCT "award"."customPrimaryKey") \
SELECT "team".*, COUNT(DISTINCT "player"."rowid") + COUNT(DISTINCT "award"."rowid") \
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"."id") - 2 \
SELECT "team".*, COUNT(DISTINCT "player"."rowid") - 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"."id") \
SELECT "team".*, 2 - COUNT(DISTINCT "player"."rowid") \
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"."id") - COUNT(DISTINCT "award"."customPrimaryKey") \
SELECT "team".*, COUNT(DISTINCT "player"."rowid") - COUNT(DISTINCT "award"."rowid") \
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"."id") * 2 \
SELECT "team".*, COUNT(DISTINCT "player"."rowid") * 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"."id") \
SELECT "team".*, 2 * COUNT(DISTINCT "player"."rowid") \
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"."id") * COUNT(DISTINCT "award"."customPrimaryKey") \
SELECT "team".*, COUNT(DISTINCT "player"."rowid") * COUNT(DISTINCT "award"."rowid") \
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"."id") / 2 \
SELECT "team".*, COUNT(DISTINCT "player"."rowid") / 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"."id") \
SELECT "team".*, 2 / COUNT(DISTINCT "player"."rowid") \
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"."id") / COUNT(DISTINCT "award"."customPrimaryKey") \
SELECT "team".*, COUNT(DISTINCT "player"."rowid") / COUNT(DISTINCT "award"."rowid") \
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 RowDecoder == Player {
extension QueryInterfaceRequest where T == Player {
func filter(teamName: String) -> QueryInterfaceRequest<Player> {
joining(required: PlayerWithOptionalTeam.team.filter(Column("name") == teamName))
}
@@ -128,18 +128,6 @@ 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, """
@@ -218,7 +206,8 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
let request = aTransform(aBase)
.including(required: abTransform(abBase)
.including(required: abaTransform(abaBase)))
try sqls.append(request.build(db).sql)
let sqlRequest = try SQLRequest(db, request: request)
sqls.append(sqlRequest.sql)
}
}
}
@@ -998,133 +998,4 @@ 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
""")
}
}
}
}
@@ -0,0 +1,468 @@
import XCTest
import GRDB
/// Test SQL generation
class AssociationHasManyFirstSQLTests: GRDBTestCase {
func testHasManyFirst() throws {
struct Child: TableRecord { }
struct Parent: TableRecord, EncodableRecord {
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
container["rowid"] = 2
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parent") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent")
}
do {
let association = Parent
.hasMany(Child.self)
.orderByPrimaryKey()
.first
try assertMatchSQL(db, Parent.all().including(required: association), """
SELECT "parent".*, "child".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
""")
try assertMatchSQL(db, Parent.all().including(optional: association), """
SELECT "parent".*, "child".*
FROM "parent"
LEFT JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
""")
try assertMatchSQL(db, Parent.all().joining(required: association), """
SELECT "parent".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
""")
try assertMatchSQL(db, Parent.all().joining(optional: association), """
SELECT "parent".*
FROM "parent"
LEFT JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
""")
try assertMatchSQL(db, Parent().request(for: association), """
SELECT * FROM "child"
WHERE "parentId" = 1
ORDER BY "id"
LIMIT 1
""")
}
}
}
func testHasManyFirstWithOneDeeperAssociation() throws {
struct Toy: TableRecord { }
struct Child: TableRecord { }
struct Parent: TableRecord, EncodableRecord {
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
container["rowid"] = 2
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parent") { t in
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
t.autoIncrementedPrimaryKey("id")
t.column("childId", .integer).references("child")
}
do {
let association = Parent
.hasMany(Child.self)
.orderByPrimaryKey()
.first
.joining(required: Child.hasOne(Toy.self))
try assertMatchSQL(db, Parent.all().including(required: association), """
SELECT "parent".*, "child".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
""")
// TODO: implement
// Not implemented: chaining a required association behind an optional association
// try assertMatchSQL(db, Parent.all().including(optional: association), """
// SELECT ...
// """)
try assertMatchSQL(db, Parent.all().joining(required: association), """
SELECT "parent".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
""")
// TODO: implement
// Not implemented: chaining a required association behind an optional association
// try assertMatchSQL(db, Parent.all().joining(optional: association), """
// SELECT ...
// """)
try assertMatchSQL(db, Parent().request(for: association), """
SELECT "child".*
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
WHERE "child"."parentId" = 1
ORDER BY "child"."id"
LIMIT 1
""")
}
do {
let association = Parent
.hasMany(Child.self)
.orderByPrimaryKey()
.first
.including(required: Child.hasOne(Toy.self))
try assertMatchSQL(db, Parent.all().including(required: association), """
SELECT "parent".*, "child".*, "toy".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
""")
try assertMatchSQL(db, Parent.all().joining(required: association), """
SELECT "parent".*, "toy".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
""")
try assertMatchSQL(db, Parent().request(for: association), """
SELECT "child".*, "toy".*
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
WHERE "child"."parentId" = 1
ORDER BY "child"."id"
LIMIT 1
""")
}
do {
let alias = TableAlias()
let association = Parent
.hasMany(Child.self)
.orderByPrimaryKey()
.filter(Column("id") == alias[Column("id")] + 1)
.first
.joining(required: Child.hasOne(Toy.self).filter(Column("id") == alias[Column("id")] * 2))
try assertMatchSQL(db, Parent.all().aliased(alias).including(required: association), """
SELECT "parent".*, "child".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON ("toy"."childId" = "child"."id") AND ("toy"."id" = ("parent"."id" * 2))
WHERE ("child"."parentId" = "parent"."id") AND ("child"."id" = ("parent"."id" + 1))
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON ("toy"."childId" = "child"."id") AND ("toy"."id" = ("parent"."id" * 2))
""")
try assertMatchSQL(db, Parent.all().aliased(alias).joining(required: association), """
SELECT "parent".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON ("toy"."childId" = "child"."id") AND ("toy"."id" = ("parent"."id" * 2))
WHERE ("child"."parentId" = "parent"."id") AND ("child"."id" = ("parent"."id" + 1))
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON ("toy"."childId" = "child"."id") AND ("toy"."id" = ("parent"."id" * 2))
""")
}
do {
let alias = TableAlias()
let association = Parent
.hasMany(Child.self)
.orderByPrimaryKey()
.filter(Column("id") == alias[Column("id")] + 1)
.first
.including(required: Child.hasOne(Toy.self).filter(Column("id") == alias[Column("id")] * 2))
try assertMatchSQL(db, Parent.all().aliased(alias).including(required: association), """
SELECT "parent".*, "child".*, "toy".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON ("toy"."childId" = "child"."id") AND ("toy"."id" = ("parent"."id" * 2))
WHERE ("child"."parentId" = "parent"."id") AND ("child"."id" = ("parent"."id" + 1))
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON ("toy"."childId" = "child"."id") AND ("toy"."id" = ("parent"."id" * 2))
""")
try assertMatchSQL(db, Parent.all().aliased(alias).joining(required: association), """
SELECT "parent".*, "toy".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON ("toy"."childId" = "child"."id") AND ("toy"."id" = ("parent"."id" * 2))
WHERE ("child"."parentId" = "parent"."id") AND ("child"."id" = ("parent"."id" + 1))
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON ("toy"."childId" = "child"."id") AND ("toy"."id" = ("parent"."id" * 2))
""")
}
}
}
func testHasManyFirstWithTwoDeeperAssociations() throws {
struct Vendor: TableRecord { }
struct Toy: TableRecord { }
struct Child: TableRecord { }
struct Parent: TableRecord, EncodableRecord {
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
container["rowid"] = 2
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parent") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "vendor") { t in
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
t.autoIncrementedPrimaryKey("id")
t.column("childId", .integer).references("child")
t.column("vendorId", .integer).references("vendor")
}
do {
let association = Parent
.hasMany(Child.self)
.orderByPrimaryKey()
.first
.joining(required: Child.hasOne(Toy.self).including(optional: Toy.belongsTo(Vendor.self)))
try assertMatchSQL(db, Parent.all().including(required: association), """
SELECT "parent".*, "child".*, "vendor".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
LEFT JOIN "vendor" ON "vendor"."id" = "toy"."vendorId"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
LEFT JOIN "vendor" ON "vendor"."id" = "toy"."vendorId"
""")
// TODO: implement
// Not implemented: chaining a required association behind an optional association
// try assertMatchSQL(db, Parent.all().including(optional: association), """
// SELECT ...
// """)
try assertMatchSQL(db, Parent.all().joining(required: association), """
SELECT "parent".*, "vendor".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
LEFT JOIN "vendor" ON "vendor"."id" = "toy"."vendorId"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
LEFT JOIN "vendor" ON "vendor"."id" = "toy"."vendorId"
""")
// TODO: implement
// Not implemented: chaining a required association behind an optional association
// try assertMatchSQL(db, Parent.all().joining(optional: association), """
// SELECT ...
// """)
try assertMatchSQL(db, Parent().request(for: association), """
SELECT "child".*, "vendor".*
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
LEFT JOIN "vendor" ON "vendor"."id" = "toy"."vendorId"
WHERE "child"."parentId" = 1
ORDER BY "child"."id"
LIMIT 1
""")
}
do {
let association = Parent
.hasMany(Child.self)
.orderByPrimaryKey()
.first
.including(required: Child.hasOne(Toy.self).including(optional: Toy.belongsTo(Vendor.self)))
try assertMatchSQL(db, Parent.all().including(required: association), """
SELECT "parent".*, "child".*, "toy".*, "vendor".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
LEFT JOIN "vendor" ON "vendor"."id" = "toy"."vendorId"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
LEFT JOIN "vendor" ON "vendor"."id" = "toy"."vendorId"
""")
try assertMatchSQL(db, Parent.all().joining(required: association), """
SELECT "parent".*, "toy".*, "vendor".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
LEFT JOIN "vendor" ON "vendor"."id" = "toy"."vendorId"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
LEFT JOIN "vendor" ON "vendor"."id" = "toy"."vendorId"
""")
try assertMatchSQL(db, Parent().request(for: association), """
SELECT "child".*, "toy".*, "vendor".*
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
LEFT JOIN "vendor" ON "vendor"."id" = "toy"."vendorId"
WHERE "child"."parentId" = 1
ORDER BY "child"."id"
LIMIT 1
""")
}
}
}
func testHasManyLast() throws {
struct Child: TableRecord { }
struct Parent: TableRecord, EncodableRecord {
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
container["rowid"] = 2
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parent") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent")
}
do {
let association = Parent
.hasMany(Child.self)
.orderByPrimaryKey()
.last
try assertMatchSQL(db, Parent.all().including(required: association), """
SELECT "parent".*, "child".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id" DESC
LIMIT 1)
""")
try assertMatchSQL(db, Parent.all().including(optional: association), """
SELECT "parent".*, "child".*
FROM "parent"
LEFT JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id" DESC
LIMIT 1)
""")
try assertMatchSQL(db, Parent.all().joining(required: association), """
SELECT "parent".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id" DESC
LIMIT 1)
""")
try assertMatchSQL(db, Parent.all().joining(optional: association), """
SELECT "parent".*
FROM "parent"
LEFT JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id" DESC
LIMIT 1)
""")
try assertMatchSQL(db, Parent().request(for: association), """
SELECT * FROM "child"
WHERE "parentId" = 1
ORDER BY "id" DESC
LIMIT 1
""")
}
}
}
}
@@ -0,0 +1,580 @@
import XCTest
import GRDB
/// Test SQL generation
// TODO: test request(for: hasManyThrough(hasMany.first, hasMany) (all comments of the last message in a chat)
class AssociationHasManyThroughFirstSQLTests: GRDBTestCase {
func testBelongsToHasMany() throws {
struct A: TableRecord, EncodableRecord {
static let b = belongsTo(B.self)
static let c = hasMany(C.self, through: b, using: B.c)
func encode(to container: inout PersistenceContainer) {
container["bId"] = 1
}
}
struct B: TableRecord {
static let c = hasMany(C.self)
}
struct C: TableRecord {
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
}
do {
let association = A.c.first
try assertMatchSQL(db, A.all().including(required: association), """
SELECT "a".*, "c".*
FROM "a"
JOIN "b" ON "b"."id" = "a"."bId"
JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
""")
try assertMatchSQL(db, A.all().including(optional: association), """
SELECT "a".*, "c".*
FROM "a"
LEFT JOIN "b" ON "b"."id" = "a"."bId"
LEFT JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
""")
try assertMatchSQL(db, A.all().joining(required: association), """
SELECT "a".*
FROM "a"
JOIN "b" ON "b"."id" = "a"."bId"
JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
""")
try assertMatchSQL(db, A.all().joining(optional: association), """
SELECT "a".*
FROM "a"
LEFT JOIN "b" ON "b"."id" = "a"."bId"
LEFT JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
""")
try assertMatchSQL(db, A().request(for: association), """
SELECT "c".*
FROM "c"
JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."id" = 1)
LIMIT 1
""")
}
}
}
func testHasOneHasMany() throws {
struct A: TableRecord, EncodableRecord {
static let b = hasOne(B.self)
static let c = hasMany(C.self, through: b, using: B.c)
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
}
}
struct B: TableRecord {
static let c = hasMany(C.self)
}
struct C: TableRecord {
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("aId").references("a")
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
}
do {
let association = A.c.first
try assertMatchSQL(db, A.all().including(required: association), """
SELECT "a".*, "c".*
FROM "a"
JOIN "b" ON "b"."aId" = "a"."id"
JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
""")
try assertMatchSQL(db, A.all().including(optional: association), """
SELECT "a".*, "c".*
FROM "a"
LEFT JOIN "b" ON "b"."aId" = "a"."id"
LEFT JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
""")
try assertMatchSQL(db, A.all().joining(required: association), """
SELECT "a".*
FROM "a"
JOIN "b" ON "b"."aId" = "a"."id"
JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
""")
try assertMatchSQL(db, A.all().joining(optional: association), """
SELECT "a".*
FROM "a"
LEFT JOIN "b" ON "b"."aId" = "a"."id"
LEFT JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
""")
try assertMatchSQL(db, A().request(for: association), """
SELECT "c".*
FROM "c"
JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."aId" = 1) LIMIT 1
""")
}
}
}
func testHasManyBelongsTo() throws {
struct A: TableRecord, EncodableRecord {
static let b = hasMany(B.self)
static let c = hasMany(C.self, through: b, using: B.c)
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
}
}
struct B: TableRecord {
static let c = belongsTo(C.self)
}
struct C: TableRecord {
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("cId").references("c")
t.column("aId").references("a")
}
do {
let association = A.c.first
try assertMatchSQL(db, A.all().including(required: association), """
SELECT "a".*, "c".*
FROM "a"
JOIN "b" ON "b"."id" = (
SELECT "b"."id"
FROM "b"
JOIN "c" ON "c"."id" = "b"."cId"
WHERE "b"."aId" = "a"."id"
LIMIT 1)
JOIN "c" ON "c"."id" = "b"."cId"
""")
try assertMatchSQL(db, A.all().including(optional: association), """
SELECT "a".*, "c".*
FROM "a"
LEFT JOIN "b" ON "b"."id" = (
SELECT "b"."id"
FROM "b"
LEFT JOIN "c" ON "c"."id" = "b"."cId"
WHERE "b"."aId" = "a"."id"
LIMIT 1)
LEFT JOIN "c" ON "c"."id" = "b"."cId"
""")
try assertMatchSQL(db, A.all().joining(required: association), """
SELECT "a".*
FROM "a"
JOIN "b" ON "b"."id" = (
SELECT "b"."id"
FROM "b"
JOIN "c" ON "c"."id" = "b"."cId"
WHERE "b"."aId" = "a"."id"
LIMIT 1)
JOIN "c" ON "c"."id" = "b"."cId"
""")
try assertMatchSQL(db, A.all().joining(optional: association), """
SELECT "a".*
FROM "a"
LEFT JOIN "b" ON "b"."id" = (
SELECT "b"."id"
FROM "b"
LEFT JOIN "c" ON "c"."id" = "b"."cId"
WHERE "b"."aId" = "a"."id"
LIMIT 1)
LEFT JOIN "c" ON "c"."id" = "b"."cId"
""")
try assertMatchSQL(db, A().request(for: association), """
SELECT "c".*
FROM "c"
JOIN "b" ON "b"."id" = (
SELECT "b"."id"
FROM "b"
WHERE ("b"."cId" = "c"."id") AND ("b"."aId" = 1)
LIMIT 1)
LIMIT 1
""")
}
}
}
func testHasManyHasOne() throws {
struct A: TableRecord, EncodableRecord {
static let b = hasMany(B.self)
static let c = hasMany(C.self, through: b, using: B.c)
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
}
}
struct B: TableRecord {
static let c = hasOne(C.self)
}
struct C: TableRecord {
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("aId").references("a")
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
}
do {
let association = A.c.first
try assertMatchSQL(db, A.all().including(required: association), """
SELECT "a".*, "c".*
FROM "a"
JOIN "b" ON "b"."id" = (
SELECT "b"."id"
FROM "b" JOIN "c"
ON "c"."bId" = "b"."id"
WHERE "b"."aId" = "a"."id"
LIMIT 1)
JOIN "c" ON "c"."bId" = "b"."id"
""")
try assertMatchSQL(db, A.all().including(optional: association), """
SELECT "a".*, "c".*
FROM "a"
LEFT JOIN "b" ON "b"."id" = (
SELECT "b"."id"
FROM "b"
LEFT JOIN "c" ON "c"."bId" = "b"."id"
WHERE "b"."aId" = "a"."id"
LIMIT 1)
LEFT JOIN "c" ON "c"."bId" = "b"."id"
""")
try assertMatchSQL(db, A.all().joining(required: association), """
SELECT "a".*
FROM "a"
JOIN "b" ON "b"."id" = (
SELECT "b"."id"
FROM "b"
JOIN "c" ON "c"."bId" = "b"."id"
WHERE "b"."aId" = "a"."id"
LIMIT 1)
JOIN "c" ON "c"."bId" = "b"."id"
""")
try assertMatchSQL(db, A.all().joining(optional: association), """
SELECT "a".*
FROM "a"
LEFT JOIN "b" ON "b"."id" = (
SELECT "b"."id"
FROM "b"
LEFT JOIN "c" ON "c"."bId" = "b"."id"
WHERE "b"."aId" = "a"."id"
LIMIT 1)
LEFT JOIN "c" ON "c"."bId" = "b"."id"
""")
try assertMatchSQL(db, A().request(for: association), """
SELECT "c".*
FROM "c"
JOIN "b" ON "b"."id" = (
SELECT "b"."id"
FROM "b"
WHERE ("b"."id" = "c"."bId") AND ("b"."aId" = 1)
LIMIT 1)
LIMIT 1
""")
}
}
}
func testHasManyThroughHasManyFirst() throws {
struct A: TableRecord, EncodableRecord {
static let b = belongsTo(B.self)
static let c = hasMany(C.self, through: b, using: B.c)
static let d = hasMany(D.self, through: c.first, using: C.d)
func encode(to container: inout PersistenceContainer) {
container["bId"] = 1
}
}
struct B: TableRecord {
static let c = hasMany(C.self)
}
struct C: TableRecord {
static let d = hasMany(D.self)
}
struct D: TableRecord {
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
}
try db.create(table: "d") { t in
t.autoIncrementedPrimaryKey("id")
t.column("cId").references("c")
}
do {
let association = A.d
try assertMatchSQL(db, A.all().including(required: association), """
SELECT "a".*, "d".*
FROM "a"
JOIN "b" ON "b"."id" = "a"."bId"
JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
JOIN "d" ON "d"."cId" = "c"."id"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
JOIN "d" ON "d"."cId" = "c"."id"
""")
try assertMatchSQL(db, A.all().including(optional: association), """
SELECT "a".*, "d".*
FROM "a"
LEFT JOIN "b" ON "b"."id" = "a"."bId"
LEFT JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
LEFT JOIN "d" ON "d"."cId" = "c"."id"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
LEFT JOIN "d" ON "d"."cId" = "c"."id"
""")
try assertMatchSQL(db, A.all().joining(required: association), """
SELECT "a".*
FROM "a"
JOIN "b" ON "b"."id" = "a"."bId"
JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
JOIN "d" ON "d"."cId" = "c"."id"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
JOIN "d" ON "d"."cId" = "c"."id"
""")
try assertMatchSQL(db, A.all().joining(optional: association), """
SELECT "a".*
FROM "a"
LEFT JOIN "b" ON "b"."id" = "a"."bId"
LEFT JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
LEFT JOIN "d" ON "d"."cId" = "c"."id"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
LEFT JOIN "d" ON "d"."cId" = "c"."id"
""")
// TODO: implement
// Not implemented: loading multiple records associated to a `first` or `last` to-one association
// try assertMatchSQL(db, A().request(for: association), """
// SELECT ...
// """)
}
}
}
func testAssociationFilteredByOtherAssociation() throws {
struct Pet: TableRecord {
static let child = belongsTo(Child.self)
}
struct Toy: TableRecord { }
struct Child: TableRecord {
static let toy = hasOne(Toy.self)
static let pets = hasMany(Pet.self)
}
struct Parent: TableRecord, EncodableRecord {
static let children = hasMany(Child.self)
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parent") { t in
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
t.column("childId", .integer).references("child")
}
try db.create(table: "pet") { t in
t.column("childId", .integer).references("child")
}
}
try dbQueue.inDatabase { db in
do {
let association = Parent.hasMany(
Pet.self,
through: Parent.children.joining(required: Child.toy),
using: Child.pets)
.first
try assertMatchSQL(db, Parent.all().including(required: association), """
SELECT "parent".*, "pet".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
JOIN "pet" ON "pet"."rowid" = (
SELECT "pet"."rowid"
FROM "pet"
WHERE "pet"."childId" = "child"."id"
LIMIT 1)
WHERE "child"."parentId" = "parent"."id"
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
JOIN "pet" ON "pet"."rowid" = (
SELECT "pet"."rowid"
FROM "pet"
WHERE "pet"."childId" = "child"."id"
LIMIT 1)
""")
try assertMatchSQL(db, Parent.all().joining(required: association), """
SELECT "parent".* FROM "parent"
JOIN "child"
ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
JOIN "pet" ON "pet"."rowid" = (
SELECT "pet"."rowid"
FROM "pet"
WHERE "pet"."childId" = "child"."id"
LIMIT 1)
WHERE "child"."parentId" = "parent"."id"
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
JOIN "pet" ON "pet"."rowid" = (
SELECT "pet"."rowid"
FROM "pet"
WHERE "pet"."childId" = "child"."id"
LIMIT 1)
""")
try assertMatchSQL(db, Parent().request(for: association), """
SELECT "pet".*
FROM "pet"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
WHERE ("child"."id" = "pet"."childId") AND ("child"."parentId" = 1)
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
LIMIT 1
""")
}
do {
#warning("TODO: generate correct SQL")
// let association = Parent.hasMany(
// Pet.self,
// through: Parent.children.filter(sql: "1 + 1"),
// using: Child.pets.joining(required: Pet.child.filter(sql: "1").joining(required: Child.toy)))
// .first
// try assertMatchSQL(db, Parent.all().including(required: association), """
// SELECT ...
// """)
// try assertMatchSQL(db, Parent.all().joining(required: association), """
// SELECT ...
// """)
// try assertMatchSQL(db, Parent().request(for: association), """
// SELECT ...
// """)
}
do {
let association = Parent.hasMany(
Pet.self,
through: Parent.children.filter(sql: "1 + 1"),
using: Child.pets)
.joining(required: Pet.child.filter(sql: "1").joining(required: Child.toy))
.first
#warning("TODO: generate correct SQL")
// try assertMatchSQL(db, Parent.all().including(required: association), """
// SELECT ...
// """)
// try assertMatchSQL(db, Parent.all().joining(required: association), """
// SELECT ...
// """)
try assertMatchSQL(db, Parent().request(for: association), """
SELECT "pet".*
FROM "pet"
JOIN "child" "child1" ON ("child1"."id" = "pet"."childId") AND (1)
JOIN "toy" ON "toy"."childId" = "child1"."id"
JOIN "child" "child2" ON "child2"."id" = (
SELECT "child"."id"
FROM "child"
WHERE ("child"."id" = "pet"."childId") AND (1 + 1) AND ("child"."parentId" = 1)
LIMIT 1)
LIMIT 1
""")
}
}
}
}
@@ -206,7 +206,8 @@ class AssociationHasOneSQLDerivationTests: GRDBTestCase {
let request = aTransform(aBase)
.including(required: abTransform(abBase)
.including(required: abaTransform(abaBase)))
try sqls.append(request.build(db).sql)
let sqlRequest = try SQLRequest(db, request: request)
sqls.append(sqlRequest.sql)
}
}
}
@@ -1,7 +1,7 @@
import XCTest
import Dispatch
import Foundation
@testable import GRDB
import GRDB
class DatabasePoolConcurrencyTests: GRDBTestCase {
@@ -267,8 +267,6 @@ 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
@@ -1075,8 +1073,6 @@ 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")
@@ -1160,8 +1156,6 @@ 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,6 +453,11 @@ 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,49 +3,29 @@ import XCTest
@testable import GRDB
class DatabaseValueConvertibleEscapingTests: GRDBTestCase {
func testNull() throws {
try makeDatabaseQueue().inDatabase { db in
try XCTAssertEqual(DatabaseValue.null.quotedSQL(db), "NULL")
}
func testText() {
XCTAssertEqual("".databaseValue.quotedSQL(), "''")
XCTAssertEqual("foo".databaseValue.quotedSQL(), "'foo'")
XCTAssertEqual("\"foo\"".databaseValue.quotedSQL(), "'\"foo\"'")
XCTAssertEqual("'foo'".databaseValue.quotedSQL(), "'''foo'''")
}
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 testInteger() {
XCTAssertEqual(0.databaseValue.quotedSQL(), "0")
XCTAssertEqual(Int64.min.databaseValue.quotedSQL(), "-9223372036854775808")
XCTAssertEqual(Int64.max.databaseValue.quotedSQL(), "9223372036854775807")
}
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 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 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"#)
}
func testBlob() {
XCTAssertEqual(Data().databaseValue.quotedSQL(), "X''")
XCTAssertEqual("foo".data(using: .utf8)!.databaseValue.quotedSQL(), "X'666F6F'")
}
}
@@ -1053,39 +1053,42 @@ extension FetchableRecordDecodableTests {
}
}
func testMissingKeys1() throws {
struct A: Decodable { }
struct B: Decodable { }
struct C: Decodable { }
// 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 { }
struct Composed: Decodable, FetchableRecord {
var a: A
var b: B?
var c: C?
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")
}
// 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
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
}
}
// 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")
// }
// }
}
+31 -21
View File
@@ -136,44 +136,54 @@ class GRDBTestCase: XCTestCase {
XCTAssertEqual(recordDict, rowDict, file: file, line: line)
}
// Compare SQL strings (ignoring leading and trailing white space and semicolons.
/// Compares SQL strings (ignoring leading and trailing white space and semicolons).
func assertEqualSQL(_ lhs: String, _ rhs: String, file: StaticString = #file, line: UInt = #line) {
// Trim white space and ";"
let cs = CharacterSet.whitespacesAndNewlines.union(CharacterSet(charactersIn: ";"))
XCTAssertEqual(lhs.trimmingCharacters(in: cs), rhs.trimmingCharacters(in: cs), file: file, line: line)
}
// Compare SQL strings (ignoring leading and trailing white space and semicolons.
/// Compares 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 {
try request.makeStatement(db).makeCursor().next()
let request = try request.makePreparedRequest(db, forSingleResult: false)
try request.statement.makeCursor().next()
assertEqualSQL(lastSQLQuery, sql, file: file, line: line)
}
// Compare SQL strings (ignoring leading and trailing white space and semicolons.
/// Compares SQL strings (ignoring leading and trailing white space and semicolons).
func assertEqualSQL<Request: FetchRequest>(_ databaseReader: DatabaseReader, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws {
try databaseReader.unsafeRead { db in
try assertEqualSQL(db, request, sql, file: file, line: line)
}
}
func sql<Request: FetchRequest>(_ databaseReader: DatabaseReader, _ request: Request) -> String {
try! databaseReader.unsafeRead { db in
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
/// Compares SQL strings (ignoring ALL white space and semicolons).
func assertMatchSQL(_ lhs: String, _ rhs: String, file: StaticString = #file, line: UInt = #line) {
let cs = CharacterSet.whitespacesAndNewlines.union(CharacterSet(charactersIn: ";"))
let lScalars = Array(lhs.unicodeScalars.filter { !cs.contains($0) })
let rScalars = Array(rhs.unicodeScalars.filter { !cs.contains($0) })
XCTAssert(lScalars == rScalars, "assertMatchSQL failed: \(lhs) does not match \(rhs)", file: file, line: line)
}
/// 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)
/// Compares SQL strings (ignoring ALL white space and semicolons).
func assertMatchSQL<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()
assertMatchSQL(lastSQLQuery, sql, file: file, line: line)
}
/// Compares SQL strings (ignoring ALL white space and semicolons).
func assertMatchSQL<Request: FetchRequest>(_ databaseReader: DatabaseReader, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws {
try databaseReader.unsafeRead { db in
try assertMatchSQL(db, request, sql, file: file, line: line)
}
}
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()
return lastSQLQuery
}
}
}
+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 XCTAssertTrue(db.table("persons", hasUniqueKey: ["id", "email"]))
try XCTAssertFalse(db.table("persons", hasUniqueKey: ["id", "email"])) // TODO: is it expected?
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)")
+13 -17
View File
@@ -18,12 +18,12 @@ let expectedSQL = """
ORDER BY t1.id
"""
let testedLiteral: SQLLiteral = """
let testedSQL = """
SELECT
\(columnsOf: T1.self),
\(columnsOf: T2.self, tableAlias: "t2Left"),
\(columnsOf: T2.self, tableAlias: "t2Right"),
\(columnsOf: T3.self),
\(T1.selectionSQL()),
\(T2.selectionSQL(alias: "t2Left")),
\(T2.selectionSQL(alias: "t2Right")),
\(T3.selectionSQL()),
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>(literal: testedLiteral).adapted { db in
SQLRequest<FlatModel>(sql: testedSQL).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>(literal: testedLiteral).adapted { db in
SQLRequest<CodableFlatModel>(sql: testedSQL).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>(literal: testedLiteral).adapted { db in
SQLRequest<CodableFlatModel>(sql: testedSQL).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>(literal: testedLiteral).adapted { db in
SQLRequest<CodableFlatModel>(sql: testedSQL).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>(literal: testedLiteral).adapted { db in
SQLRequest<CodableNestedModel>(sql: testedSQL).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 SQLRequest<Row>(literal: testedLiteral).fetchAll(db)
let rows = try Row.fetchAll(db, sql: expectedSQL)
XCTAssertEqual(rows.count, 3)
XCTAssertEqual(rows[0], [
// t1.*
@@ -292,17 +292,13 @@ class JoinSupportTests: GRDBTestCase {
}
func testTestedSQL() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let (testedSQL, _) = try testedLiteral.build(db)
XCTAssertEqual(testedSQL, expectedSQL)
}
XCTAssertEqual(testedSQL, expectedSQL)
}
func testSplittingRowAdapters() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = SQLRequest<Row>(literal: testedLiteral).adapted { db in
let request = SQLRequest<Row>(sql: testedSQL).adapted { db in
let adapters = try splittingRowAdapters(columnCounts: [
T1.numberOfSelectedColumns(db),
T2.numberOfSelectedColumns(db),
@@ -229,7 +229,7 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase {
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."id") = 0)
HAVING COUNT(DISTINCT "player"."rowid") = 0)
""")
}
do {
@@ -456,7 +456,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."id") = 0)
HAVING COUNT(DISTINCT "player"."rowid") = 0)
""")
}
do {
@@ -195,41 +195,6 @@ 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()
@@ -504,28 +469,6 @@ 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,7 +386,8 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = MinimalRowID.orderByPrimaryKey()
try assertEqualSQL(db, request, "SELECT * FROM \"minimalRowIDs\" ORDER BY \"id\"")
let sqlRequest = try SQLRequest(db, request: request)
XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"minimalRowIDs\" ORDER BY \"id\"")
}
}
@@ -402,7 +402,8 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = MinimalSingle.orderByPrimaryKey()
try assertEqualSQL(db, request, "SELECT * FROM \"minimalSingles\" ORDER BY \"UUID\"")
let sqlRequest = try SQLRequest(db, request: request)
XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"minimalSingles\" ORDER BY \"UUID\"")
}
}
@@ -472,7 +472,8 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = Person.orderByPrimaryKey()
try assertEqualSQL(db, request, "SELECT *, \"rowid\" FROM \"persons\" ORDER BY \"rowid\"")
let sqlRequest = try SQLRequest(db, request: request)
XCTAssertEqual(sqlRequest.sql, "SELECT *, \"rowid\" FROM \"persons\" ORDER BY \"rowid\"")
}
}
@@ -425,7 +425,8 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = Citizenship.orderByPrimaryKey()
try assertEqualSQL(db, request, "SELECT * FROM \"citizenships\" ORDER BY \"personName\", \"countryName\"")
let sqlRequest = try SQLRequest(db, request: request)
XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"citizenships\" ORDER BY \"personName\", \"countryName\"")
}
}
@@ -120,7 +120,8 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = Item.orderByPrimaryKey()
try assertEqualSQL(db, request, "SELECT * FROM \"items\" ORDER BY \"rowid\"")
let sqlRequest = try SQLRequest(db, request: request)
XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"items\" ORDER BY \"rowid\"")
}
}
@@ -468,7 +468,8 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = Person.orderByPrimaryKey()
try assertEqualSQL(db, request, "SELECT * FROM \"persons\" ORDER BY \"id\"")
let sqlRequest = try SQLRequest(db, request: request)
XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"persons\" ORDER BY \"id\"")
}
}
@@ -416,7 +416,8 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = Pet.orderByPrimaryKey()
try assertEqualSQL(db, request, "SELECT * FROM \"pets\" ORDER BY \"UUID\"")
let sqlRequest = try SQLRequest(db, request: request)
XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"pets\" ORDER BY \"UUID\"")
}
}
@@ -409,7 +409,8 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = Email.orderByPrimaryKey()
try assertEqualSQL(db, request, "SELECT * FROM \"emails\" ORDER BY \"email\"")
let sqlRequest = try SQLRequest(db, request: request)
XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"emails\" ORDER BY \"email\"")
}
}
+16 -20
View File
@@ -3,27 +3,23 @@ import XCTest
@testable import GRDB
class SQLExpressionLiteralTests: GRDBTestCase {
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 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 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))")
}
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))")
}
}
+331 -546
View File
@@ -2,134 +2,106 @@ import XCTest
@testable import GRDB
class SQLLiteralTests: GRDBTestCase {
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 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 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 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 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 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 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 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 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 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 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])
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])
}
}
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() 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"]),
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"]),
])
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"])
}
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"])
}
}
@@ -165,476 +137,289 @@ class SQLLiteralTests: GRDBTestCase {
}
extension SQLLiteralTests {
func testLiteralInitializer() throws {
try makeDatabaseQueue().inDatabase { db in
let query = SQLLiteral("""
SELECT * FROM player
WHERE id = \(1)
""")
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT * FROM player
WHERE id = ?
""")
XCTAssertEqual(arguments, [1])
}
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() throws {
try makeDatabaseQueue().inDatabase { db in
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 *
\(sql: "FROM player")
\(sql: "WHERE score > \(1000)")
\(sql: "AND \("name") = :name", arguments: ["name": "Arthur"])
SELECT \(AllColumns())
FROM player
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
XCTAssertEqual(query.sql, """
SELECT *
FROM player
WHERE score > 1000
AND name = :name
""")
XCTAssertEqual(arguments, ["name": "Arthur"])
XCTAssert(query.arguments.isEmpty)
}
}
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
do {
// Existential
let query: SQLLiteral = """
SELECT
\(a),
\(a + 1),
\(2 * (a + 1)),
\(a < b),
\(integer),
\(optionalInteger),
\(nilInteger),
\(a == nilInteger)
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT
"a",
"a" + ?,
? * ("a" + ?),
"a" < "b",
?,
?,
NULL,
"a" IS NULL
""")
XCTAssertEqual(arguments, [1, 2, 1, 1, 2])
}
}
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])
}
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)
}
}
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])
}
}
func testAliasedExpressionInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
let query: SQLLiteral = """
SELECT \(Column("name").forKey("foo")), \(1.databaseValue.forKey("bar"))
SELECT \(AllColumns() as SQLSelectable)
FROM player
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT "name" AS "foo", ? AS "bar"
XCTAssertEqual(query.sql, """
SELECT *
FROM player
""")
XCTAssertEqual(arguments, [1])
XCTAssert(query.arguments.isEmpty)
}
}
func testCodingKeyInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
enum CodingKeys: String, CodingKey {
case name
func testTableInterpolation() {
struct Player: TableRecord { }
do {
let query: SQLLiteral = """
SELECT *
FROM \(Player.self)
"""
XCTAssertEqual(query.sql, """
SELECT *
FROM "player"
""")
XCTAssert(query.arguments.isEmpty)
}
do {
let query: SQLLiteral = """
INSERT INTO \(tableOf: Player()) DEFAULT VALUES
"""
XCTAssertEqual(query.sql, """
INSERT INTO "player" DEFAULT VALUES
""")
XCTAssert(query.arguments.isEmpty)
}
}
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
}
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 testCodingKeyColumnInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
enum CodingKeys: String, CodingKey, ColumnExpression {
case name
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> V? {
nil
}
let query: SQLLiteral = """
SELECT \(CodingKeys.name)
FROM player
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT "name"
FROM player
""")
XCTAssert(arguments.isEmpty)
}
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 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 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 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 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 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 testCodingKeyInterpolation() {
enum CodingKeys: String, CodingKey {
case name
}
let query: SQLLiteral = """
SELECT \(CodingKeys.name)
FROM player
"""
XCTAssertEqual(query.sql, """
SELECT "name"
FROM player
""")
XCTAssert(query.arguments.isEmpty)
}
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 testCodingKeyColumnInterpolation() {
enum CodingKeys: String, CodingKey, ColumnExpression {
case name
}
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 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 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 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 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 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 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 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 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 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 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 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 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 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 testQualifiedSQLInterpolation() throws {
@@ -665,8 +450,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")
+67 -40
View File
@@ -47,19 +47,49 @@ 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"]))
let (sql, arguments) = try request.build(db)
XCTAssertEqual(sql, """
XCTAssertEqual(request.sql, """
SELECT ?
""")
XCTAssertEqual(arguments, ["O'Brien"])
let string = try request.fetchOne(db)!
XCTAssertEqual(string, "O'Brien")
}
@@ -71,13 +101,9 @@ class SQLRequestTests: GRDBTestCase {
let request = SQLRequest<String>("""
SELECT \("O'Brien")
""")
let (sql, arguments) = try request.build(db)
XCTAssertEqual(sql, """
XCTAssertEqual(request.sql, """
SELECT ?
""")
XCTAssertEqual(arguments, ["O'Brien"])
let string = try request.fetchOne(db)!
XCTAssertEqual(string, "O'Brien")
}
@@ -89,13 +115,9 @@ class SQLRequestTests: GRDBTestCase {
let request = SQLRequest<String>(literal: """
SELECT \("O'Brien")
""")
let (sql, arguments) = try request.build(db)
XCTAssertEqual(sql, """
XCTAssertEqual(request.sql, """
SELECT ?
""")
XCTAssertEqual(arguments, ["O'Brien"])
let string = try request.fetchOne(db)!
XCTAssertEqual(string, "O'Brien")
}
@@ -152,79 +174,84 @@ class SQLRequestTests: GRDBTestCase {
do {
let request = Player.filter(id: 42)
let (sql, arguments) = try request.build(db)
XCTAssertEqual(sql, """
XCTAssertEqual(request.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])
let (sql, arguments) = try request.build(db)
XCTAssertEqual(sql, """
XCTAssertEqual(request.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: [])
let (sql, arguments) = try request.build(db)
XCTAssertEqual(sql, """
XCTAssertEqual(request.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])
let (sql, arguments) = try request.build(db)
XCTAssertEqual(sql, """
XCTAssertEqual(request.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: [])
let (sql, arguments) = try request.build(db)
XCTAssertEqual(sql, """
XCTAssertEqual(request.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, 4],
records: [0, 1, 1, 2, 3, 2],
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: "INSERT INTO t DEFAULT VALUES")
try db.execute(sql: "DELETE FROM t WHERE id = 2")
})
}
@@ -30,7 +30,7 @@ class ValueObservationCountTests: GRDBTestCase {
try assertValueObservation(
ValueObservation.tracking(T.fetchCount).removeDuplicates(),
records: [0, 1, 2, 3, 4],
records: [0, 1, 2, 3, 2],
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: "INSERT INTO t DEFAULT VALUES")
try db.execute(sql: "DELETE FROM t WHERE id = 2")
})
}
}
@@ -77,8 +77,7 @@ class ValueObservationRecordTests: GRDBTestCase {
Player(id: 1, name: "foo"),
Player(id: 1, name: "foo"),
Player(id: 2, name: "bar"),
nil,
Player(id: 3, name: "toto")],
nil],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
},
@@ -92,7 +91,6 @@ 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
@@ -105,8 +103,7 @@ class ValueObservationRecordTests: GRDBTestCase {
nil,
Player(id: 1, name: "foo"),
Player(id: 2, name: "bar"),
nil,
Player(id: 3, name: "toto")],
nil],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
},
@@ -120,7 +117,6 @@ class ValueObservationRecordTests: GRDBTestCase {
return .commit
}
try db.execute(sql: "DELETE FROM t")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'toto')")
})
}
}
+16 -37
View File
@@ -378,13 +378,6 @@ 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,
@@ -411,7 +404,7 @@ extension GRDBTestCase {
try writer.writeWithoutTransaction(recordedUpdates)
let expectation = recorder.next(expectedValues.count)
let values = try wait(for: expectation, timeout: timeout)
let values = try wait(for: expectation, timeout: 0.3)
XCTAssertEqual(
values, expectedValues,
"\(#function), \(writer), \(scheduler)", file: file, line: line)
@@ -441,7 +434,7 @@ extension GRDBTestCase {
}
let expectation = recorder.next(expectedValues.count)
let values = try wait(for: expectation, timeout: timeout)
let values = try wait(for: expectation, timeout: 0.3)
XCTAssertEqual(
values, expectedValues,
"\(#function), \(writer), \(scheduler)", file: file, line: line)
@@ -466,28 +459,17 @@ extension GRDBTestCase {
try writer.writeWithoutTransaction(recordedUpdates)
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)
}
let expectation = recorder
.prefix(expectedValues.count + 2 /* pool may perform double initial fetch */)
.inverted
let values = try wait(for: expectation, timeout: 0.3)
if scheduler.immediateInitialValue() {
XCTAssertEqual(recordedValues.first, expectedValues.first)
XCTAssertEqual(values.first, expectedValues.first)
}
assertValueObservationRecordingMatch(
recorded: recordedValues,
recorded: values,
expected: expectedValues,
"\(#function), \(writer), \(scheduler)", file: file, line: line)
}
@@ -521,14 +503,18 @@ extension GRDBTestCase {
if waitForLast {
// Optimization!
let expectation = recorder.prefix(until: { $0 == lastExpectedValue } )
recordedValues = try wait(for: expectation, timeout: timeout)
recordedValues = try wait(for: expectation, timeout: 1)
} 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 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
}
XCTAssertEqual(recordedValues.first, expectedValues.first)
@@ -595,13 +581,6 @@ 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,
@@ -615,7 +594,7 @@ extension GRDBTestCase {
scheduling: scheduler,
onError: { _ in testErrorDispatching() })
let (_, error) = try wait(for: recorder.failure(), timeout: timeout)
let (_, error) = try wait(for: recorder.failure(), timeout: 0.3)
if let error = error as? Failure {
try testFailure(error, writer)
} else {
@@ -61,8 +61,7 @@ class ValueObservationRowTests: GRDBTestCase {
["id":1, "name":"foo"],
["id":1, "name":"foo"],
["id":2, "name":"bar"],
nil,
["id":3, "name":"toto"]],
nil],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
},
@@ -76,7 +75,6 @@ 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(
@@ -85,8 +83,7 @@ class ValueObservationRowTests: GRDBTestCase {
nil,
["id":1, "name":"foo"],
["id":2, "name":"bar"],
nil,
["id":3, "name":"toto"]],
nil],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
},
@@ -100,7 +97,6 @@ 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 = 4
notificationExpectation.expectedFulfillmentCount = 3
notificationExpectation.isInverted = true
struct TestError: Error { }
@@ -62,7 +62,7 @@ class ValueObservationTests: GRDBTestCase {
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
waitForExpectations(timeout: 0.3, 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: 1, handler: nil)
waitForExpectations(timeout: 0.2, 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: 1, handler: nil)
waitForExpectations(timeout: 0.2, handler: nil)
}
try test(makeDatabaseQueue())